Programs & Examples On #Clientid

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Try change update="insTable:display" to update="display". I believe you cannot prefix the id with the form ID like that.

How to get CSS to select ID that begins with a string (not in Javascript)?

I noticed that there is another CSS selector that does the same thing . The syntax is as follows :

[id|="name_id"]

This will select all elements ID which begins with the word enclosed in double quotes.

Casting int to bool in C/C++

The following cites the C11 standard (final draft).

6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

bool (mapped by stdbool.h to the internal name _Bool for C) itself is an unsigned integer type:

... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

According to 6.2.5p2:

An object declared as type _Bool is large enough to store the values 0 and 1.

AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool for C++ and _Bool for C.

Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool behaves as in C++.

error: invalid type argument of ‘unary *’ (have ‘int’)

I have reformatted your code.

The error was situated in this line :

printf("%d", (**c));

To fix it, change to :

printf("%d", (*c));

The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.

In addition, the () was optional.

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int *c = NULL;

    a = &b;
    c = &a;

    printf("%d", *c);

    return 0;
} 

EDIT :

The line :

c = &a;

must be replaced by :

c = a;

It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :

10

EDIT 2:

If you want to use a double * :

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int **c = NULL;

    a = &b;
    c = &a;

    printf("%d", **c);

    return 0;
} 

Output:

10

apache server reached MaxClients setting, consider raising the MaxClients setting

Here's an approach that could resolve your problem, and if not would help with troubleshooting.

  1. Create a second Apache virtual server identical to the current one

  2. Send all "normal" user traffic to the original virtual server

  3. Send special or long-running traffic to the new virtual server

Special or long-running traffic could be report-generation, maintenance ops or anything else you don't expect to complete in <<1 second. This can happen serving APIs, not just web pages.

If your resource utilization is low but you still exceed MaxClients, the most likely answer is you have new connections arriving faster than they can be serviced. Putting any slow operations on a second virtual server will help prove if this is the case. Use the Apache access logs to quantify the effect.

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

How to loop over a Class attributes in Java?

Here is a solution which sorts the properties alphabetically and prints them all together with their values:

public void logProperties() throws IllegalArgumentException, IllegalAccessException {
  Class<?> aClass = this.getClass();
  Field[] declaredFields = aClass.getDeclaredFields();
  Map<String, String> logEntries = new HashMap<>();

  for (Field field : declaredFields) {
    field.setAccessible(true);

    Object[] arguments = new Object[]{
      field.getName(),
      field.getType().getSimpleName(),
      String.valueOf(field.get(this))
    };

    String template = "- Property: {0} (Type: {1}, Value: {2})";
    String logMessage = System.getProperty("line.separator")
            + MessageFormat.format(template, arguments);

    logEntries.put(field.getName(), logMessage);
  }

  SortedSet<String> sortedLog = new TreeSet<>(logEntries.keySet());

  StringBuilder sb = new StringBuilder("Class properties:");

  Iterator<String> it = sortedLog.iterator();
  while (it.hasNext()) {
    String key = it.next();
    sb.append(logEntries.get(key));
  }

  System.out.println(sb.toString());
}

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Importing a long list of constants to a Python file

Sure, you can put your constants into a separate module. For example:

const.py:

A = 12
B = 'abc'
C = 1.2

main.py:

import const

print const.A, const.B, const.C

Note that as declared above, A, B and C are variables, i.e. can be changed at run time.

How can I check if a date is the same day as datetime.today()?

You can set the hours, minutes, seconds and microseconds to whatever you like

datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()s of the times

Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace() once vs hundreds of calls to date()

Spring Boot + JPA : Column name annotation ignored

For hibernate5 I solved this issue by puting next lines in my application.properties file:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

The Philippe solution but cleaner:

My subtraction data is: '2018-09-22T11:05:00.000Z'

import datetime
import pandas as pd

df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)

How do I list one filename per output line in Linux?

Easy, as long as your filenames don't include newlines:

find . -maxdepth 1

If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):

find . -maxdepth 1 -print0

Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort's -z. Your own script similarly would need to account for this.

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

Clearing localStorage in javascript?

First things first, you need to check to make sure that localStorage is enabled. I would recommend doing it like this:

var localStorageEnabled = false;
try { localStorageEnabled = !!localStorage; } catch(e) {};

Yes, you can (in some cases) just check to see if the localStorage is a member of the window object. However, there are iframe sandboxing options (among other things) that will throw an exception if you even attempt to access the index 'localStorage'. Thus, for best-practices reasons, this is the best way to check to see if the localStorage is enabled. Then, you can just clear the localStorage like so.

if (localStorageEnabled) localStorage.clear();

For example, you could clear the localStorage after an error occurs in webkit browsers like so.

// clears the local storage upon error
if (localStorageEnabled)
  window.onerror = localStorage.clear.bind(localStorage);

In the above example, you need the .bind(window) because without it, the localStorage.clear function will run in the context of the window object, instead of the localStorage object making it silently fail. To demonstrate this, look at the below example:

window.onerror = localStorage.clear;

is the same as:

window.onerror = function(){
    localStorage.clear.call(window);
}

How to check if a Ruby object is a Boolean

If your code can sensibly be written as a case statement, this is pretty decent:

case mybool
when TrueClass, FalseClass
  puts "It's a bool!"
else
  puts "It's something else!"
end

How can I create and style a div using JavaScript?

You can just use the method below:

document.write()

It is very simple, in the doc below I explain

_x000D_
_x000D_
document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
_x000D_
.div {
  background-color: red;
  padding: 5px;
  color: #fff;
  font-family: Arial;
  cursor: pointer;
}

.div:hover {
  background-color: blue;
  padding: 10px;
}

.div:hover:before {
  content: 'Hover! ';
}

.div:active {
  background-color: green;
  padding: 15px;
}

.div:active:after {
  content: ' Active! or clicked...';
}
_x000D_
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>
_x000D_
_x000D_
_x000D_

Explicitly select items from a list or tuple

list( myBigList[i] for i in [87, 342, 217, 998, 500] )

I compared the answers with python 2.5.2:

  • 19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]

  • 20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))

  • 22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)

  • 24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )

Note that in Python 3, the 1st was changed to be the same as the 4th.


Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:

>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])

The tuple doesn't work the same way as those are slices.

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

How to generate the JPA entity Metamodel?

Please take a look at jpa-metamodels-with-maven-example.

Hibernate

  • We need org.hibernate.org:hibernate-jpamodelgen.
  • The processor class is org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor.

Hibernate as a dependency

    <dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-jpamodelgen</artifactId>
      <version>${version.hibernate-jpamodelgen}</version>
      <scope>provided</scope>
    </dependency>

Hibernate as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <compilerArguments>-AaddGeneratedAnnotation=false</compilerArguments> <!-- suppress java.annotation -->
              <processors>
                <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>${version.hibernate-jpamodelgen}</version>
          </dependency>
        </dependencies>
      </plugin>

OpenJPA

  • We need org.apache.openjpa:openjpa.
  • The processor class is org.apache.openjpa.persistence.meta.AnnotationProcessor6.
  • OpenJPA seems require additional element <openjpa.metamodel>true<openjpa.metamodel>.

OpenJPA as a dependency

  <dependencies>
    <dependency>
      <groupId>org.apache.openjpa</groupId>
      <artifactId>openjpa</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <compilerArgs>
            <arg>-Aopenjpa.metamodel=true</arg>
          </compilerArgs>
        </configuration>
      </plugin>
    </plugins>
  </build>

OpenJPA as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.apache.openjpa.persistence.meta.AnnotationProcessor6</processor>
              </processors>
              <optionMap>
                <openjpa.metamodel>true</openjpa.metamodel>
              </optionMap>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>${version.openjpa}</version>
          </dependency>
        </dependencies>
      </plugin>

EclipseLink

  • We need org.eclipse.persistence:org.eclipse.persistence.jpa.modelgen.processor.
  • The processor class is org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor.
  • EclipseLink requires persistence.xml.

EclipseLink as a dependency

  <dependencies>
    <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
      <scope>provided</scope>
    </dependency>

EclipseLink as a processor

    <plugins>
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
              </processors>
              <compilerArguments>-Aeclipselink.persistencexml=src/main/resources-${environment.id}/META-INF/persistence.xml</compilerArguments>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>${version.eclipselink}</version>
          </dependency>
        </dependencies>
      </plugin>

DataNucleus

  • We need org.datanucleus:datanucleus-jpa-query.
  • The processor class is org.datanucleus.jpa.query.JPACriteriaProcessor.

DataNucleus as a dependency

  <dependencies>
    <dependency>
      <groupId>org.datanucleus</groupId>
      <artifactId>datanucleus-jpa-query</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>

DataNucleus as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.datanucleus.jpa.query.JPACriteriaProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-jpa-query</artifactId>
            <version>${version.datanucleus}</version>
          </dependency>
        </dependencies>
      </plugin>

Get unique values from arraylist in java

Here's straightforward way without resorting to custom comparators or stuff like that:

Set<String> gasNames = new HashSet<String>();
List<YourRecord> records = ...;

for(YourRecord record : records) {
  gasNames.add(record.getGasName());
}

// now gasNames is a set of unique gas names, which you could operate on:
List<String> sortedGasses = new ArrayList<String>(gasNames);
Collections.sort(sortedGasses);

Note: Using TreeSet instead of HashSet would give directly sorted arraylist and above Collections.sort could be skipped, but TreeSet is otherwise less efficent, so it's often better, and rarely worse, to use HashSet even when sorting is needed.

What is null in Java?

Bytecode representation

Java's null has direct JVM support: three instructions are used to implement it:

  • aconst_null: e.g. to set a variable to null as in Object o = null;
  • ifnull and ifnonnull: e.g. to compare an object to null as in if (o == null)

Chapter 6 "The Java Virtual Machine Instruction Set " then mentions the effects of null on other instructions: it throws a NullPointerException for many of them.

2.4. "Reference Types and Values" also mentions null in generic terms:

A reference value may also be the special null reference, a reference to no object, which will be denoted here by null. The null reference initially has no run-time type, but may be cast to any type. The default value of a reference type is null.

Onclick on bootstrap button

You can use 'onclick' attribute like this :

<a ... href="javascript: onclick();" ...>...</a>

Carousel with Thumbnails in Bootstrap 3.0

  1. Use the carousel's indicators to display thumbnails.
  2. Position the thumbnails outside of the main carousel with CSS.
  3. Set the maximum height of the indicators to not be larger than the thumbnails.
  4. Whenever the carousel has slid, update the position of the indicators, positioning the active indicator in the middle of the indicators.

I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.

Also, my templating engine is smarty, but I'm sure you get the idea.

The meat...

Updating the indicators:

<ol class="carousel-indicators">
    {assign var='walker' value=0}
    {foreach from=$item["imagearray"] key="key" item="value"}
        <li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
            <img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
        </li>

        {assign var='walker' value=1 + $walker}
    {/foreach}
</ol>

Changing the CSS related to the indicators:

.carousel-indicators {
    bottom:-50px;
    height: 36px;
    overflow-x: hidden;
    white-space: nowrap;
}

.carousel-indicators li {
    text-indent: 0;
    width: 34px !important;
    height: 34px !important;
    border-radius: 0;
}

.carousel-indicators li img {
    width: 32px;
    height: 32px;
    opacity: 0.5;
}

.carousel-indicators li:hover img, .carousel-indicators li.active img {
    opacity: 1;
}

.carousel-indicators .active {
    border-color: #337ab7;
}

When the carousel has slid, update the list of thumbnails:

$('#myCarousel').on('slid.bs.carousel', function() {
    var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width(); 
    var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
    var toScroll = newIndicatorPosition + indicatorPosition;
    var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
    if (adjustedScroll < 0)
        adjustedScroll = 0;

    if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
        adjustedScroll = widthEstimate - $(".carousel-indicators").width();

    $('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);

    indicatorPosition = adjustedScroll;
});

And, when your page loads, set the initial scroll position of the thumbnails:

var indicatorPosition = 0;

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

Nested lists python

If you really need the indices you can just do what you said again for the inner list:

l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
    for index2 in xrange(len(l[index1])):
        print index1, index2, l[index1][index2]

But it is more pythonic to iterate through the list itself:

for inner_l in l:
    for item in inner_l:
        print item

If you really need the indices you can also use enumerate:

for index1, inner_l in enumerate(l):
    for index2, item in enumerate(inner_l):
        print index1, index2, item, l[index1][index2]

Encoding Error in Panda read_csv

Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' (these are some of the various encodings found on Windows).

Quick way to retrieve user information Active Directory

You can call UserPrincipal.FindByIdentity inside System.DirectoryServices.AccountManagement:

using System.DirectoryServices.AccountManagement;

using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
    var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}

Simple way to repeat a string

I wanted a function to create a comma-delimited list of question marks for JDBC purposes, and found this post. So, I decided to take two variants and see which one performed better. After 1 million iterations, the garden-variety StringBuilder took 2 seconds (fun1), and the cryptic supposedly more optimal version (fun2) took 30 seconds. What's the point of being cryptic again?

private static String fun1(int size) {
    StringBuilder sb = new StringBuilder(size * 2);
    for (int i = 0; i < size; i++) {
        sb.append(",?");
    }
    return sb.substring(1);
}

private static String fun2(int size) {
    return new String(new char[size]).replaceAll("\0", ",?").substring(1);
}

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had the issue when I put jcenter() before google() in project level build.gradle. When I changed the order and put google() before jcenter() in build.gradle the problem disappeared

Here is my final build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)

{'a': 1, 'c': 7, 'b': 5, 'd': 5}

Map.Entry: How to use it?

This code is better rewritten as:

for( Map.Entry me : entrys.entrySet() )
{
    this.add( (Component) me.getValue() );
}

and it is equivalent to:

for( Component comp : entrys.getValues() )
{
    this.add( comp );
}

When you enumerate the entries of a map, the iteration yields a series of objects which implement the Map.Entry interface. Each one of these objects contains a key and a value.

It is supposed to be slightly more efficient to enumerate the entries of a map than to enumerate its values, but this factoid presumes that your Map is a HashMap, and also presumes knowledge of the inner workings (implementation details) of the HashMap class. What can be said with a bit more certainty is that no matter how your map is implemented, (whether it is a HashMap or something else,) if you need both the key and the value of the map, then enumerating the entries is going to be more efficient than enumerating the keys and then for each key invoking the map again in order to look up the corresponding value.

How to take the first N items from a generator or list?

With itertools you will obtain another generator object so in most of the cases you will need another step the take the first N elements (N). There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator:

Using list comprehension:

first_N_element=[generator.next() for i in range(N)]

Otherwise:

first_N_element=list(generator)[:N]

Where N is the number of elements you want to take (e.g. N=5 for the first five elements).

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

foreach:

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

MSDN Link

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

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

How to generate auto increment field in select query

here's for SQL server, Oracle, PostgreSQL which support window functions.

SELECT  ROW_NUMBER() OVER (ORDER BY first_name, last_name)  Sequence_no,
        first_name,
        last_name
FROM    tableName

Best cross-browser method to capture CTRL+S with JQuery?

This jQuery solution works for me in Chrome and Firefox, for both Ctrl+S and Cmd+S.

$(document).keydown(function(e) {

    var key = undefined;
    var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];

    while (key === undefined && possible.length > 0)
    {
        key = possible.pop();
    }

    if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
    {
        e.preventDefault();
        alert("Ctrl-s pressed");
        return false;
    }
    return true;
}); 

Android failed to load JS bundle

I don't have enough reputation to comment, but this is referring to dsissitka's answer. It works on Windows 10 as well.

To reiterate, the commands are:

cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081

HTML - how to make an entire DIV a hyperlink?

You just need to specify the cursor as a pointer, not a hand, as pointer is now the standard, so, here's the example page code:

<div onclick="location.href='portable-display-stands.html';" id="smallbox">The content of the div here</div>

and the example CSS:

#smallbox {
    cursor: pointer;
}

So the div is now a clickable element using 'onclick' and you've faked the hand cursor with the CSS...job done, works for me!

How to stop app that node.js express 'npm start'

In case your json file does not have a script to stop the app, an option that I use is just by pressing ctrl+C on the cmd.

How can I scan barcodes on iOS?

If support for the iPad 2 or iPod Touch is important for your application, I'd choose a barcode scanner SDK that can decode barcodes in blurry images, such as our Scandit barcode scanner SDK for iOS and Android. Decoding blurry barcode images is also helpful on phones with autofocus cameras because the user does not have to wait for the autofocus to kick in.

Scandit comes with a free community price plan and also has a product API that makes it easy to convert barcode numbers into product names.

(Disclaimer: I'm a co-founder of Scandit)

Creating CSS Global Variables : Stylesheet theme management

Latest Update: 16/01/2020

CSS Custom Properties (Variables) have arrived!

It's 2020 and time to officially roll out this feature in your new applications.


Preprocessor "NOT" required!

There is a lot of repetition in CSS. A single color may be used in several places.

For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally.

For non-trivial projects, this is not always possible. By declaring a variable on the :root pseudo-element, a CSS author can halt some instances of repetition by using the variable.

How it works

Set your variable at the top of your stylesheet:

CSS

Create a root class:

:root {
}

Create variables (-- [String] : [value])

:root {
  --red: #b00;
  --blue: #00b;
  --fullwidth: 100%;
}

Set your variables anywhere in your CSS document:

h1 {
  color: var(--red);
}
#MyText {
  color: var(--blue);
  width: var(--fullwidth);
}

BROWSER SUPPORT / COMPATIBILITY

See caniuse.com for current compatability.

![supported browsers


Firefox: Version 31+ (Enabled by default)

Supported since 2014 (Leading the way as usual.)

More info from Mozilla


Chrome: Version 49+ (Enabled by default).

Supported since 2016


Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).

Supported since 2016


Opera: Version 39+ (Enabled by default).

Supported since 2016


Android: Version 52+ (Enabled by default).

Supported since 2016


Edge: Version 15+ (Enabled by default).

Supported since 2017

CSS Custom Properties landed in Windows Insider Preview build 14986


IE: When pigs fly.

It's time to finally let this ship sink. No one enjoyed riding her anyway. ?


W3C SPEC

Full specification for upcoming CSS variables

Read more


TRY IT OUT

A fiddle and snippet are attached below for testing:

(It will only work with supported browsers.)

DEMO FIDDLE

_x000D_
_x000D_
:root {
  --red: #b00;
  --blue: #4679bd;
  --grey: #ddd;
  --W200: 200px;
  --Lft: left;
}
.Bx1,
.Bx2,
.Bx3,
.Bx4 {
  float: var(--Lft);
  width: var(--W200);
  height: var(--W200);
  margin: 10px;
  padding: 10px;
  border: 1px solid var(--red);
}
.Bx1 {
  color: var(--red);
  background: var(--grey);
}
.Bx2 {
  color: var(--grey);
  background: black;
}
.Bx3 {
  color: var(--grey);
  background: var(--blue);
}
.Bx4 {
  color: var(--grey);
  background: var(--red);
}
_x000D_
<p>If you see four square boxes then variables are working as expected.</p>

<div class="Bx1">I should be red text on grey background.</div>
<div class="Bx2">I should be grey text on black background.</div>
<div class="Bx3">I should be grey text on blue background.</div>
<div class="Bx4">I should be grey text on red background.</div>
_x000D_
_x000D_
_x000D_

Pure JavaScript Send POST Data Without a Form

You can use the XMLHttpRequest object as follows:

xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);

That code would post someStuff to url. Just make sure that when you create your XMLHttpRequest object, it will be cross-browser compatible. There are endless examples out there of how to do that.

Print time in a batch file (milliseconds)

Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.

How do I profile memory usage in Python?

If you only want to look at the memory usage of an object, (answer to other question)

There is a module called Pympler which contains the asizeof module.

Use as follows:

from pympler import asizeof
asizeof.asizeof(my_object)

Unlike sys.getsizeof, it works for your self-created objects.

>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:

asizeof(*objs, **opts)
    Return the combined size in bytes of all objects passed as positional arguments.

Split / Explode a column of dictionaries into separate columns with pandas

df = pd.concat([df['a'], df.b.apply(pd.Series)], axis=1)

How to hide a mobile browser's address bar?

This should be the code you need to hide the address bar:

window.addEventListener("load",function() {
    setTimeout(function(){
        // This hides the address bar:
        window.scrollTo(0, 1);
    }, 0);
});

Also nice looking Pokedex by the way! Hope this helps!

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

Collision resolution in Java HashMap

There is no collision in your example. You use the same key, so the old value gets replaced with the new one. Now, if you used two keys that map to the same hash code, then you'd have a collision. But even in that case, HashMap would replace your value! If you want the values to be chained in case of a collision, you have to do it yourself, e.g. by using a list as a value.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

$blog is an object not an array

try using $blog->id instead of $blog['id']

2D arrays in Python

Depending what you're doing, you may not really have a 2-D array.

80% of the time you have simple list of "row-like objects", which might be proper sequences.

myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ]

myArray[0][1] == 3.14159
myArray[1][1] == 2.71828

More often, they're instances of a class or a dictionary or a set or something more interesting that you didn't have in your previous languages.

myArray = [ {'pi':3.1415925,'r':2}, {'e':2.71828,'theta':.5} ]

20% of the time you have a dictionary, keyed by a pair

myArray = { (2009,'aug'):(some,tuple,of,values), (2009,'sep'):(some,other,tuple) }

Rarely, will you actually need a matrix.

You have a large, large number of collection classes in Python. Odds are good that you have something more interesting than a matrix.

How to resize Twitter Bootstrap modal dynamically based on the content

Simple Css work for me

.modal-dialog { 
max-width : 100% ;
}

PHP array printing using a loop

for using both things variables value and kye

foreach($array as $key=>$value){
 print "$key holds $value\n";
}

for using variables value only

foreach($array as $value){
 print $value."\n";
}

if you want to do something repeatedly until equal the length of array us this

// for loop
for($i = 0; $i < count($array); $i++) {
 // do something with $array[$i]
}

Thanks!

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

From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

>>> from __future__ import print_function
>>> print('a', end='')

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function at the beginning). The print statement was removed and became the print() function by default in Python 3.0.

Validate fields after user has left a field

By using ng-focus you can achieve your goal. you need to provide ng-focus in your input field. And while writing your ng-show derivatives you have to write a logic not equal too. Like the below code:

<input type="text" class="form-control" name="inputPhone" ng-model="demo.phoneNumber" required ng-focus> <div ng-show="demoForm.inputPhone.$dirty && demoForm.inputPhone.$invalid && !demoForm.inputPhone.$focused"></div>

how to convert object to string in java

Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.

PHP write file from input to txt

use fwrite() instead of file_put_contents()

Finding what branch a Git commit came from

This simple command works like a charm:

git name-rev <SHA>

For example (where test-branch is the branch name):

git name-rev 651ad3a
251ad3a remotes/origin/test-branch

Even this is working for complex scenarios, like:

origin/branchA/
              /branchB
                      /commit<SHA1>
                                   /commit<SHA2>

Here git name-rev commit<SHA2> returns branchB.

Jquery Ajax, return success/error from mvc.net controller

 $.ajax({
    type: "POST",
    data: formData,
    url: "/Forms/GetJobData",
    dataType: 'json',
    contentType: false,
    processData: false,               
    success: function (response) {
        if (response.success) {
            alert(response.responseText);
        } else {
            // DoSomethingElse()
            alert(response.responseText);
        }                          
    },
    error: function (response) {
        alert("error!");  // 
    }

});

Controller:

[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
    var mimeType = jobData.File.ContentType;
    var isFileSupported = IsFileSupported(mimeType);

    if (!isFileSupported){        
         //  Send "false"
        return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        //  Send "Success"
        return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
    }   
}

---Supplement:---

basically you can send multiple parameters this way:

Controller:

 return Json(new { 
                success = true,
                Name = model.Name,
                Phone = model.Phone,
                Email = model.Email                                
            }, 
            JsonRequestBehavior.AllowGet);

Html:

<script> 
     $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                contentType: 'application/json; charset=utf-8',            
                success: function (response) {

                   if(response.success){ 
                      console.log(response.Name);
                      console.log(response.Phone);
                      console.log(response.Email);
                    }


                },
                error: function (response) {
                    alert("error!"); 
                }
            });

How do I read from parameters.yml in a controller in symfony2?

You can use:

public function indexAction()
{
   dump( $this->getParameter('api_user'));
}

For more information I recommend you read the doc :

http://symfony.com/doc/2.8/service_container/parameters.html

SQL - How do I get only the numbers after the decimal?

Make it very simple by query:

select substr('123.123',instr('123.123','.')+1, length('123.123')) from dual;

Put your number or column name instead 123.122

How do I delete multiple rows with different IDs?

  • You can make this.

    CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
    @CODE XML ,@ERRFLAG CHAR(1) = '0' OUTPUT

AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )

IF @@ROWCOUNT = 0 SET @ERRFLAG = 200

SET NOCOUNT OFF

  • <'RecordList'><'ID'>1<'/ID'><'ID'>2<'/ID'><'/RecordList'>

How to set date format in HTML date input tag?

We can change this yyyy-mm-dd format to dd-mm-yyyy in javascript by using split method.

let dateyear= "2020-03-18";
let arr = dateyear.split('-') //now we get array of these and we can made in any format as we want
let dateFormat = arr[2] + "-" + arr[1] + "-" + arr[0]  //In dd-mm-yyyy format

How to force an entire layout View refresh?

Try recreate() it will cause this Activity to be recreated.

Substring with reverse index

you can just split it up and get the last element

var string="xxx_456";
var a=string.split("_");
alert(a[1]); #or a.pop

In jQuery, how do I select an element by its name attribute?

You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.

You create RadioButton control in ASP.NET as below:

<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />

And ASP.NET renders following HTML for your RadioButton

<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>

For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.

The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following

$('span.radios input:radio').click(function() {
    var value = $(this).val();
});

How to Cast Objects in PHP

Without using inheritance (as mentioned by author), it seems like you are looking for a solution that can transform one class to another with preassumption of the developer knows and understand the similarity of 2 classes.

There's no existing solution for transforming between objects. What you can try out are:

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You could make a recursive function do the work

  • Let L = size(M)
  • Let idx = zeros(L,1)
  • Take length(L) as the maximum depth
  • Loop for idx(depth) = 1:L(depth)
  • If your depth is length(L), do the element operation, else call the function again with depth+1

Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.

Save Screen (program) output to a file

You can also use Control-a + H to save loggings into screenlog.n file. One more Control-a + H to turn off.

C-a H: Begins/ends logging of the current window to the file "screenlog.n".

Hour from DateTime? in 24 hours format

You can get the desired result with the code below. Two'H' in HH is for 24-hour format.

return fechaHora.Value.ToString("HH:mm");

Merge 2 arrays of objects

I was facing the same problem and based on guya answer I have extended the underscore library and also added a bit more of functionality that I was requiring. Here's the Gist.

/**
 * Merges two object-like arrays based on a key property and also merges its array-like attributes specified in objectPropertiesToMerge.
 * It also removes falsy values after merging object properties.
 *
 * @param firstArray The original object-like array.
 * @param secondArray An object-like array to add to the firstArray.
 * @param keyProperty The object property that will be used to check if objects from different arrays are the same or not.
 * @param objectPropertiesToMerge The list of object properties that you want to merge. It all must be arrays.
 * @returns The updated original array.
 */
function merge(firstArray, secondArray, keyProperty, objectPropertiesToMerge) {

    function mergeObjectProperties(object, otherObject, objectPropertiesToMerge) {
        _.each(objectPropertiesToMerge, function (eachProperty) {
            object[eachProperty] = _.chain(object[eachProperty]).union(otherObject[eachProperty]).compact().value();
        });
    }

    if (firstArray.length === 0) {
        _.each(secondArray, function (each) {
            firstArray.push(each);
        });
    } else {
        _.each(secondArray, function (itemFromSecond) {
            var itemFromFirst = _.find(firstArray, function (item) {
                return item[keyProperty] === itemFromSecond[keyProperty];
            });

            if (itemFromFirst) {
                mergeObjectProperties(itemFromFirst, itemFromSecond, objectPropertiesToMerge);
            } else {
                firstArray.push(itemFromSecond);
            }
    });
    }

    return firstArray;
}

_.mixin({
            merge: merge
        });

Hope it to be useful! Regards!

Defining arrays in Google Scripts

Try this

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  //var values = rows.getValues();

  var Names = sheet.getRange("A2:A7");
  var Name = [
    Names.getCell(1, 1).getValue(),
    Names.getCell(2, 1).getValue(),
    .....
    Names.getCell(5, 1).getValue()]

You can define arrays simply as follows, instead of allocating and then assigning.

var arr = [1,2,3,5]

Your initial error was because of the following line, and ones like it

var Name[0] = Name_cell.getValue(); 

Since Name is already defined and you are assigning the values to its elements, you should skip the var, so just

Name[0] = Name_cell.getValue();

Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.

The thread has exited with code 0 (0x0) with no unhandled exception

The framework creates threads to support each window you create, eg, as when you create a Form and .Show() it. When the windows close, the threads are terminated (ie, they exit).

This is normal behavior. However, if the application is creating threads, and there are a lot of thread exit messages corresponding to these threads (one could tell possibly by the thread's names, by giving them distinct names in the app), then perhaps this is indicative of a problem with the app creating threads when it shouldn't, due to a program logic error.

It would be an interesting followup to have the original poster let us know what s/he discovered regarding the problems with the server crashing. I have a feeling it wouldn't have anything to do with this... but it's hard to tell from the information posted.

Merging two arrays in .NET

Easier would just be using LINQ:

var array = new string[] { "test" }.ToList();
var array1 = new string[] { "test" }.ToList();
array.AddRange(array1);
var result = array.ToArray();

First convert the arrays to lists and merge them... After that just convert the list back to an array :)

Convert string to variable name in python

You can use a Dictionary to keep track of the keys and values.

For instance...

dictOfStuff = {} ##Make a Dictionary

x = "Buffalo" ##OR it can equal the input of something, up to you.

dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to  what ever you like

print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.

A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.

Maximum size of an Array in Javascript

You could try something like this to test and trim the length:

http://jsfiddle.net/orolo/wJDXL/

_x000D_
_x000D_
var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
_x000D_
if (longArray.length >= 6) {_x000D_
  longArray.length = 3;_x000D_
}_x000D_
_x000D_
alert(longArray); //1, 2, 3
_x000D_
_x000D_
_x000D_

Windows batch: call more than one command in a FOR loop?

Using & is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.

FOR /r %%X IN (*.txt) DO (
    ECHO %%X
    DEL %%X
)

Placement of ( and ) matters. The round brackets after DO must be placed on the same line, otherwise the batch file will be incorrect.

See if /?|find /V "" for details.

Run a .bat file using python code

import subprocess

filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)

stdout, stderr = p.communicate()
print p.returncode # is 0 if success

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

RelativeLayout center vertical

If View's height/width = wrap_content

use:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

If View's height/width = match_parent

use:

android:gravity="center_vertical|center_horizontal"

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

<VirtualHost *:80>
    ServerName www.YOURDOMAIN.COM
    ServerAlias YOURDOMAIN.COM
    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    ErrorLog /var/www/YOURDOMAIN.COM/error.log
    CustomLog /var/www/YOURDOMAIN.COM/requests.log combined

    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/YOURDOMAIN.COM/public_html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

</VirtualHost>

Why doesn't Java allow overriding of static methods?

Static methods are treated as global by the JVM, there are not bound to an object instance at all.

It could conceptually be possible if you could call static methods from class objects (like in languages like Smalltalk) but it's not the case in Java.

EDIT

You can overload static method, that's ok. But you can not override a static method, because class are no first-class object. You can use reflection to get the class of an object at run-time, but the object that you get does not parallel the class hierarchy.

class MyClass { ... }
class MySubClass extends MyClass { ... }

MyClass obj1 = new MyClass();
MySubClass obj2 = new MySubClass();

ob2 instanceof MyClass --> true

Class clazz1 = obj1.getClass();
Class clazz2 = obj2.getClass();

clazz2 instanceof clazz1 --> false

You can reflect over the classes, but it stops there. You don't invoke a static method by using clazz1.staticMethod(), but using MyClass.staticMethod(). A static method is not bound to an object and there is hence no notion of this nor super in a static method. A static method is a global function; as a consequence there is also no notion of polymorphism and, therefore, method overriding makes no sense.

But this could be possible if MyClass was an object at run-time on which you invoke a method, as in Smalltalk (or maybe JRuby as one comment suggest, but I know nothing of JRuby).

Oh yeah... one more thing. You can invoke a static method through an object obj1.staticMethod() but that really syntactic sugar for MyClass.staticMethod() and should be avoided. It usually raises a warning in modern IDE. I don't know why they ever allowed this shortcut.

How to get Text BOLD in Alert or Confirm box?

Maybe you coul'd use UTF8 bold chars.

For examples: https://yaytext.com/bold-italic/

It works on Chromium 80.0, I don't know on other browsers...

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES program which was causing the issue.

Using NSPredicate to filter an NSArray based on NSDictionary keys

I know it's old news but to add my two cents. By default I use the commands LIKE[cd] rather than just [c]. The [d] compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d] strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name where object.name == @"voodoo" will return the object containing the name Vòódòó.

From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.

How to add headers to a multicolumn listbox in an Excel userform using VBA

Here is my approach to solve the problem:

This solution requires you to add a second ListBox element and place it above the first one.

Like this:

Add an additional ListBox

Then you call the function CreateListBoxHeader to make the alignment correct and add header items.

Result:

Call the function CreateListBoxHeader

Code:

  Public Sub CreateListBoxHeader(body As MSForms.ListBox, header As MSForms.ListBox, arrHeaders)
            ' make column count match
            header.ColumnCount = body.ColumnCount
            header.ColumnWidths = body.ColumnWidths

        ' add header elements
        header.Clear
        header.AddItem
        Dim i As Integer
        For i = 0 To UBound(arrHeaders)
            header.List(0, i) = arrHeaders(i)
        Next i

        ' make it pretty
        body.ZOrder (1)
        header.ZOrder (0)
        header.SpecialEffect = fmSpecialEffectFlat
        header.BackColor = RGB(200, 200, 200)
        header.Height = 10

        ' align header to body (should be done last!)
        header.Width = body.Width
        header.Left = body.Left
        header.Top = body.Top - (header.Height - 1)
End Sub

Usage:

Private Sub UserForm_Activate()
    Call CreateListBoxHeader(Me.listBox_Body, Me.listBox_Header, Array("Header 1", "Header 2"))
End Sub

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

Javascript: 'window' is not defined

It is from an external js file and it is the only file linked to the page.

OK.

When I double click this file I get the following error

Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:

Windows Script Host Error: 'window' is not defined Code: 800A1391

... not an error you'll see in a browser. And of course, the browser is what supplies the window object.

ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

How to split() a delimited string to a List<String>

This will read a csv file and it includes a csv line splitter that handles double quotes and it can read even if excel has it open.

    public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
    {
        var result = new List<Dictionary<string, string>>();

        var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        System.IO.StreamReader file = new System.IO.StreamReader(fs);

        string line;

        int n = 0;
        List<string> columns = null;
        while ((line = file.ReadLine()) != null)
        {
            var values = SplitCsv(line);
            if (n == 0)
            {
                columns = values;
            }
            else
            {
                var dict = new Dictionary<string, string>();
                for (int i = 0; i < columns.Count; i++)
                    if (i < values.Count)
                        dict.Add(columns[i], values[i]);
                result.Add(dict);
            }
            n++;
        }

        file.Close();
        return result;
    }

    private List<string> SplitCsv(string csv)
    {
        var values = new List<string>();

        int last = -1;
        bool inQuotes = false;

        int n = 0;
        while (n < csv.Length)
        {
            switch (csv[n])
            {
                case '"':
                    inQuotes = !inQuotes;
                    break;
                case ',':
                    if (!inQuotes)
                    {
                        values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
                        last = n;
                    }
                    break;
            }
            n++;
        }

        if (last != csv.Length - 1)
            values.Add(csv.Substring(last + 1).Trim());

        return values;
    }

1052: Column 'id' in field list is ambiguous

If the format of the id's in the two table varies then you want to join them, as such you can select to use an id from one-main table, say if you have table_customes and table_orders, and tha id for orders is like "101","102"..."110", just use one for customers

select customers.id, name, amount, date from customers.orders;

Reading string from input with space character?

"Barack Obama" has a space between 'Barack' and 'Obama'. To accommodate that, use this code;

#include <stdio.h>
int main()
{
    printf("Enter your name\n");
   char a[80];
   gets(a);
   printf("Your name is %s\n", a);
   return 0;
}

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

jQuery: Adding two attributes via the .attr(); method

the proper way is:

.attr({target:'nw', title:'Opens in a new window'})

How do I delete rows in a data frame?

For completeness, I'll add that this can be done with dplyr as well using slice. The advantage of using this is that it can be part of a piped workflow.

df <- df %>%
  .
  .
  slice(-c(2, 4, 6)) %>%
  .
  .

Of course, you can also use it without pipes.

df <- slice(df, -c(2, 4, 6))

The "not vector" format, -c(2, 4, 6) means to get everything that is not at rows 2, 4 and 6. For an example using a range, let's say you wanted to remove the first 5 rows, you could do slice(df, 6:n()). For more examples, see the docs.

How to tag docker image with docker-compose

It seems the docs/tool have been updated and you can now add the image tag to your script. This was successful for me.

Example:

version: '2'
services:

  baggins.api.rest:
    image: my.image.name:rc2
    build:
      context: ../..
      dockerfile: app/Docker/Dockerfile.release
    ports:
      ...

https://docs.docker.com/compose/compose-file/#build

How to iterate over array of objects in Handlebars?

This fiddle has both each and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.

Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.

Eg1: The below example is directly calling json key (data) inside small_data variable.

In html use the below code:

<div id="small-content-placeholder"></div>

The below can be placed in header or body of html:

<script id="small-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#data}}
                <tr>
                    <td>{{username}}
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/data}}
        </tbody>
    </table>
</script>

The below one is on document ready:

var small_source   = $("#small-template").html();
var small_template = Handlebars.compile(small_source);

The below is the json:

var small_data = {
            data: [
                {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
            ]
        };

Finally attach the json to content holder:

$("#small-content-placeholder").html(small_template(small_data));

Eg2: Iteration using each.

Consider the below json.

var big_data = [
            {
                name: "users1",
                details: [
                    {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            },
            {
                name: "users2",
                details: [
                    {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            }
      ];

While passing the json to content holder just name it in this way:

$("#big-content-placeholder").html(big_template({big_data:big_data}));

And the template looks like :

<script id="big-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#each big_data}}
                <tr>
                    <td>{{name}}
                            <ul>
                                {{#details}}
                                    <li>{{username}}</li>
                                    <li>{{email}}</li>
                                {{/details}}
                            </ul>
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/each}}
        </tbody>
    </table>
</script>

How to get the id of the element clicked using jQuery

Since you are loading in the spans via ajax you will have to attach delegate handlers to the events to catch them as they bubble up.

$(document).on('click','span',function(e){
    console.log(e.target.id)
})

you will want to attach the event to the closest static member you can to increase efficiency.

$('#main_div').on('click','span',function(e){
    console.log(e.target.id)
})

is better than binding to the document for instance.

This question may help you understand

Direct vs. Delegated - jQuery .on()

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:

git add .
git commit -m"commentary"

Then I was able to type:

git push -u origin master

Running an outside program (executable) in Python?

Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.system, subprocess methods, or whatever...

If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?

Unable to start MySQL server

In my case I had to go to the MySQL installer, then configuration button for the MySQL server, then next until the option to "create the server as a windows service" ticked that, gave it a service name as MySQL8.0, next and then finish, that solved the issue and started a new service

How to delete a specific file from folder using asp.net

This is how I delete files

if ((System.IO.File.Exists(fileName)))
                {
                    System.IO.File.Delete(fileName);
}

Also make sure that the file name you are passing in your delete, is the accurate path

EDIT

You could use the following event instead as well or just use the code in this snippet and use in your method

void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
  {

    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;

    //Debug this line and see what value is returned if it contains the full path.
    //If it does not contain the full path then add the path to the string.
    string fileName = row.Cells[0].Text 

    if(fileName != null || fileName != string.empty)
    {
       if((System.IO.File.Exists(fileName))
           System.IO.File.Delete(fileName);

     }
  }

Returning a stream from File.OpenRead()

You need

    str.CopyTo(data);
    data.Position = 0; // reset to beginning
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);  

And since your Test() method is imitating the client it ought to Close() or Dispose() the str Stream. And the memoryStream too, just out of principal.

Difference between numeric, float and decimal in SQL Server

use the float or real data types only if the precision provided by decimal (up to 38 digits) is insufficient

  • Approximate numeric data types do not store the exact values specified for many numbers; they store an extremely close approximation of the value.(Technet)

  • Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators (Technet)

so generally because the precision provided by decimal is [10E38 ~ 38 digits] if your number can fit in it, and smaller storage space (and maybe speed) of Float is not important and dealing with abnormal behaviors and issues of approximate numeric types are not acceptable, use Decimal generally.

more useful information

  • numeric = decimal (5 to 17 bytes) (Exact Numeric Data Type)
    • will map to Decimal in .NET
    • both have (18, 0) as default (precision,scale) parameters in SQL server
    • scale = maximum number of decimal digits that can be stored to the right of the decimal point.
    • kindly note that money(8 byte) and smallmoney(4 byte) are also exact and map to Decimal In .NET and have 4 decimal points(MSDN)
    • decimal and numeric (Transact-SQL) - MSDN
  • real (4 byte) (Approximate Numeric Data Type)
  • float (8 byte) (Approximate Numeric Data Type)
    • will map to Double in .NET
  • All exact numeric types always produce the same result, regardless of which kind of processor architecture is being used or the magnitude of the numbers
  • The parameter supplied to the float data type defines the number of bits that are used to store the mantissa of the floating point number.
  • Approximate Numeric Data Type usually uses less storage and have better speed (up to 20x) and you should also consider when they got converted in .NET

Exact Numeric Data Types Approximate Numeric Data Types

main source : MCTS Self-Paced Training Kit (Exam 70-433): Microsoft® SQL Server® 2008 Database Development - Chapter 3 - Tables , Data Types , and Declarative Data Integrity Lesson 1 - Choosing Data Types (Guidelines) - Page 93

Display HTML form values in same page after submit using Ajax

One more way to do it (if you use form), note that input type is button

<input type="button" onclick="showMessage()" value="submit" />

Complete code is:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

But you can do it even without form:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

Here you can use either submit or button:

<input type="submit" onclick="showMessage()" value="submit" />

No need to set

return false;

from JavaScript function for neither of those two examples.

Detect when browser receives file download

Create an iframe when button/link is clicked and append this to body.

                  $('<iframe />')
                 .attr('src', url)
                 .attr('id','iframe_download_report')
                 .hide()
                 .appendTo('body'); 

Create an iframe with delay and delete it after download.

                            var triggerDelay =   100;
                            var cleaningDelay =  20000;
                            var that = this;
                            setTimeout(function() {
                                var frame = $('<iframe style="width:1px; height:1px;" class="multi-download-frame"></iframe>');
                                frame.attr('src', url+"?"+ "Content-Disposition: attachment ; filename="+that.model.get('fileName'));
                                $(ev.target).after(frame);
                                setTimeout(function() {
                                    frame.remove();
                                }, cleaningDelay);
                            }, triggerDelay);

Object array initialization without default constructor

You can create an array of pointers.

Car** mycars = new Car*[userInput];
for (int i=0; i<userInput; i++){
    mycars[i] = new Car(...);
}

...

for (int i=0; i<userInput; i++){
    delete mycars[i];
}
delete [] mycars;

or

Car() constructor does not need to be public. Add a static method to your class that builds an array:

static Car* makeArray(int length){
    return new Car[length];
}

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Convert Date/Time for given Timezone - java

We can handle this by using offset value

 public static long convertDateTimeZone(long lngDate, String fromTimeZone,
        String toTimeZone){
    TimeZone toTZ = TimeZone.getTimeZone(toTimeZone);
    Calendar toCal = Calendar.getInstance(toTZ);        

    TimeZone fromTZ = TimeZone.getTimeZone(fromTimeZone);
    Calendar fromCal = Calendar.getInstance(fromTZ);
    fromCal.setTimeInMillis(lngDate);
    toCal.setTimeInMillis(fromCal.getTimeInMillis()
            + toTZ.getOffset(fromCal.getTimeInMillis())
            - TimeZone.getDefault().getOffset(fromCal.getTimeInMillis()));      
    return toCal.getTimeInMillis();
}

Test Code snippet:

 System.out.println(new Date().getTime())
 System.out.println(convertDateTimeZone(new Date().getTime(), TimeZone
                .getDefault().getID(), "EST"));

Output: 1387353270742 1387335270742

Different ways of clearing lists

del list[:] 

Will delete the values of that list variable

del list

Will delete the variable itself from memory

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

Alert after page load

With the use of jQuery to handle the document ready event,

<script type="text/javascript">

function onLoadAlert() {
    alert('<%: TempData["Resultat"]%>');
}

$(document).ready(onLoadAlert);
</script>

Or, even simpler - put the <script> at the end of body, not in the head.

Cycles in an Undirected Graph

I believe using DFS correctly also depends on how are you going to represent your graph in the code. For example suppose you are using adjacent lists to keep track of neighbor nodes and your graph has 2 vertices and only one edge: V={1,2} and E={(1,2)}. In this case starting from vertex 1, DFS will mark it as VISITED and will put 2 in the queue. After that it will pop vertex 2 and since 1 is adjacent to 2, and 1 is VISITED, DFS will conclude that there is a cycle (which is wrong). In other words in Undirected graphs (1,2) and (2,1) are the same edge and you should code in a way for DFS not to consider them different edges. Keeping parent node for each visited node will help to handle this situation.

How exactly does the android:onClick XML attribute differ from setOnClickListener?

The best way to do this is with the following code:

 Button button = (Button)findViewById(R.id.btn_register);
 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do your fancy method
            }
        });

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

Split Strings into words with multiple word boundary delimiters

I like pprzemek's solution because it does not assume that the delimiters are single characters and it doesn't try to leverage a regex (which would not work well if the number of separators got to be crazy long).

Here's a more readable version of the above solution for clarity:

def split_string_on_multiple_separators(input_string, separators):
    buffer = [input_string]
    for sep in separators:
        strings = buffer
        buffer = []  # reset the buffer
        for s in strings:
            buffer = buffer + s.split(sep)

    return buffer

Spring data JPA query with parameter properties

Are you working with a @Service too? Because if you are, then you can @Autowired your PersonRepository to the @Service and then in the service just invoke the Name class and use the form that @CuriosMind... proposed:

@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
                         @Param("forename") String firstname);
}

and when invoking the method from the repository in the service, you can then pass those parameters.

How might I force a floating DIV to match the height of another floating DIV?

Here is a jQuery plugin to set the heights of multiple divs to be the same. And below is the actual code of the plugin.

$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
    if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
    if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
    if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
        $(this).children().css({'min-height': currentTallest}); 
    });
    return this;
};

PHP PDO with foreach and fetch

This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.

If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

Scanner only reads first word instead of line

Use input.nextLine(); instead of input.next();

How to force the browser to reload cached CSS and JavaScript files

A SilverStripe-specific answer worked out from reading: http://api.silverstripe.org/3.0/source-class-SS_Datetime.html#98-110:

Hopefully this will help someone using a SilverStripe template and trying to force reload a cached image on each page visit / refresh. In my case it is a GIF animation which only plays once and therefore did not replay after it was cached. In my template I simply added:

?$Now.Format(dmYHis)

to the end of the file path to create a unique time stamp and to force the browser to treat it as a new file.

C# MessageBox dialog result

This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:

//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

// If the no button was pressed ... 
if (result == DialogResult.No)
{
    ...
}

Hope it helps

Get the Highlighted/Selected text

Use window.getSelection().toString().

You can read more on developer.mozilla.org

How to do Base64 encoding in node.js?

The accepted answer previously contained new Buffer(), which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).

The Buffer constructor is deprecated according to the documentation.

Here is an example of a vulnerability that can result from using it in the ws library.

The code snippets should read:

console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));

After this answer was written, it has been updated and now matches this.

How to drop a PostgreSQL database if there are active connections to it?

PostgreSQL 13 introduced FORCE option.

DROP DATABASE

DROP DATABASE drops a database ... Also, if anyone else is connected to the target database, this command will fail unless you use the FORCE option described below.

FORCE

Attempt to terminate all existing connections to the target database. It doesn't terminate if prepared transactions, active logical replication slots or subscriptions are present in the target database.

DROP DATABASE db_name WITH (FORCE);

How to add line break for UILabel?

If you read a string from an XML file, the line break \n in this string will not work in UILabel text. The \n is not parsed to a line break.

Here is a little trick to solve this issue:

// correct next line \n in string from XML file
NSString *myNewLineStr = @"\n";
myLabelText = [myLabelText stringByReplacingOccurrencesOfString:@"\\n" withString:myNewLineStr];

myLabel.text = myLabelText;

So you have to replace the unparsed \n part in your string by a parsed \n in a hardcoded NSString.

Here are my other label settings:

myLabel.numberOfLines = 0;
myLabel.backgroundColor = [UIColor lightGrayColor];
myLabel.textColor = [UIColor redColor]; 
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
myLabel.textAlignment = UITextAlignmentCenter;

Most important is to set numberOfLines to 0 (= unlimited number of lines in label).

No idea why Apple has chosen to not parse \n in strings read from XML?

Hope this helps.

Create XML in Javascript

Consider that we need to create the following XML document:

<?xml version="1.0"?>
<people>
  <person first-name="eric" middle-initial="H" last-name="jung">
    <address street="321 south st" city="denver" state="co" country="usa"/>
    <address street="123 main st" city="arlington" state="ma" country="usa"/>
  </person>

  <person first-name="jed" last-name="brown">
    <address street="321 north st" city="atlanta" state="ga" country="usa"/>
    <address street="123 west st" city="seattle" state="wa" country="usa"/>
    <address street="321 south avenue" city="denver" state="co" country="usa"/>
  </person>
</people>

we can write the following code to generate the above XML

var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");

var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");

var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);

var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);

var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");

var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);

var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);

var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);

peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);

If any text need to be written between a tag we can use innerHTML property to achieve it.

Example

elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)

For more details please follow the below link. The above example has been explained there in more details.

https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree

Execute jar file with multiple classpath libraries from command prompt

You can use maven-assembly-plugin, Here is the example from the official site: https://maven.apache.org/plugins/maven-assembly-plugin/usage.html

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
            <archive>
                <manifest>
                    <mainClass>your main class</mainClass>
                </manifest>
            </archive>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id> <!-- this is used for inheritance merges -->
                <phase>package</phase> <!-- bind to the packaging phase -->
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

WITH PivotCTE AS
(
    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
    numericmonth,
    chardate,
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

Regular Expression for alphanumeric and underscores

You want to check that each character matches your requirements, which is why we use:

[A-Za-z0-9_]

And you can even use the shorthand version:

\w

Which is equivalent (in some regex flavors, so make sure you check before you use it). Then to indicate that the entire string must match, you use:

^

To indicate the string must start with that character, then use

$

To indicate the string must end with that character. Then use

\w+ or \w*

To indicate "1 or more", or "0 or more". Putting it all together, we have:

^\w*$

Update select2 data without rebuilding the control

I think it suffices to hand the data over directly:

$("#inputhidden").select2("data", data, true);

Note that the second parameter seems to indicate that a refresh is desired.

Thanks to @Bergi for help with this.


If that doesn't automatically update you could either try calling it's updateResults method directly.

$("#inputhidden").select2("updateResults");

Or trigger it indirectly by sending a trigger to the "input.select2-input" like so:

var search = $("#inputhidden input.select2-input");
search.trigger("input");

Fixed header table with horizontal scrollbar and vertical scrollbar on

If this is what you want only HTML and CSS solution

fiddle

Here's the HTML

<div class="outer-container"> <!-- absolute positioned container -->
<div class="inner-container">

    <div class="table-header">
        <table id="headertable" width="100%" cellpadding="0" cellspacing="0">
            <thead>
                <tr>
                    <th class="header-cell col1">One</th>
                    <th class="header-cell col2">Two</th>
                    <th class="header-cell col3">Three</th>
                    <th class="header-cell col4">Four</th>
                    <th class="header-cell col5">Five</th>
                </tr>
            </thead>
        </table>
    </div>

    <div class="table-body">
        <table id="bodytable" width="100%" cellpadding="0" cellspacing="0">
            <tbody>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</div>

And this is the css

body {
margin:0;
padding:0;
height: 100%;
width: 100%;
}
table {
    border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
tr {
    width: 100%;
}

.outer-container {
    background-color: #ccc;
    position: absolute;
    top:0;
    left: 0;
    right: 300px;
    bottom:40px;
    overflow: scroll;

}
.inner-container {
    width: 100%;
    height: 100%;
    position: relative;
    overflow-x: visible;
    overflow-y:visible;
}
.table-header {
    float:left;
    width: 100%;
}
.table-body {
    float:left;
    height: auto;
    width: auto;
    overflow: visible;
    background-color: red;
}
.header-cell {
    background-color: yellow;
    text-align: left;
    height: 40px;
}
.body-cell {
    background-color: transparent;
    text-align: left;
}
.col1, .col3, .col4, .col5 {
    width:120px;
    min-width: 120px;
}
.col2 {
    min-width: 300px;
}

Let me know if this is what you need. Or some thing is missing. I went through the other answers and found that jquery has been used . I took it on assumption that you need css solution . If I am missing any more point please mention :)

How to git commit a single file/directory

Try:

git commit -m 'my notes' path/to/my/file.ext 

Swift: Convert enum value to String?

For now, I'll redefine the enum as:

enum Audience: String {
    case Public = "Public"
    case Friends = "Friends"
    case Private = "Private"
}

so that I can do:

audience.toRaw() // "Public"

But, isn't this new enum definition redundant? Can I keep the initial enum definition and do something like:

audience.toString() // "Public"

How to get all properties values of a JavaScript Object (without knowing the keys)?

I realize I'm a little late but here's a shim for the new firefox 47 Object.values method

Object.prototype.values = Object.prototype.values || function(obj) {
  return this.keys(obj).map(function(key){
    return obj[key];
  });
};

Angular2 - Focusing a textbox on component load

I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.

For router changes:

router.events.subscribe((val) => {
    setTimeout(() => {
        if (this.searchElement) {
            this.searchElement.nativeElement.focus();
        }
    }, 1);
})

Then ngAfterViewInit() for the onload scenario.

Creating an Array from a Range in VBA

This function returns an array regardless of the size of the range.

Ranges will return an array unless the range is only 1 cell and then it returns a single value instead. This function will turn the single value into an array (1 based, the same as the array's returned by ranges)

This answer improves on previous answers as it will return an array from a range no matter what the size. It is also more efficient that other answers as it will return the array generated by the range if possible. Works with single dimension and multi-dimensional arrays

The function works by trying to find the upper bounds of the array. If that fails then it must be a single value so we'll create an array and assign the value to it.

Public Function RangeToArray(inputRange As Range) As Variant()
Dim size As Integer
Dim inputValue As Variant, outputArray() As Variant

    ' inputValue will either be an variant array for ranges with more than 1 cell
    ' or a single variant value for range will only 1 cell
    inputValue = inputRange

    On Error Resume Next
    size = UBound(inputValue)

    If Err.Number = 0 Then
        RangeToArray = inputValue
    Else
        On Error GoTo 0
        ReDim outputArray(1 To 1, 1 to 1)
        outputArray(1,1) = inputValue
        RangeToArray = outputArray
    End If

    On Error GoTo 0

End Function

Preserve line breaks in angularjs

Just use the css style "white-space: pre-wrap" and you should be good to go. I've had the same issue where I need to handle error messages for which the line breaks and white spaces are really particular. I just added this inline where I was binding the data and it works like Charm!

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

Display Back Arrow on Toolbar

Simple and easy way to show back button on toolbar

Paste this code in onCreate method

 if (getSupportActionBar() != null){

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

Paste this override method outside the onCreate method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== android.R.id.home) {

        finish();
    }
    return super.onOptionsItemSelected(item);
}

Remote debugging a Java application

I'd like to emphasize that order of arguments is important.

For me java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 -jar app.jar command opens debugger port,

but java -jar app.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 command doesn't.

Bootstrap 3 Navbar Collapse

Easiest way is to customize bootstrap

find variable:

 @grid-float-breakpoint

which is set to @screen-sm, you can change it according to your needs. Hope it helps!

How to get resources directory path programmatically

Finally, this is what I did:

private File getFileFromURL() {
    URL url = this.getClass().getClassLoader().getResource("/sql");
    File file = null;
    try {
        file = new File(url.toURI());
    } catch (URISyntaxException e) {
        file = new File(url.getPath());
    } finally {
        return file;
    }
}

...

File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();

Get selected value from combo box in C# WPF

It's the same principle.

You can either use SelectedIndex and use ComboBox.Items[SelectedIndex].ToString(). Or just ComboBox.SelectedItem and cast it to any type you need :)

Android: ProgressDialog.show() crashes with getApplicationContext

Having read the above answers i found that for my situation the following fixed the issue.

This threw the error

myButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v) {
        MyDialogue dialog = new MyDialogue(getApplicationContext());
        dialog.show();              
    }
});

Based on the previous answers that suggested the context was the wrong one, i changed the getApplicationContext() to retrieve the context from the View passed in to the buttons onClick method.

myButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v) {
        MyDialogue dialog = new MyDialogue(v.getContext());
        dialog.show();              
    }
});

I don't fully understand the workings of Java so i could be wrong, but I'm guessing that for my specific situation the cause could have been related to the fact that the above snippet was defined in an Abstract Activity class; inherited and used by many Activities, perhaps that contributed to the fact that getApplicationContext() doesn't return a valid context?? (Just a guess).

Create an application setup in visual studio 2013

I will tell , how i solved almost similar problem. I developed a application using VS 2013 and tried to create wizard for it failed to do. Later i installed premium VS and tried and failed.

at last i used "ClickOnce" and it worked fine.

So i believe here also , "CLICKONCE" would help you.

jQuery get the rendered height of an element?

So is this the answer?

"If you need to calculate something but not show it, set the element to visibility:hidden and position:absolute, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the lines last time I checked)."

I have the same problem on a number of elements. There is no jQuery or Prototype to be used on the site but I'm all in favor of borrowing the technique if it works. As an example of some things that failed to work, followed by what did, I have the following code:

// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
    var DoOffset = true;
    if (!elementPassed) { return 0; }
    if (!elementPassed.style) { return 0; }
    var thisHeight = 0;
    var heightBase = parseInt(elementPassed.style.height);
    var heightOffset = parseInt(elementPassed.offsetHeight);
    var heightScroll = parseInt(elementPassed.scrollHeight);
    var heightClient = parseInt(elementPassed.clientHeight);
    var heightNode = 0;
    var heightRects = 0;
    //
    if (DoBase) {
        if (heightBase > thisHeight) { thisHeight = heightBase; }
    }
    if (DoOffset) {
        if (heightOffset > thisHeight) { thisHeight = heightOffset; }
    }
    if (DoScroll) {
        if (heightScroll > thisHeight) { thisHeight = heightScroll; }
    }
    //
    if (thisHeight == 0) { thisHeight = heightClient; }
    //
    if (thisHeight == 0) { 
        // Dom Add:
        // all else failed so use the protype approach...
        var elBodyTempContainer = document.getElementById('BodyTempContainer');
        elBodyTempContainer.appendChild(elementPassed);
        heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
        elBodyTempContainer.removeChild(elementPassed);
        if (heightNode > thisHeight) { thisHeight = heightNode; }
        //
        // Bounding Rect:
        // Or this approach...
        var clientRects = elementPassed.getClientRects();
        heightRects = clientRects.height;
        if (heightRects > thisHeight) { thisHeight = heightRects; }
    }
    //
    // Default height not appropriate here
    // if (thisHeight == 0) { thisHeight = elementHeightDefault; }
    if (thisHeight > 3000) {
        // ERROR
        thisHeight = 3000;
    }
    return thisHeight;
}

which basically tries anything and everything only to get a zero result. ClientHeight with no affect. With the problem elements I typically get NaN in the Base and zero in the Offset and Scroll heights. I then tried the Add DOM solution and clientRects to see if it works here.

29 Jun 2011, I did indeed update the code to try both adding to DOM and clientHeight with better results than I expected.

1) clientHeight was also 0.

2) Dom actually gave me a height which was great.

3) ClientRects returns a result almost identical to the DOM technique.

Because the elements added are fluid in nature, when they are added to an otherwise empty DOM Temp element they are rendered according to the width of that container. This get weird, because that is 30px shorter than it eventually ends up.

I added a few snapshots to illustrate how the height is calculated differently. Menu block rendered normally Menu block added to DOM Temp element

The height differences are obvious. I could certainly add absolute positioning and hidden but I am sure that will have no effect. I continued to be convinced this would not work!

(I digress further) The height comes out (renders) lower than the true rendered height. This could be addressed by setting the width of the DOM Temp element to match the existing parent and could be done fairly accurately in theory. I also do not know what would result from removing them and adding them back into their existing location. As they arrived through an innerHTML technique I will be looking using this different approach.

* HOWEVER * None of that was necessary. In fact it worked as advertised and returned the correct height!!!

When I was able to get the menus visible again amazingly DOM had returned the correct height per the fluid layout at the top of the page (279px). The above code also uses getClientRects which return 280px.

This is illustrated in the following snapshot (taken from Chrome once working.)
enter image description here

Now I have noooooo idea why that prototype trick works, but it seems to. Alternatively, getClientRects also works.

I suspect the cause of all this trouble with these particular elements was the use of innerHTML instead of appendChild, but that is pure speculation at this point.

How to close a web page on a button click, a hyperlink or a link button click?

Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.

Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close

    private void myNewButton_Click(object sender, EventArgs e) {
        this.Close();
    }

And that should be it.

The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

I'm trying to use python in powershell

  1. download Nodejs for windows
  2. install node-vxxx.msi
  3. find "Install Additional Tools for Node.js" script
  4. open and install it
  5. reopen a new shell prompt, type "python" >> press "enter" >> it works!!

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

  1. Check if compatible Mysql for your PHP version is correctly installed. (eg. mysql-installer-community-5.5.40.1.msi for PHP 5.2.10, apache 2.2 and phpMyAdmin 3.5.2)
  2. In your php\php.ini set your loadable php extensions path (eg. extension_dir = "C:\php\ext") (https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)
  3. (In your php\php.ini) check if extension=php_mysqli.dll is uncommented (https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)
  4. Set your php folder (eg."C:\php") and php\ext folder (eg."C:\php\ext") as your runtime environment variable path (https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)
  5. Restart apache service (https://drive.google.com/open?id=1kJF5kxPSrj3LdKWJcJTos9ecKFx0ORAW)

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

My tricky solution is:

  1. Open your windows Task Manager,
  2. Find the Javaw.exe process and highlight it, then End it by End Process
  3. In eclipse project browser, right click it and use Maven -> Update Project again.

Issue is resolved.

If you have Tomcat Server Running in Eclipse, you need to refresh project before restart Tomcat Server.

AngularJS - get element attributes values

If you are using Angular2+ following code will help

You can use following syntax to get attribute value from html element

//to retrieve html element

const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p

//get attribute value from that element

  const attributeValue = element.attributeName // like textContent/href

Equal sized table cells to fill the entire width of the containing table

Just use percentage widths and fixed table layout:

<table>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>
</table>

with

table { table-layout: fixed; }
td { width: 33%; }

Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.

Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.

How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

https://github.com/leoselig/jsFancyScroll/

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

Return value from exec(@sql)

declare @nReturn int = 0 EXEC @nReturn = Stored Procedures

Alternative for frames in html5 using iframes

HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".

http://www.w3schools.com/html5/tag_iframe.asp

or you can use

<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>

Asp.net Hyperlink control equivalent to <a href="#"></a>

If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);

"findTop"!! The only one result!

Best way to select random rows PostgreSQL

The one with the ORDER BY is going to be the slower one.

select * from table where random() < 0.01; goes record by record, and decides to randomly filter it or not. This is going to be O(N) because it only needs to check each record once.

select * from table order by random() limit 1000; is going to sort the entire table, then pick the first 1000. Aside from any voodoo magic behind the scenes, the order by is O(N * log N).

The downside to the random() < 0.01 one is that you'll get a variable number of output records.


Note, there is a better way to shuffling a set of data than sorting by random: The Fisher-Yates Shuffle, which runs in O(N). Implementing the shuffle in SQL sounds like quite the challenge, though.

Resize a large bitmap file to scaled output file on Android

Taking into account that you want to resize to exact size and want to keep as much quality as needed I think you should try this.

  1. Find out the size of the resized image with call of BitmapFactory.decodeFile and providing the checkSizeOptions.inJustDecodeBounds
  2. Calculate the maximum possible inSampleSize you can use on your device to not exceed the memory. bitmapSizeInBytes = 2*width*height; Generally for your picture inSampleSize=2 would be fine since you will need only 2*1944x1296)=4.8Mb? which should feet in memory
  3. Use BitmapFactory.decodeFile with inSampleSize to load the Bitmap
  4. Scale the bitmap to exact size.

Motivation: multiple-steps scaling could give you higher quality picture, however there is no guarantee that it will work better than using high inSampleSize. Actually, I think that you also can use inSampleSize like 5 (not pow of 2) to have direct scaling in one operation. Or just use 4 and then you can just use that image in UI. if you send it to server - than you can do scaling to exact size on server side which allow you to use advanced scaling techniques.

Notes: if the Bitmap loaded in step-3 is at least 4 times larger (so the 4*targetWidth < width) you probably can use several resizing to achieve better quality. at least that works in generic java, in android you don't have the option to specify the interpolation used for scaling http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

3 column layout HTML/CSS

This is less for @easwee and more for others that might have the same question:

If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.

With the current, final standard, you would be done with

.container {
    display: flex;
}

.container div {
    flex: 1;
}

.column_center {
    order: 2;
}

That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into

.container {
    display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;      /* TWEENER - IE 10 */
    display: -webkit-flex;     /* NEW - Chrome */
    display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.container div {
    -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1;         /* OLD - Firefox 19- */
    -webkit-flex: 1;          /* Chrome */
    -ms-flex: 1;              /* IE 10 */
    flex: 1;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.column_center {
    -webkit-box-ordinal-group: 2;   /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-ordinal-group: 2;      /* OLD - Firefox 19- */
    -ms-flex-order: 2;              /* TWEENER - IE 10 */
    -webkit-order: 2;               /* NEW - Chrome */
    order: 2;                       /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

jsFiddle demo

Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New

How can I get a specific parameter from location.search?

A Simple One-Line Solution:

let query = Object.assign.apply(null, location.search.slice(1).split('&').map(entry => ({ [entry.split('=')[0]]: entry.split('=')[1] })));

Expanded & Explained:

// define variable
let query;

// fetch source query
query = location.search;

// skip past the '?' delimiter
query = query.slice(1);

// split source query by entry delimiter
query = query.split('&');

// replace each query entry with an object containing the query entry
query = query.map((entry) => {

   // get query entry key
   let key = entry.split('=')[0];

   // get query entry value
   let value = entry.split('=')[1];

   // define query object
   let container = {};

   // add query entry to object
   container[key] = value;

   // return query object
   return container;
});

// merge all query objects
query = Object.assign.apply(null, query);

"No such file or directory" but it exists

I found my solution for my Ubuntu 18 here.

sudo dpkg --add-architecture i386

Then:

sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386

Passing an array of parameters to a stored procedure

You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.

CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
    DELETE YourTable
    FROM YourTable                    
    LEFT OUTER JOIN #temp T ON T.myid=s.id
    WHERE s.id IS NULL
END

Converting a String to DateTime

String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);

this one gives you

2019-08-17 11:14:49.000

Posting raw image data as multipart/form-data in curl

CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA

// files to upload

$filename = "https://example.s3.amazonaws.com/0.jpg";       

// URL to upload to (Destination server)

$url = "https://otherserver/image";

AND

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        //CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => file_get_contents($filename),
        CURLOPT_HTTPHEADER => array(
            //"Authorization: Bearer $TOKEN",
            "Content-Type: multipart/form-data",
            "Content-Length: " . strlen(file_get_contents($filename)),
            "API-Key: abcdefghi" //Optional if required
        ),
    ));

   $response = curl_exec($curl);

    $info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";

//print_r($info['request_header']);

    var_dump($response);
    $err = curl_error($curl);

    echo "error";
    var_dump($err);
    curl_close($curl);

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

The private key password defined in your app/config is incorrect. First try verifying the the private key password by changing to another one as follows:

keytool -keypasswd -new changeit -keystore cacerts -storepass changeit -alias someapp -keypass password

The above example changes the password from password to changeit. This command will succeed if the private key password was password.

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

I've had exactly the same problem as you for a while now, and after looking at some of the suggestions above, I finally solved the problem.

It turns out (at least for me anyway), I needed to supply a key (a prop called 'key') to the component I am returning from my renderSeparator method. Adding a key to my renderRow or renderSectionHeader didn't do anything, but adding it to renderSeparator made the warning go away.

Hope that helps.

Javadoc link to method in other class

For the Javadoc tag @see, you don't need to use @link; Javadoc will create a link for you. Try

@see com.my.package.Class#method()

Here's more info about @see.

Generate an integer that is not among four billion given ones

I think this is a solved problem (see above), but there's an interesting side case to keep in mind because it might get asked:

If there are exactly 4,294,967,295 (2^32 - 1) 32-bit integers with no repeats, and therefore only one is missing, there is a simple solution.

Start a running total at zero, and for each integer in the file, add that integer with 32-bit overflow (effectively, runningTotal = (runningTotal + nextInteger) % 4294967296). Once complete, add 4294967296/2 to the running total, again with 32-bit overflow. Subtract this from 4294967296, and the result is the missing integer.

The "only one missing integer" problem is solvable with only one run, and only 64 bits of RAM dedicated to the data (32 for the running total, 32 to read in the next integer).

Corollary: The more general specification is extremely simple to match if we aren't concerned with how many bits the integer result must have. We just generate a big enough integer that it cannot be contained in the file we're given. Again, this takes up absolutely minimal RAM. See the pseudocode.

# Grab the file size
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
# Print a '2' for every bit of the file.
for (c=0; c<sz; c++) {
  for (b=0; b<4; b++) {
    print "2";
  }
}

OS X Terminal Colors

MartinVonMartinsgrün and 4Levels methods confirmed work great on Mac OS X Mountain Lion.

The file I needed to update was ~/.profile.

However, I couldn't leave this question without recommending my favorite application, iTerm 2.

iTerm 2 lets you load global color schemes from a file. Really easy to experiment and try a bunch of color schemes.

Here's a screenshot of the iTerm 2 window and the color preferences. iTerm2 Color Preferences Screenshot Mac

Once I added the following to my ~/.profile file iTerm 2 was able to override the colors.

export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

Here is a great repository with some nice presets:

iTerm2 Color Schemes on Github by mbadolato

Bonus: Choose "Show/hide iTerm2 with a system-wide hotkey" and bind the key with BetterTouchTool for an instant hide/show the terminal with a mouse gesture.

Converting year and month ("yyyy-mm" format) to a date?

You could also achieve this with the parse_date_time or fast_strptime functions from the lubridate-package:

> parse_date_time(dates1, "ym")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"

> fast_strptime(dates1, "%Y-%m")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"

The difference between those two is that parse_date_time allows for lubridate-style format specification, while fast_strptime requires the same format specification as strptime.

For specifying the timezone, you can use the tz-parameter:

> parse_date_time(dates1, "ym", tz = "CET")
[1] "2009-01-01 CET" "2009-02-01 CET" "2009-03-01 CET"

When you have irregularities in your date-time data, you can use the truncated-parameter to specify how many irregularities are allowed:

> parse_date_time(dates2, "ymdHMS", truncated = 3)
[1] "2012-06-01 12:23:00 UTC" "2012-06-01 12:00:00 UTC" "2012-06-01 00:00:00 UTC"

Used data:

dates1 <- c("2009-01","2009-02","2009-03")
dates2 <- c("2012-06-01 12:23","2012-06-01 12",'2012-06-01")

Java - Check if JTextField is empty or not

The following will return true if the JTextField "name" does not contain text:

name.getText().isEmpty

Create new XML file and write data to it?

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();

$doc->add('Album', true)
        ->add('Track', 'Track Title');

$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');

$doc->query('//Track')
        ->attr('id', 123);

https://github.com/servo-php/fluidxml

fill an array in C#

Write yourself an extension method

public static class ArrayExtensions {
    public static void Fill<T>(this T[] originalArray, T with) {
        for(int i = 0; i < originalArray.Length; i++){
            originalArray[i] = with;
        }
    }  
}

and use it like

int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);

will fill all the elements with 13

What does the 'static' keyword do in a class?

static methods don't use any instance variables of the class they are defined in. A very good explanation of the difference can be found on this page

How do I get an Excel range using row and column numbers in VSTO / C#?

Where the range is multiple cells:

Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,3]);

Where range is one cell:

Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.Cells[1, 1];

Where do I call the BatchNormalization function in Keras?

Adding another entry for the debate about whether batch normalization should be called before or after the non-linear activation:

In addition to the original paper using batch normalization before the activation, Bengio's book Deep Learning, section 8.7.1 gives some reasoning for why applying batch normalization after the activation (or directly before the input to the next layer) may cause some issues:

It is natural to wonder whether we should apply batch normalization to the input X, or to the transformed value XW+b. Io?e and Szegedy (2015) recommend the latter. More speci?cally, XW+b should be replaced by a normalized version of XW. The bias term should be omitted because it becomes redundant with the ß parameter applied by the batch normalization reparameterization. The input to a layer is usually the output of a nonlinear activation function such as the recti?ed linear function in a previous layer. The statistics of the input are thus more non-Gaussian and less amenable to standardization by linear operations.

In other words, if we use a relu activation, all negative values are mapped to zero. This will likely result in a mean value that is already very close to zero, but the distribution of the remaining data will be heavily skewed to the right. Trying to normalize that data to a nice bell-shaped curve probably won't give the best results. For activations outside of the relu family this may not be as big of an issue.

Keep in mind that there are reports of models getting better results when using batch normalization after the activation, while others get best results when the batch normalization is placed before the activation. It is probably best to test your model using both configurations, and if batch normalization after activation gives a significant decrease in validation loss, use that configuration instead.

Gradle error: could not execute build using gradle distribution

This happened to me after a java update, few things to check if you are sure your path has been set before:

  1. if the path doesn't match the latest java install folder, change it (if your in eclipse check the eclipse.ini too to make sure your using your systems default vm (ie no VM tag) )

  2. go to the java directory, there should be a 'jdk' and a 'jre' in the path, for example:

    C:\Program Files (x86)\Java\jdk1.8.0_72\jre
    

    if not you probably installed the JRE only not the JDK that

  3. finally if the lib folder of the jdk (not jre) doesnt contain tools.jar then you have a problem with the install

Pdf.js: rendering a pdf file using a base64 file source instead of url

According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData}); Codetoffel answer does work just fine for me though.

What is SELF JOIN and when would you use it?

You use a self join when a table references data in itself.

E.g., an Employee table may have a SupervisorID column that points to the employee that is the boss of the current employee.

To query the data and get information for both people in one row, you could self join like this:

select e1.EmployeeID, 
    e1.FirstName, 
    e1.LastName,
    e1.SupervisorID, 
    e2.FirstName as SupervisorFirstName, 
    e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

Breaking a list into multiple columns in Latex

I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.

Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!

How to put multiple statements in one line?

Yes this post is 8 years old, but incase someone comes on here also looking for an answer: you can now just use semicolons. However, you cannot use if/elif/else staments, for/while loops, and you can't define functions. The main use of this would be when using imported modules where you don't have to define any functions or use any if/elif/else/for/while statements/loops.

Here's an example that takes the artist of a song, the song name, and searches genius for the lyrics:

import bs4, requests; song = input('Input artist then song name\n'); print(bs4.BeautifulSoup(requests.get(f'https://genius.com/{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())

DTO pattern: Best way to copy properties between two objects

You can use reflection to find all the get methods in your DAO objects and call the equivalent set method in the DTO. This will only work if all such methods exist. It should be easy to find example code for this.

Disable click outside of bootstrap modal area to close modal

You can use an attribute like this: data-backdrop="static" or with javascript:

$('#myModal').modal({
    backdrop: 'static',
    keyboard: false  // to prevent closing with Esc button (if you want this too)
})

See this answer too: Disallow twitter bootstrap modal window from closing

How to edit the size of the submit button on a form?

<input type="button" value="submit" style="height: 100px; width: 100px; left: 250; top: 250;">

Use this with your requirements.

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

Column name or number of supplied values does not match table definition

Dropping the table was not an option for me, since I'm keeping a running log. If every time I needed to insert I had to drop, the table would be meaningless.

My error was because I had a couple columns in the create table statement that were products of other columns, changing these fixed my problem. eg

create table foo (
field1 as int
,field2 as int
,field12 as field1 + field2 )

create table copyOfFoo (
field1 as int
,field2 as int
,field12 as field1 + field2)  --this is the problem, should just be 'as int'

insert into copyOfFoo
SELECT * FROM foo

Save multiple sheets to .pdf

Start by selecting the sheets you want to combine:

ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
     IgnorePrintAreas:=False, OpenAfterPublish:=True

How can I disable an <option> in a <select> based on its value in JavaScript?

Pure Javascript

With pure Javascript, you'd have to cycle through each option, and check the value of it individually.

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  (op[i].value.toLowerCase() == "stackoverflow") 
    ? op[i].disabled = true 
    : op[i].disabled = false ;
}

Without enabling non-targeted elements:

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  if (op[i].value.toLowerCase() == "stackoverflow") {
    op[i].disabled = true;
  }
}

jQuery

With jQuery you can do this with a single line:

$("option[value='stackoverflow']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

Without enabling non-targeted elements:

$("option[value='stackoverflow']").attr("disabled", "disabled");

? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
  }
});

Without enabling non-targeted elements:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled");
  }
});

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

How to have a default option in Angular.js select box

The accepted answer use ng-init, but document says to avoid ng-init if possible.

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

You also can use ng-repeat instead of ng-options for your options. With ng-repeat, you can use ng-selected with ng-repeat special properties. i.e. $index, $odd, $even to make this work without any coding.

$first is one of the ng-repeat special properties.

  <select ng-model="foo">
    <option ng-selected="$first" ng-repeat="(id,value) in myOptions" value="{{id}}">
      {{value}}
    </option>
  </select>

---------------------- EDIT ----------------
Although this works, I would prefer @mik-t's answer when you know what value to select, https://stackoverflow.com/a/29564802/454252, which uses track-by and ng-options without using ng-init or ng-repeat.

This answer should only be used when you must select the first item without knowing what value to choose. e.g., I am using this for auto completion which requires to choose the FIRST item all the time.

Clear text from textarea with selenium

for java

driver.findelement(By.id('foo').clear();

or

webElement.clear();

If this element is a text entry element, this will clear the value.

Ordering by specific field value first

Generally you can do

select * from your_table
order by case when name = 'core' then 1 else 2 end,
         priority 

Especially in MySQL you can also do

select * from your_table
order by name <> 'core',
         priority 

Since the result of a comparision in MySQL is either 0 or 1 and you can sort by that result.