Programs & Examples On #Viewusercontrol

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

If you add this to your web.config transformation file, you can also set certain publish options to have debugging enabled or disabled:

<system.web>
    <customErrors mode="Off" defaultRedirect="~/Error.aspx" xdt:Transform="Replace"/>
</system.web>

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

C# compiler have only lambda

arg => arg.MyProperty

for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.

How to convert View Model into JSON object in ASP.NET MVC?

Extending the great answer from Dave. You can create a simple HtmlHelper.

public static IHtmlString RenderAsJson(this HtmlHelper helper, object model)
{
    return helper.Raw(Json.Encode(model));
}

And in your view:

@Html.RenderAsJson(Model)

This way you can centralize the logic for creating the JSON if you, for some reason, would like to change the logic later.

How to split a line into words separated by one or more spaces in bash?

More simple,

echo $line | sed 's/\s/\n/g'

\s --> whitespace character (space, tab, NL, FF, VT, CR). In many systems also valid [:space:]

\n --> new line

How can I get the current array index in a foreach loop?

In your sample code, it would just be $key.

If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:

$i = -1;
foreach($arr as $val) {
  $i++;
  //$i is now the index.  if $i == 0, then this is the first element.
  ...
}

Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.

Apache is downloading php files instead of displaying them

I had similar symptoms, yet another solution: in /etc/apache2/mods-enabled/php5.conf there was a helpful advice in the comment, which I followed:

# To re-enable php in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.

Usage of $broadcast(), $emit() And $on() in AngularJS

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.


Visual demo:

Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview

Demonstrates the method calls:

  $scope.$on('eventEmitedName', function(event, data) ...
  $scope.broadcastEvent
  $scope.emitEvent

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

What is the difference between Java RMI and RPC?

The only real difference between RPC and RMI is that there is objects involved in RMI: instead of invoking functions through a proxy function, we invoke methods through a proxy.

How to change shape color dynamically?

This works for me, with an initial xml resource:

example.setBackgroundResource(R.drawable.myshape);
GradientDrawable gd = (GradientDrawable) example.getBackground().getCurrent();
gd.setColor(Color.parseColor("#000000"));
gd.setCornerRadii(new float[]{30, 30, 30, 30, 0, 0, 30, 30});
gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6);

Result of the above: http://i.stack.imgur.com/hKUR7.png

Best practices for copying files with Maven

For a simple copy-tasks I can recommend copy-rename-maven-plugin. It's straight forward and simple to use:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>com.coderplus.maven.plugins</groupId>
        <artifactId>copy-rename-maven-plugin</artifactId>
        <version>1.0</version>
        <executions>
          <execution>
            <id>copy-file</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
              <destinationFile>target/someDir/environment.properties</destinationFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

If you would like to copy more than one file, replace the <sourceFile>...</destinationFile> part with

<fileSets>
  <fileSet>
    <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
    <destinationFile>target/someDir/environment.properties</destinationFile>
  </fileSet>
  <fileSet>
    <sourceFile>src/someDirectory/test.logback.xml</sourceFile>
    <destinationFile>target/someDir/logback.xml</destinationFile>
  </fileSet>                
</fileSets>

Furthermore you can specify multiple executions in multiple phases if needed, the second goal is "rename", which simply does what it says while the rest of the configuration stays the same. For more usage examples refer to the Usage-Page.

Note: This plugin can only copy files, not directories. (Thanks to @james.garriss for finding this limitation.)

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

How do I test a single file using Jest?

Jest will use what you pass as a regular expression pattern. That it will match for.

If you want to run a specific test file, then the best way to do it is to use the precise full path to it. (You can too specify a certain relative path like (src/XFolder/index.spec.ts)).

The easiest way to provide the full path being in the directory and in Linux is:

jest $PWD/index.spec.ts

Note the use of the variable $PWD.

Enter image description here

For Windows! (to be updated)

How to install bcmath module?

Try yum install php-bcmath. If you still can't find anything, try yum search bcmath to find the package name

Check if value exists in enum in TypeScript

export enum UserLevel {
  Staff = 0,
  Leader,
  Manager,
}

export enum Gender {
  None = "none",
  Male = "male",
  Female = "female",
}

Difference result in log:

log(Object.keys(Gender))
=>
[ 'None', 'Male', 'Female' ]

log(Object.keys(UserLevel))
=>
[ '0', '1', '2', 'Staff', 'Leader', 'Manager' ]

The solution, we need to remove key as a number.

export class Util {
  static existValueInEnum(type: any, value: any): boolean {
    return Object.keys(type).filter(k => isNaN(Number(k))).filter(k => type[k] === value).length > 0;
  }
}

Usage

// For string value
if (!Util.existValueInEnum(Gender, "XYZ")) {
  //todo
}

//For number value, remember cast to Number using Number(val)
if (!Util.existValueInEnum(UserLevel, 0)) {
  //todo
}

How do you get the list of targets in a makefile?

For a Bash Script

Here's a very simple way to do this in bash -- based on the comment by @cibercitizen1 above:

grep : Makefile | awk -F: '/^[^.]/ {print $1;}'

See also the more authoritative answer by @Marc.2377, too, which says how the Bash completion module for make does it.

node.js: read a text file into an array. (Each line an item in the array.)

Essentially this will do the job: .replace(/\r\n/g,'\n').split('\n'). This works on Mac, Linux & Windows.

Code Snippets

Synchronous:

const { readFileSync } = require('fs');

const array = readFileSync('file.txt').toString().replace(/\r\n/g,'\n').split('\n');

for(let i of array) {
    console.log(i);
}

Asynchronous:

With the fs.promises API that provides an alternative set of asynchronous file system methods that return Promise objects rather than using callbacks. (No need to promisify, you can use async-await with this too, available on and after Node.js version 10.0.0)

const { readFile } = require('fs').promises;

readFile('file.txt', function(err, data) {
    if(err) throw err;

    const arr = data.toString().replace(/\r\n/g,'\n').split('\n');

    for(let i of arr) {
        console.log(i);
    }
});

More about \r & \n here: \r\n, \r and \n what is the difference between them?

Exploring Docker container's file system

UPDATE: EXPLORING!

This command should let you explore a running docker container:

docker exec -it name-of-container bash

The equivalent for this in docker-compose would be:

docker-compose exec web bash

(web is the name-of-service in this case and it has tty by default.)

Once you are inside do:

ls -lsa

or any other bash command like:

cd ..

This command should let you explore a docker image:

docker run --rm -it --entrypoint=/bin/bash name-of-image

once inside do:

ls -lsa

or any other bash command like:

cd ..

The -it stands for interactive... and tty.


This command should let you inspect a running docker container or image:

docker inspect name-of-container-or-image

You might want to do this and find out if there is any bash or sh in there. Look for entrypoint or cmd in the json return.

NOTE: This answer relies on commen tool being present, but if there is no bash shell or common tools like ls present you could first add one in a layer if you have access to the Dockerfile: example for alpine:

RUN apk add --no-cache bash

Otherwise if you don't have access to the Dockerfile then just copy the files out of a newly created container and look trough them by doing:

docker create <image>  # returns container ID the container is never started.
docker cp <container ID>:<source_path> <destination_path>
docker rm <container ID>
cd <destination_path> && ls -lsah

see docker exec documentation

see docker-compose exec documentation

see docker inspect documentation

see docker create documentation

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

Why is __dirname not defined in node REPL?

I was running a script from batch file as SYSTEM user and all variables like process.cwd() , path.resolve() and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

// this should be the name of currently executed file
const currentFilename = 'index.js';

function veryHackyGetFolder() {
  try {
    throw new Error();
  } catch(e) {
    const fullMsg = e.stack.toString();
    const beginning = fullMsg.indexOf('file:///') + 8;
    const end = fullMsg.indexOf('\/' + currentFilename);
    const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
    return dir;
  }
}

Usage

const dir = veryHackyGetFolder();

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

Counting array elements in Perl

sub uniq {
    return keys %{{ map { $_ => 1 } @_ }};
}
my @my_array = ("a","a","b","b","c");
#print join(" ", @my_array), "\n";
my $a = join(" ", uniq(@my_array));
my @b = split(/ /,$a);
my $count = $#b;

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

MySQL SELECT DISTINCT multiple columns

Another simple way to do it is with concat()

SELECT DISTINCT(CONCAT(a,b)) AS cc FROM my_table GROUP BY (cc);

Stop form refreshing page on submit

Personally I like to validate the form on submit and if there are errors, just return false.

$('form').submit(function() {

    var error;

   if ( !$('input').val() ) {
        error = true
    }

    if (error) {
         alert('there are errors')
         return false
    }

});

http://jsfiddle.net/dfyXY/

get keys of json-object in JavaScript

The working code

_x000D_
_x000D_
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
    if(jsonData.hasOwnProperty(obj)){_x000D_
    for(var prop in jsonData[obj]){_x000D_
        if(jsonData[obj].hasOwnProperty(prop)){_x000D_
           alert(prop + ':' + jsonData[obj][prop]);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_

UIScrollView scroll to bottom programmatically

CGFloat yOffset = scrollView.contentOffset.y;

CGFloat height = scrollView.frame.size.height;

CGFloat contentHeight = scrollView.contentSize.height;

CGFloat distance = (contentHeight  - height) - yOffset;

if(distance < 0)
{
    return ;
}

CGPoint offset = scrollView.contentOffset;

offset.y += distance;

[scrollView setContentOffset:offset animated:YES];

Is it possible to read from a InputStream with a timeout?

Here is a way to get a NIO FileChannel from System.in and check for availability of data using a timeout, which is a special case of the problem described in the question. Run it at the console, don't type any input, and wait for the results. It was tested successfully under Java 6 on Windows and Linux.

import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;

public class Main {

    static final ByteBuffer buf = ByteBuffer.allocate(4096);

    public static void main(String[] args) {

        long timeout = 1000 * 5;

        try {
            InputStream in = extract(System.in);
            if (! (in instanceof FileInputStream))
                throw new RuntimeException(
                        "Could not extract a FileInputStream from STDIN.");

            try {
                int ret = maybeAvailable((FileInputStream)in, timeout);
                System.out.println(
                        Integer.toString(ret) + " bytes were read.");

            } finally {
                in.close();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /* unravels all layers of FilterInputStream wrappers to get to the
     * core InputStream
     */
    public static InputStream extract(InputStream in)
            throws NoSuchFieldException, IllegalAccessException {

        Field f = FilterInputStream.class.getDeclaredField("in");
        f.setAccessible(true);

        while( in instanceof FilterInputStream )
            in = (InputStream)f.get((FilterInputStream)in);

        return in;
    }

    /* Returns the number of bytes which could be read from the stream,
     * timing out after the specified number of milliseconds.
     * Returns 0 on timeout (because no bytes could be read)
     * and -1 for end of stream.
     */
    public static int maybeAvailable(final FileInputStream in, long timeout)
            throws IOException, InterruptedException {

        final int[] dataReady = {0};
        final IOException[] maybeException = {null};
        final Thread reader = new Thread() {
            public void run() {                
                try {
                    dataReady[0] = in.getChannel().read(buf);
                } catch (ClosedByInterruptException e) {
                    System.err.println("Reader interrupted.");
                } catch (IOException e) {
                    maybeException[0] = e;
                }
            }
        };

        Thread interruptor = new Thread() {
            public void run() {
                reader.interrupt();
            }
        };

        reader.start();
        for(;;) {

            reader.join(timeout);
            if (!reader.isAlive())
                break;

            interruptor.start();
            interruptor.join(1000);
            reader.join(1000);
            if (!reader.isAlive())
                break;

            System.err.println("We're hung");
            System.exit(1);
        }

        if ( maybeException[0] != null )
            throw maybeException[0];

        return dataReady[0];
    }
}

Interestingly, when running the program inside NetBeans 6.5 rather than at the console, the timeout doesn't work at all, and the call to System.exit() is actually necessary to kill the zombie threads. What happens is that the interruptor thread blocks (!) on the call to reader.interrupt(). Another test program (not shown here) additionally tries to close the channel, but that doesn't work either.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I don't think that x[[1,3]][:,[1,3]] is hardly readable. If you want to be more clear on your intent, you can do:

a[[1,3],:][:,[1,3]]

I am not an expert in slicing but typically, if you try to slice into an array and the values are continuous, you get back a view where the stride value is changed.

e.g. In your inputs 33 and 34, although you get a 2x2 array, the stride is 4. Thus, when you index the next row, the pointer moves to the correct position in memory.

Clearly, this mechanism doesn't carry well into the case of an array of indices. Hence, numpy will have to make the copy. After all, many other matrix math function relies on size, stride and continuous memory allocation.

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

In short, yes, the order is preserved. In long:

In general the following definitions will always apply to objects like lists:

A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa" can exist and != "a").

A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).

Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.

This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the + sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.

If we have

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]

Then

list1 + list2

Is the same as

[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]

Which evaluates to

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Much like

"abdcde" + "fghijk"

Produces

"abdcdefghijk"

MySQL DAYOFWEEK() - my week begins with monday

Could write a udf and take a value to tell it which day of the week should be 1 would look like this (drawing on answer from John to use MOD instead of CASE):

DROP FUNCTION IF EXISTS `reporting`.`udfDayOfWeek`;
DELIMITER |
CREATE FUNCTION `reporting`.`udfDayOfWeek` (
  _date DATETIME,
  _firstDay TINYINT
) RETURNS tinyint(4)
FUNCTION_BLOCK: BEGIN
  DECLARE _dayOfWeek, _offset TINYINT;
  SET _offset = 8 - _firstDay;
  SET _dayOfWeek = (DAYOFWEEK(_date) + _offset) MOD 7;
  IF _dayOfWeek = 0 THEN
    SET _dayOfWeek = 7;
  END IF;
  RETURN _dayOfWeek;
END FUNCTION_BLOCK

To call this function to give you the current day of week value when your week starts on a Tuesday for instance, you'd call:

SELECT udfDayOfWeek(NOW(), 3);

Nice thing about having it as a udf is you could also call it on a result set field like this:

SELECT
  udfDayOfWeek(p.SignupDate, 3) AS SignupDayOfWeek,
  p.FirstName,
  p.LastName
FROM Profile p;

Python 3: EOF when reading a line (Sublime Text 2 is angry)

help(input) shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:

input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.

You could reproduce it using an empty file:

$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
  File "<string>", line 1, in <module>
EOFError: EOF when reading a line

You could use /dev/null or nul (Windows) as an empty file for reading. os.devnull shows the name that is used by your OS:

$ python3 -c "import os; print(os.devnull)"
/dev/null

Note: input() happily accepts input from a file/pipe. You don't need stdin to be connected to the terminal:

$ echo abc | python3 -c "print(input()[::-1])"
cba

Either handle EOFError in your code:

try:
    reply = input('Enter text')
except EOFError:
    break

Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file

Currency Formatting in JavaScript

You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?

How do I remove a file from the FileList

If you have the luck to be sending a post request to the database with the files and you have the files you want to send in your DOM

you can simply check if the file in the file list is present in your DOM, and of course if it's not you just don't send that element to de DB.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...

Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:

https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new

The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.

For instance, where I had:

$_SERVER['SERVER_NAME']

I've put instead:

filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)

You have the filter_input and filters doc here:

http://www.php.net/manual/en/function.filter-input.php

http://www.php.net/manual/en/filter.filters.php

What does Include() do in LINQ?

Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.

The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.

On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.

Formatting struct timespec

You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

As some suggested here, replacing utf8mb4 with utf8 will help you resolve the issue. IMHO, I used sed to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is

sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql

Done!

How to get a variable value if variable name is stored as string?

Had the same issue with arrays, here is how to do it if you're manipulating arrays too :

array_name="ARRAY_NAME"
ARRAY_NAME=("Val0" "Val1" "Val2")

ARRAY=$array_name[@]
echo "ARRAY=${ARRAY}"
ARRAY=("${!ARRAY}")
echo "ARRAY=${ARRAY[@]}"
echo "ARRAY[0]=${ARRAY[0]}"
echo "ARRAY[1]=${ARRAY[1]}"
echo "ARRAY[2]=${ARRAY[2]}"

This will output :

ARRAY=ARRAY_NAME[@]
ARRAY=Val0 Val1 Val2
ARRAY[0]=Val0
ARRAY[1]=Val1
ARRAY[2]=Val2

Insert text with single quotes in PostgreSQL

String literals

Escaping single quotes ' by doubling them up -> '' is the standard way and works of course:

'user's log'     -- incorrect syntax (unbalanced quote)
'user''s log'

In old versions or if you still run with standard_conforming_strings = off or, generally, if you prepend your string with E to declare Posix escape string syntax, you can also escape with the backslash \:

E'user\'s log'

Backslash itself is escaped with another backslash. But that's generally not preferable.
If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with dollar-quoted strings:

'escape '' with '''''
$$escape ' with ''$$

To further avoid confusion among dollar-quotes, add a unique token to each pair:

$token$escape ' with ''$token$

Which can be nested any number of levels:

$token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$

Pay attention if the $ character should have special meaning in your client software. You may have to escape it in addition. This is not the case with standard PostgreSQL clients like psql or pgAdmin.

That is all very useful for writing plpgsql functions or ad-hoc SQL commands. It cannot alleviate the need to use prepared statements or some other method to safeguard against SQL injection in your application when user input is possible, though. @Craig's answer has more on that. More details:

Values inside Postgres

When dealing with values inside the database, there are a couple of useful functions to quote strings properly:

  • quote_literal() or quote_nullable() - the latter outputs the string NULL for null input. (There is also quote_ident() to double-quote strings where needed to get valid SQL identifiers.)
  • format() with the format specifier %L is equivalent to quote_nullable().
    Like: format('%L', string_var)
  • concat() or concat_ws() are typically no good for this purpose as those do not escape nested single quotes and backslashes.

Validating with an XML schema in Python

lxml provides etree.DTD

from the tests on http://lxml.de/api/lxml.tests.test_dtd-pysrc.html

...
root = etree.XML(_bytes("<b/>")) 
dtd = etree.DTD(BytesIO("<!ELEMENT b EMPTY>")) 
self.assert_(dtd.validate(root)) 

Class constructor type in typescript?

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

class Zoo<T extends Animal> {
    constructor(public readonly AnimalClass: new () => T) {
    }
}

This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.

const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.

How to run only one unit test class using Gradle

Run a single test called MyTest:

./gradlew app:testDebug --tests=com.example.MyTest

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

How to retrieve SQL result column value using column name in Python?

selecting values from particular column:

import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
    #query execution
    cursor.execute(sql)
    #fetch all rows 
    rs = cursor.fetchall()
    #iterate through rows
    for i in rs:
        #converting set to list
        k=list(i)
        #taking the first element from the list and append it to the list
        l.append(k[0])
    db.commit()
except:
    db.rollback()
db.close()
print(l)

How can I remove a child node in HTML using JavaScript?

To answer the original question - there are various ways to do this, but the following would be the simplest.

If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:

myChildNode.parentNode.removeChild(myChildNode);

Obviously, if you are not using one of the numerous libraries that already do this, you would want to create a function to abstract this out:

function removeElement(node) {
    node.parentNode.removeChild(node);
}

EDIT: As has been mentioned by others: if you have any event handlers wired up to the node you are removing, you will want to make sure you disconnect those before the last reference to the node being removed goes out of scope, lest poor implementations of the JavaScript interpreter leak memory.

ApiNotActivatedMapError for simple html page using google-places-api

To enable Api do this

  1. Go to API Manager
  2. Click on Overview
  3. Search for Google Maps JavaScript API(Under Google Maps APIs). Click on that
  4. You will find Enable button there. Click to enable API.

OR You can try this url: Maps JavaScript API

Hope this will solve the problem of enabling API.

Receiving JSON data back from HTTP request

Building on @Panagiotis Kanavos' answer, here's a working method as example which will also return the response as an object instead of a string:

using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // Nuget Package

public static async Task<object> PostCallAPI(string url, object jsonObject)
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
            var response = await client.PostAsync(url, content);
            if (response != null)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<object>(jsonString);
            }
        }
    }
    catch (Exception ex)
    {
        myCustomLogger.LogException(ex);
    }
    return null;
}

Keep in mind that this is only an example and that you'd probably would like to use HttpClient as a shared instance instead of using it in a using-clause.

Run a mySQL query as a cron job?

Try creating a shell script like the one below:

#!/bin/bash

mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

How to check python anaconda version installed on Windows 10 PC?

The folder containing your Anaconda installation contains a subfolder called conda-meta with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json.

My file is called anaconda-5.0.1-py27hdb50712_1.json, and at the bottom is more info about the version:

"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe", 
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" }, 
"name": "anaconda", 
"platform": "win", 
"subdir": "win-64", 
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2", 
"version": "5.0.1"

(Slightly edited for brevity.)

The output from conda -V is the conda version.

Set the layout weight of a TextView programmatically

This should works to you

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT LayoutParams.MATCH_PARENT);

param.weight=1.0f;

Can you force Vue.js to reload/re-render?

Worked for me

    data () {
        return {
            userInfo: null,
            offers: null
        }
    },

    watch: {
        '$route'() {
            this.userInfo = null
            this.offers = null
            this.loadUserInfo()
            this.getUserOffers()
        }
    }

How to overlay one div over another div

By using a div with style z-index:1; and position: absolute; you can overlay your div on any other div.

z-index determines the order in which divs 'stack'. A div with a higher z-index will appear in front of a div with a lower z-index. Note that this property only works with positioned elements.

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

Perform commands over ssh with Python

Asking User to enter the command as per the device they are logging in.
The below code is validated by PEP8online.com.

import paramiko
import xlrd
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0, 1)
Port = int(sheet.cell_value(3, 1))
User = sheet.cell_value(1, 1)
Pass = sheet.cell_value(2, 1)

def details(Host, Port, User, Pass):
    time.sleep(2)
    ssh.connect(Host, Port, User, Pass)
    print('connected to ip ', Host)
    stdin, stdout, stderr = ssh.exec_command("")
    x = input('Enter the command:')
    stdin.write(x)
    stdin.write('\n')
    print('success')

details(Host, Port, User, Pass)

change image opacity using javascript

In fact, you need to use CSS.

document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

It works on FireFox, Chrome and IE.

How to remove leading and trailing whitespace in a MySQL field?

If you need to use trim in select query, you can also use regular expressions

SELECT * FROM table_name WHERE field RLIKE ' * query-string *'

return rows with field like '      query-string   '

Git Clone: Just the files, please?

git checkout -f

There's another way to do this by splitting the repo from the working tree.

This method is useful if you need to update these git-less git files on a regular basis. For instance, I use it when I need to check out source files and build an artifact, then copy the artifact into a different repo just for deployment to a server, and I also use it when pushing source code to a server when I want the source code to checkout and build into the www directory.

We'll make two folders, one for the git one for the working files:

mkdir workingfiles
mkdir barerepo.git

initialize a bare git repo:

cd barerepo.git
git --bare init 

Then create a post-receive hook:

touch hooks/post-receive
chmod ug+x hooks/post-receive

Edit post-receive in your favorite editor:

GIT_WORK_TREE=/path/to/workingfiles git checkout -f
# optional stuff:
cd down/to/some/directory
[do some stuff]

Add this as a remote:

git remote add myserver ssh://user@host:/path/to/barerepo.git

Now every time you push to this bare repo it will checkout the working tree to /workingfiles/. But /workingfiles/ itself is not under version control; running git status in /workingfiles/ will give the error fatal: Not a git repository (or any parent up to mount point /data). It's just plain files.

Unlike other solutions rm -r .git command is not needed, so if /workingfiles/ is some other git repo you don't have to worry about the command used removing the other repo's git files.

Count number of occurrences of a pattern in a file (even on same line)

Try this:

grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c

Sample:

grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
  6  SMTP connect from unknown [188.190.118.90]
 54  SMTP connect from unknown [62.193.131.114]
  3  SMTP connect from unknown [91.222.51.253]

The application has stopped unexpectedly: How to Debug?

Check whether your app has the needed permissions.I was also getting the same error and I checked the logcat debug log which showed this:

04-15 13:38:25.387: E/AndroidRuntime(694): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:555-555-5555 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{44068640 694:rahulserver.test/10055} (pid=694, uid=10055) requires android.permission.CALL_PHONE

I then gave the needed permission in my android-manifest which worked for me.

How do I set the focus to the first input element in an HTML form independent from the id?

I'm using this:

$("form:first *:input,select,textarea").filter(":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])").first().focus();

jQuery append() - return appended elements

// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);

// append to the DOM
$("#myDiv").append($elements);

// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);

How to set text size in a button in html

Try this

<input type="submit" 
       value="HOME" 
       onclick="goHome()" 
       style="font-size : 20px; width: 100%; height: 100px;" /> 

ps1 cannot be loaded because running scripts is disabled on this system

Open terminal

Run the command: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

in terminal: yarn --version

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I got the same error message for two separate reasons, so you can add them to your debugging checklist:

Context: Xcode 6.4, iOS:8.4. I was adding a toolbar with custom UIBarButtons to load with the UIKeyboardTypeNumberPad (Swift: UIKeyboardType.numberPad) , namely "Done" and "+/-". I had this problem when:

  1. My UIToolbar was declared as a property, but I had forgotten to explicitly alloc/init it.

  2. I had left off the last line, [myCustomToolbar sizeToFit];, which sounds like it's the same family as Holden's answer (my code here: https://stackoverflow.com/a/32016397/4898050).

Good luck

Excel Date to String conversion

I have no idea about the year of publication of the question; it might be old now. So, I expect my answer to be more of a reference for future similar questions after my post.

I don't know if anybody out there has already given an answer similar to the one I am about to give, which might result -I think- being the simplest, most direct and most effective: If someone has already given it, I apologize, but I haven't seen it. Here, my answer using CStr instead of TEXT:

Asuming cell A1 contains a date, and using VBA code:

Dim strDate As String

'Convert to string the value contained in A1 (a date)
strDate = CStr([A1].Value)

You can, thereafter, manipulate it as any ordinary string using string functions (MID, LEFT, RIGHT, LEN, CONCATENATE (&), etc.)

When should I use Async Controllers in ASP.NET MVC?

Is it good to use async action everywhere in ASP.NET MVC?

It's good to do so wherever you can use an async method especially when you have performance issues at the worker process level which happens for massive data and calculation operations. Otherwise, no need because unit testing will need casting.

Regarding awaitable methods: shall I use async/await keywords when I want to query a database (via EF/NHibernate/other ORM)?

Yes, it's better to use async for any DB operation as could as possible to avoid performance issues at the level of worker processes. Note that EF has created many async alternatives for most operations, such as:

.ToListAsync()
.FirstOrDefaultAsync()
.SaveChangesAsync()
.FindAsync()

How many times can I use await keywords to query the database asynchronously in one single action method?

The sky is the limit

Passing an array of parameters to a stored procedure

I'd consider passing your IDs as an XML string, and then you could shred the XML into a temp table to join against, or you could also query against the XML directly using SP_XML_PREPAREDOCUMENT and OPENXML.

Best way to check if column returns a null value (from database to .net application)

Use DBNull.Value.Equals on the object without converting it to a string.

Here's an example:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }

How to install PHP mbstring on CentOS 6.2

I have experienced the same issue before. In my case, I needed to install php-mbstring extension on GoDaddy VPS server. None of above solutions did work for me.

What I've found is to install PHP extensions using WHM (Web Hosting Manager) of GoDaddy. Anyone who use GoDaddy VPS server can access this page with the following address.

http://{Your_Server_IP_Address}:2087

On this page, you can easily find Easy Apache software that can help you to install/upgrade php components and extensions. You can select currently installed profile and customize and then provision the profile. Everything with Easy Apache is explanatory.

I remember that I did very similar things for HostGator server, but I don't remember how actually I did for profile update.

Edit: When you have got the server which supports Web Hosting Manager, then you can add/update/remove php extensions on WHM. On godaddy servers, it's even recommended to update PHP ini settings on WHM.

Angular: Can't find Promise, Map, Set and Iterator

This is what worked for me.

check if there exists a typings.json file,

It looks something like this,

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160317120654",
    "jasmine": "registry:dt/jasmine#2.2.0+20160505161446",
    "node": "registry:dt/node#6.0.0+20160613154055"
  }
}

Install typings package globally.

sudo npm install -g typings

after installing typings, run

typings install

then restart the server.

How to tell which disk Windows Used to Boot

You can try use simple command line. bcdedit is what you need, just run cmd as administrator and type bcdedit or bcdedit \v, this doesn't work on XP, but hope it is not an issue.

Anyway for XP you can take a look into boot.ini file.

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

Java ArrayList of Arrays?

This works very well.

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be

Borkala

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

You do realize this is the default behavior, right? if you add /something the results would be different.

you can do a number of things to prevent default behavior.

href="#":

Will do nothing but anchor - not the best solution since it may jump to page top.

<a href="#">

href="javascript:void(0);"

Will do nothing at all and is perfectly legit.

<a href="javascript:void(0);"></a>

href="your-actual-intended-link" (Best)

obviously the best.

<a href="<your-actual-intended-link>"></a>

If you don't want an a tag to go somewhere, why use an a tag at all?

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

The first proposed solution is pretty close. If you use stop() instead of interrupt() it even kills runaway threads, that run endlessly in a groovy system script. This will kill any build, that runs for a job. Here is the code:

Thread.getAllStackTraces().keySet().each() {
    if (it.name.contains('YOUR JOBNAME')) {  
      println "Stopping $it.name"
      it.stop()
    }
}

Add a auto increment primary key to existing table in oracle

Snagged from Oracle OTN forums

Use alter table to add column, for example:

alter table tableName add(columnName NUMBER);

Then create a sequence:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

and, the use update to insert values in column like this

UPDATE tableName SET columnName = seq_test_id.NEXTVAL

Storing data into list with class

This line is your problem:

lstemail.Add("JOhn","Smith","Los Angeles");

There is no direct cast from 3 strings to your custom class. The compiler has no way of figuring out what you're trying to do with this line. You need to Add() an instance of the class to lstemail:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });

Convert varchar into datetime in SQL Server

Likely you have bad data that cannot convert. Dates should never be stored in varchar becasue it will allow dates such as ASAP or 02/30/2009. Use the isdate() function on your data to find the records which can't convert.

OK I tested with known good data and still got the message. You need to convert to a different format becasue it does not know if 12302009 is mmddyyyy or ddmmyyyy. The format of yyyymmdd is not ambiguous and SQL Server will convert it correctly

I got this to work:

cast( right(@date,4) + left(@date,4) as datetime)

You will still get an error message though if you have any that are in a non-standard format like '112009' or some text value or a true out of range date.

How can I get the current page's full URL on a Windows/IIS server?

Add:

function my_url(){
    $url = (!empty($_SERVER['HTTPS'])) ?
               "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
               "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    echo $url;
}

Then just call the my_url function.

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

C# how to convert File.ReadLines into string array?

Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

Bootstrap 3 panel header with buttons wrong position

In this case you should add .clearfix at the end of container with floated elements.

<div class="panel-heading">
    <h4>Panel header</h4>
    <div class="btn-group pull-right">
        <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
    </div>
    <span class="clearfix"></span>
</div>

http://www.bootply.com/NCXkOtIkD6

Android Starting Service at Boot Time , How to restart service class after device Reboot?

It's possible to register your own application service for starting automatically when the device has been booted. You need this, for example, when you want to receive push events from a http server and want to inform the user as soon a new event occurs. The user doesn't have to start the activity manually before the service get started...

It's quite simple. First give your app the permission RECEIVE_BOOT_COMPLETED. Next you need to register a BroadcastReveiver. We call it BootCompletedIntentReceiver.

Your Manifest.xml should now look like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.jjoe64">
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
 <application>
  <receiver android:name=".BootCompletedIntentReceiver">
   <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
  </receiver>
  <service android:name=".BackgroundService"/>
 </application>
</manifest>

As the last step you have to implement the Receiver. This receiver just starts your background service.

package com.jjoe64;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.jjoe64.BackgroundService;

public class BootCompletedIntentReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
  if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
   Intent pushIntent = new Intent(context, BackgroundService.class);
   context.startService(pushIntent);
  }
 }
}

From http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

How to debug a GLSL shader?

void main(){
  float bug=0.0;
  vec3 tile=texture2D(colMap, coords.st).xyz;
  vec4 col=vec4(tile, 1.0);

  if(something) bug=1.0;

  col.x+=bug;

  gl_FragColor=col;
}

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Xampp Access Forbidden php

Did you change any thing on the virtual-host before it stop working ?

Add this line to xampp/apache/conf/extra/httpd-vhosts.conf

<VirtualHost localhost:80>
    DocumentRoot "C:/xampp/htdocs"
    ServerAdmin localhost
    <Directory "C:/xampp/htdocs">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Laravel is there a way to add values to a request array

enough said on this subject but i couldn't resist to add my own answer. I believe the simplest approach is

request()->merge([ 'foo' => 'bar' ]);

How to read the value of a private field from a different class in Java?

You can use Manifold's @JailBreak for direct, type-safe Java reflection:

@JailBreak Foo foo = new Foo();
foo.stuffIWant = "123;

public class Foo {
    private String stuffIWant;
}

@JailBreak unlocks the foo local variable in the compiler for direct access to all the members in Foo's hierarchy.

Similarly you can use the jailbreak() extension method for one-off use:

foo.jailbreak().stuffIWant = "123";

Through the jailbreak() method you can access any member in Foo's hierarchy.

In both cases the compiler resolves the field access for you type-safely, as if a public field, while Manifold generates efficient reflection code for you under the hood.

Discover more about Manifold.

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

Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?

List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the  map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.

You can easily do it like the above.

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

The solution is definitely "spring-security-config" not in your WEB-INF/lib.

For my project in Eclipse using Maven, it turned out not all of the maven dependencies were being copied to WEB-INF/lib. Looking at Project -> Properties -> Deployment Assembly, only some of the jars were being copied.

To fix this, I clicked "Add", then "Java Build Path Entires" and finally "Maven Dependencies".

I have been searching SO and the web for the last hour looking for this, so hopefully this helps someone else.

Python syntax for "if a or b or c but not all of them"

How about:

conditions = [a, b, c]
if any(conditions) and not all(conditions):
   ...

Other variant:

if 1 <= sum(map(bool, conditions)) <= 2:
   ...

How to convert JSON data into a Python object

The lightest solution I think is

import json
from typing import NamedTuple

_j = '{"name":"????","age":37,"mother":{"name":"?????","age":58},"children":["????","?????","????"],"married": true,' \
     '"dog":null} '


class PersonNameAge(NamedTuple):
    name: str
    age: int


class UserInfo(NamedTuple):
    name: str
    age: int
    mother: PersonNameAge
    children: list
    married: bool
    dog: str


j = json.loads(_j)
u = UserInfo(**j)

print(u.name, u.age, u.mother, u.children, u.married, u.dog)

>>> Ivan 37 {'name': 'Olga', 'age': 58} ['Mary', 'Igor', 'Jane'] True None

Checking if sys.argv[x] is defined

I use this - it never fails:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

what is trailing whitespace and how can I handle this?

Trailing whitespace:

It is extra spaces (and tabs) at the end of line      
                                                 ^^^^^ here

Strip them:

#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""

import sys

if len(sys.argv[1:]) != 1:
  sys.exit(__doc__)

content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
  content = infile.read()
with open(outp, 'wb') as output:
  for line in content.splitlines():
    newline = line.rstrip(" \t")
    outsize += len(newline) + 1
    output.write(newline + '\n')

print("Done. Stripped %s bytes." % (len(content)-outsize))

https://gist.github.com/techtonik/c86f0ea6a86ed3f38893

How to assign a select result to a variable?

In order to assign a variable safely you have to use the SET-SELECT statement:

SET @PrimaryContactKey = (SELECT c.PrimaryCntctKey
    FROM tarcustomer c, tarinvoice i
    WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key)

Make sure you have both a starting and an ending parenthesis!

The reason the SET-SELECT version is the safest way to set a variable is twofold.

1. The SELECT returns several posts

What happens if the following select results in several posts?

SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key

@PrimaryContactKey will be assigned the value from the last post in the result.

In fact @PrimaryContactKey will be assigned one value per post in the result, so it will consequently contain the value of the last post the SELECT-command was processing.

Which post is "last" is determined by any clustered indexes or, if no clustered index is used or the primary key is clustered, the "last" post will be the most recently added post. This behavior could, in a worst case scenario, be altered every time the indexing of the table is changed.

With a SET-SELECT statement your variable will be set to null.

2. The SELECT returns no posts

What happens, when using the second version of the code, if your select does not return a result at all?

In a contrary to what you may believe the value of the variable will not be null - it will retain it's previous value!

This is because, as stated above, SQL will assign a value to the variable once per post - meaning it won't do anything with the variable if the result contains no posts. So, the variable will still have the value it had before you ran the statement.

With the SET-SELECT statement the value will be null.

See also: SET versus SELECT when assigning variables?

Client on Node.js: Uncaught ReferenceError: require is not defined

Even using this won't work. I think the best solution is Browserify:

module.exports = {
  func1: function () {
   console.log("I am function 1");
  },
  func2: function () {
    console.log("I am function 2");
  }
};

-getFunc1.js-
var common = require('./common');
common.func1();

Android, How can I Convert String to Date?

String source = "24/10/17";

String[] sourceSplit= source.split("/");

int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);

    GregorianCalendar calendar = new GregorianCalendar();
  calendar.set(anno,mese-1,giorno);
  Date   data1= calendar.getTime();
  SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");

    String   dayFormatted= myFormat.format(data1);

    System.out.println("data formattata,-->"+dayFormatted);

jQuery hide and show toggle div with plus and minus icon

this works:

http://jsfiddle.net/UhEut/

CSS:

.show_hide {
    display:none;
}
.plus:after {
    content:" +";
}
.minus:after {
    content:" -";
}

jQuery:

$(document).ready(function(){
  $(".slidingDiv").hide();
  $(".show_hide").addClass("plus").show();
  $('.show_hide').toggle(
      function(){
          $(".slidingDiv").slideDown();
          $(this).addClass("minus");
          $(this).removeClass("plus");
      },
      function(){
          $(".slidingDiv").slideUp();
          $(this).addClass("plus");
          $(this).removeClass("minus");
      }
  );
});

HTML:

<a href="#" class="show_hide">Show/hide</a>

<div class="slidingDiv" style="display: block;">
Check out the updated jQuery plugin for doing this: <a href="http://papermashup.com/jquery-show-hide-plugin/" class="show_hide" target="_blank" style="display: inline;">jQuery Show / Hide Plugin</a>
</div>

in the CSS, instead of content:" +"; You can put an background-image (with background-position:right center; and background-repeat:no-repeat and maybe making the .show_hide displayed as block and give him a width, so that the bg-image is not overlayed by the link-text itself).

PHP-FPM and Nginx: 502 Bad Gateway

You should see the error log. By default, its location is in /var/log/nginx/error.log

In my case, 502 get way because of:

GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:28 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"

When we know exactly what is wrong, then fix it. For these error, just modify the buffer:

fastcgi_buffers 16 512k; 
fastcgi_buffer_size 512k;

How to set locale in DatePipe in Angular 2?

With angular5 the above answer no longer works!

The following code:

app.module.ts

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
    //otherProviders...
  ]
})

Leads to following error:

Error: Missing locale data for the locale "de-at".

With angular5 you have to load and register the used locale file on your own.

app.module.ts

import { NgModule, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeDeAt from '@angular/common/locales/de-at';

registerLocaleData(localeDeAt);

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
    //otherProviders...
  ]
})

Documentation

When to use static classes in C#

For C# 3.0, extension methods may only exist in top-level static classes.

Encrypt Password in Configuration Files?

Depending on how secure you need the configuration files or how reliable your application is, http://activemq.apache.org/encrypted-passwords.html may be a good solution for you.

If you are not too afraid of the password being decrypted and it can be really simple to configure using a bean to store the password key. However, if you need more security you can set an environment variable with the secret and remove it after launch. With this you have to worry about the application / server going down and not application not automatically relaunching.

Check if a radio button is checked jquery

Something like this:

 $("input[name=test]").is(":checked");

Using the jQuery is() function should work.

Changing the page title with Jquery

Its very simple way to change the page title with jquery..

<a href="#" id="changeTitle">Click!</a>

Here the Jquery method:

$(document).ready(function(){   
    $("#changeTitle").click(function() {
       $(document).prop('title','I am New One');
    });
});

How to link to a named anchor in Multimarkdown?

If you have headers in the markdown files, you can directly link them in the file.

Markdown Header -

## The Header

this will generate an implicit id #the-header (replace internal spaces with hyphens and make lowercase).

To navigate to this id, you can create the link like this:

[Link to Header](#the-header)

This is equivalent to:

<a href="#the-header">Link to Header</a>

Please note the reference's name is a lower-case #header.

SQL sum with condition

With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.

SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch 
AND t1.transID = t2.transID
AND ValueDate > @startMonthDate HAVING money > 0;

Escape double quote character in XML

New, improved answer to an old, frequently asked question...

When to escape double quote in XML

Double quote (") may appear without escaping:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Note: switching to single quotes (') also requires no escaping:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

Double quote (") must be escaped:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Bottom line

Double quote (") must be escaped as &quot; in XML only in very limited contexts.

Uncaught (in promise) TypeError: Failed to fetch and Cors error

In my case, the problem was the protocol. I was trying to call a script url with http instead of https.

"End of script output before headers" error in Apache

Internal error is due to a HIDDEN character at end of shebang line !! ie line #!/usr/bin/perl

By adding - or -w at end moves the character away from "perl" allowing the path to the perl processor to be found and script to execute.

HIDDEN character is created by the editor used to create the script

How to group subarrays by a column value?

You can try the following:

$group = array();

foreach ( $array as $value ) {
    $group[$value['id']][] = $value;
}

var_dump($group);

Output:

array
  96 => 
    array
      0 => 
        array
          'id' => int 96
          'shipping_no' => string '212755-1' (length=8)
          'part_no' => string 'reterty' (length=7)
          'description' => string 'tyrfyt' (length=6)
          'packaging_type' => string 'PC' (length=2)
      1 => 
        array
          'id' => int 96
          'shipping_no' => string '212755-1' (length=8)
          'part_no' => string 'dftgtryh' (length=8)
          'description' => string 'dfhgfyh' (length=7)
          'packaging_type' => string 'PC' (length=2)
  97 => 
    array
      0 => 
        array
          'id' => int 97
          'shipping_no' => string '212755-2' (length=8)
          'part_no' => string 'ZeoDark' (length=7)
          'description' => string 's%c%s%c%s' (length=9)
          'packaging_type' => string 'PC' (length=2)

iOS 7 UIBarButton back button arrow color

Just to change the NavigationBar color you can set the tint color like below.

[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

Use virtualenv with Python with Visual Studio Code in Ubuntu

With the latest Python extension for Visual Studio Code, there is a venvPath Setting:

// Path to folder with a list of Virtual Environments (e.g. ~/.pyenv, ~/Envs, ~/.virtualenvs).
  "python.venvPath": "",

On Mac OS X, go to Code ? Preferences ? Settings and scroll down to Python Configuration.

Look for "python.venvPath: "", and click the pencil on the left-hand side to open up your user settings. Finally, add the path to where you store your virtual environments.

If you are using virtuanenvwrapper, or you have put all your virtual environment setting in one folder, this will be the one for you.

After you have configured "python.venvPath", restart Visual Studio Code. Then open the command palette and look for "Python: Select Interpreter". At this point, you should see the interpreter associated with the virtual environment you just added.

Can I set the height of a div based on a percentage-based width?

This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.

Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:

_x000D_
_x000D_
$(function() {_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

_x000D_
_x000D_
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

Limit the length of a string with AngularJS

Since we need ellipsis only when the string length is over the limit, it seems more appropriate to add ellipsis by using ng-if than binding.

{{ longString | limitTo: 20 }}<span ng-if="longString.length > 20">&hellip;</span>

SQL Server format decimal places with commas

Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:

FORMAT(@s,'#,0.0000')


In prior versions, at the risk of looking real ugly

[Query]:

declare @s decimal(18,10);
set @s = 1234.1234567;
select replace(convert(varchar,cast(floor(@s) as money),1),'.00',
    '.'+right(cast(@s * 10000 +10000.5 as int),4))

In the first part, we use MONEY->VARCHAR to produce the commas, but FLOOR() is used to ensure the decimals go to .00. This is easily identifiable and replaced with the 4 digits after the decimal place using a mixture of shifting (*10000) and CAST as INT (truncation) to derive the digits.

[Results]:

|   COLUMN_0 |
--------------
| 1,234.1235 |

But unless you have to deliver business reports using SQL Server Management Studio or SQLCMD, this is NEVER the correct solution, even if it can be done. Any front-end or reporting environment has proper functions to handle display formatting.

How to disable or enable viewpager swiping in android

In your custom view pager adapter, override those methods in ViewPager.

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

And to enable, just return each super method:

super.onInterceptTouchEvent(event) and super.onTouchEvent(event).

How to Update a Component without refreshing full page - Angular

To refresh the component at regular intervals I found this the best method. In the ngOnInit method setTimeOut function

ngOnInit(): void {
  setTimeout(() => { this.ngOnInit() }, 1000 * 10)
}
//10 is the number of seconds

ipynb import another ipynb file

The issue is that a notebooks is not a plain python file. The steps to import the .ipynb file are outlined in the following: Importing notebook

I am pasting the code, so if you need it...you can just do a quick copy and paste. Notice that at the end I have the import primes statement. You'll have to change that of course. The name of my file is primes.ipynb. From this point on you can use the content inside that file as you would do regularly.

Wish there was a simpler method, but this is straight from the docs.
Note: I am using jupyter not ipython.

import io, os, sys, types
from IPython import get_ipython
from nbformat import current
from IPython.core.interactiveshell import InteractiveShell


def find_notebook(fullname, path=None):
    """find a notebook, given its fully qualified name and an optional path

    This turns "foo.bar" into "foo/bar.ipynb"
    and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar
    does not exist.
    """
    name = fullname.rsplit('.', 1)[-1]
    if not path:
        path = ['']
    for d in path:
        nb_path = os.path.join(d, name + ".ipynb")
        if os.path.isfile(nb_path):
            return nb_path
        # let import Notebook_Name find "Notebook Name.ipynb"
        nb_path = nb_path.replace("_", " ")
        if os.path.isfile(nb_path):
            return nb_path


class NotebookLoader(object):
    """Module Loader for Jupyter Notebooks"""
    def __init__(self, path=None):
        self.shell = InteractiveShell.instance()
        self.path = path

    def load_module(self, fullname):
        """import a notebook as a module"""
        path = find_notebook(fullname, self.path)

        print ("importing Jupyter notebook from %s" % path)

        # load the notebook object
        with io.open(path, 'r', encoding='utf-8') as f:
            nb = current.read(f, 'json')


        # create the module and add it to sys.modules
        # if name in sys.modules:
        #    return sys.modules[name]
        mod = types.ModuleType(fullname)
        mod.__file__ = path
        mod.__loader__ = self
        mod.__dict__['get_ipython'] = get_ipython
        sys.modules[fullname] = mod

        # extra work to ensure that magics that would affect the user_ns
        # actually affect the notebook module's ns
        save_user_ns = self.shell.user_ns
        self.shell.user_ns = mod.__dict__

        try:
        for cell in nb.worksheets[0].cells:
            if cell.cell_type == 'code' and cell.language == 'python':
                # transform the input to executable Python
                code = self.shell.input_transformer_manager.transform_cell(cell.input)
                # run the code in themodule
                exec(code, mod.__dict__)
        finally:
            self.shell.user_ns = save_user_ns
        return mod


class NotebookFinder(object):
    """Module finder that locates Jupyter Notebooks"""
    def __init__(self):
        self.loaders = {}

    def find_module(self, fullname, path=None):
        nb_path = find_notebook(fullname, path)
        if not nb_path:
            return

        key = path
        if path:
            # lists aren't hashable
            key = os.path.sep.join(path)

        if key not in self.loaders:
            self.loaders[key] = NotebookLoader(path)
        return self.loaders[key]

sys.meta_path.append(NotebookFinder())

import primes

What exactly does stringstream do?

From C++ Primer:

The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

I come across some cases where it is both convenient and concise to use stringstream.

case 1

It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;

int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of 
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;

out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';

// final result in string format
string result = out.str() 

case 2

It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

string simplifyPath(string path) {
    string res, tmp;
    vector<string> stk;
    stringstream ss(path);
    while(getline(ss,tmp,'/')) {
        if (tmp == "" or tmp == ".") continue;
        if (tmp == ".." and !stk.empty()) stk.pop_back();
        else if (tmp != "..") stk.push_back(tmp);
    }
    for(auto str : stk) res += "/"+str;
    return res.empty() ? "/" : res; 
 }

Without the use of stringstream, it would be difficult to write such concise code.

Pretty git branch graphs

Looking at this conversation tried to use my favorite git-cola & git-dag. Running View->DAG... from git-cola and replace Log: master -- with --all shows pretty graph with all branches.

Optimistic vs. Pessimistic locking

Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.

If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.

This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.

In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.

Plotting multiple lines, in different colors, with pandas dataframe

Another simple way is to use the pivot function to format the data as you need first.

df.plot() does the rest

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()

result

pivot effectively turns the data into:

enter image description here

Concatenate two PySpark dataframes

This should do it for you ...

from pyspark.sql.types import FloatType
from pyspark.sql.functions import randn, rand, lit, coalesce, col
import pyspark.sql.functions as F

df_1 = sqlContext.range(0, 6)
df_2 = sqlContext.range(3, 10)
df_1 = df_1.select("id", lit("old").alias("source"))
df_2 = df_2.select("id")

df_1.show()
df_2.show()
df_3 = df_1.alias("df_1").join(df_2.alias("df_2"), df_1.id == df_2.id, "outer")\
  .select(\
    [coalesce(df_1.id, df_2.id).alias("id")] +\
    [col("df_1." + c) for c in df_1.columns if c != "id"])\
  .sort("id")
df_3.show()

Properly Handling Errors in VBA (Excel)

Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume statement to clear the Error Handler. The Resume also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.

Block 3 fails because there is no Resume statement so any attempt at error handling after that will fail.

Every error handler must be ended by exiting the procedure or a Resume statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.

But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.

Sub InLineErrorHandling()

    'code without error handling

BeginTry1:

    'activate inline error handler
    On Error GoTo ErrHandler1

        'code block that may result in an error
        Dim a As String: a = "Abc"
        Dim c As Integer: c = a 'type mismatch

ErrHandler1:

    'handle the error
    If Err.Number <> 0 Then

        'the error handler has deactivated the previous error handler

        MsgBox (Err.Description)

        'Resume (or exit procedure) is the only way to get out of an error handling block
        'otherwise the following On Error statements will have no effect
        'CAUTION: it also reactivates the previous error handler
        Resume EndTry1
    End If

EndTry1:
    'CAUTION: since the Resume statement reactivates the previous error handler
    'you must ALWAYS use an On Error GoTo statement here
    'because another error here would cause an endless loop
    'use On Error GoTo 0 or On Error GoTo <Label>
    On Error GoTo 0

    'more code with or without error handling

End Sub

Sources:

The key to making this work is to use a Resume statement immediately followed by another On Error statement. The Resume is within the error handler and diverts code to the EndTry1 label. You must immediately set another On Error statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.

To avoid using the previous error handler again you need to set On Error to a new error handler or simply use On Error Goto 0 to cancel all error handling.

How to play a sound using Swift?

Swift 4 (iOS 12 compatible)

var player: AVAudioPlayer?

let path = Bundle.main.path(forResource: "note\(sender.tag)", ofType: "wav")
let url = URL(fileURLWithPath: path ?? "")
    
do {
   player = try AVAudioPlayer(contentsOf: url)
   player?.play()
} catch let error {
   print(error.localizedDescription)
}

How do I profile memory usage in Python?

maybe it help:
<see additional>

pip install gprof2dot
sudo apt-get install graphviz

gprof2dot -f pstats profile_for_func1_001 | dot -Tpng -o profile.png

def profileit(name):
    """
    @profileit("profile_for_func1_001")
    """
    def inner(func):
        def wrapper(*args, **kwargs):
            prof = cProfile.Profile()
            retval = prof.runcall(func, *args, **kwargs)
            # Note use of name from outer scope
            prof.dump_stats(name)
            return retval
        return wrapper
    return inner

@profileit("profile_for_func1_001")
def func1(...)

C# - Fill a combo box with a DataTable

For example, i created a table :

DataTable dt = new DataTable ();
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Value", typeof(int));

Add recorde to table :

DataRow row = dt.NewRow();
row["Title"] = "Price"
row["Value"] = 2000;
dt.Rows.Add(row);

or :

dt.Rows.Add("Price",2000);

finally :

combo.DataSource = dt;
combo.DisplayMember = "Title";
combo.ValueMember = "Value";

React Native TextInput that only accepts numeric characters

This not work on IOS, setState -> render -> not change the text, but can change other. The textinput can't change itself value when textOnChange.

by the way, This work well on Android.

Bootstrap 3 navbar active li not changing background-color

You need to add CSS to .active instead of .active a.

Fiddle: http://jsfiddle.net/T5X6h/2/

Something like this:

.navbar-default .navbar-nav > .active{
    color: #000;
    background: #d65c14;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #000;
    background: #d65c14;
}

Lambda expression to convert array/List of String to array/List of Integers

I used maptoInt() with Lambda operation for converting string to Integer

int[] arr = Arrays.stream(stringArray).mapToInt(item -> Integer.parseInt(item)).toArray();

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I had exactly the same issue last week - WCF program behaves strangely on one server - why?

For me the solution was rather simple. Sharepoint has its own set of permissions. My client tried to log on as a user that wasn't explicitly given access to the webservice through Sharepoint's administration panel.

I added the user to Sharepoint's whitelist and bang - it just worked.

Even if that isn't the issue, please note that

The HTTP request is unauthorized with client authentication scheme ‘Ntlm’. The authentication header received from the server was ‘NTLM’.

Means (in English) that you simply don't have permission. Your protocol is probably right - your user just doesn't have permissions.

ASP.NET Core Get Json Array using IConfiguration

In ASP.NET Core 2.2 and later we can inject IConfiguration anywhere in our application like in your case, you can inject IConfiguration in HomeController and use like this to get the array.

string[] array = _config.GetSection("MyArray").Get<string[]>();

Get the current displaying UIViewController on the screen in AppDelegate.m

Why not just handle the push notification code in the app delegate? Is it directly related to a view?

You can check if a UIViewController's view is currently visible by checking if it's view's window property has a value. See more here.

converting drawable resource image into bitmap

In res/drawable folder,

1. Create a new Drawable Resources.

2. Input file name.

A new file will be created inside the res/drawable folder.

Replace this code inside the newly created file and replace ic_action_back with your drawable file name.

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_action_back"
    android:tint="@color/color_primary_text" />

Now, you can use it with Resource ID, R.id.filename.

How do I draw a set of vertical lines in gnuplot?

To elaborate on previous answers about the "every x units" part, here is what I came up with:

# Draw 5 vertical lines
n = 5

# ... evenly spaced between x0 and x1
x0 = 1.0
x1 = 2.0
dx = (x1-x0)/(n-1.0)

# ... each line going from y0 to y1
y0 = 0
y1 = 10

do for [i = 0:n-1] {
    x = x0 + i*dx
    set arrow from x,y0 to x,y1 nohead linecolor "blue" # add other styling options if needed
}

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

Converting json results to a date

You need to extract the number from the string, and pass it into the Date constructor:

var x = [{
    "id": 1,
    "start": "\/Date(1238540400000)\/"
}, {
    "id": 2,
    "start": "\/Date(1238626800000)\/"
}];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0]                - extract the numeric part
x[0].start.match(/\d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

string encoding and decoding?

Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.

In the first example string is of type unicode and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:

>>> u"\xa0".decode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:

>>> "\xc2".encode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

Make a Bash alias that takes a parameter?

If you're looking for a generic way to apply all params to a function, not just one or two or some other hardcoded amount, you can do that this way:

#!/usr/bin/env bash

# you would want to `source` this file, maybe in your .bash_profile?
function runjar_fn(){
    java -jar myjar.jar "$@";
}

alias runjar=runjar_fn;

So in the example above, i pass all parameters from when i run runjar to the alias.

For example, if i did runjar hi there it would end up actually running java -jar myjar.jar hi there. If i did runjar one two three it would run java -jar myjar.jar one two three.

I like this $@ - based solution because it works with any number of params.

Installing PDO driver on MySQL Linux server

If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!

Here's how I installed in Ubuntu-based image:

https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8

RUN docker-php-ext-install mysql mysqli pdo pdo_mysql

Building and running your application is just a 2 step process (considering you are in the current directory of the app):

$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp

Calling a function of a module by using its name (a string)

The best answer according to the Python programming FAQ would be:

functions = {'myfoo': foo.bar}

mystring = 'myfoo'
if mystring in functions:
    functions[mystring]()

The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct

C# list.Orderby descending

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

In Visual Studio and most other half decent IDEs you can simply do SHIFT+TAB. It does the opposite of just TAB.

I would think and hope that the IDEs you mention support this as well.

java.math.BigInteger cannot be cast to java.lang.Integer

You can use:

Integer grandChildCount = ((BigInteger) result[1]).intValue();

Or perhaps cast to Number to cover both Integer and BigInteger values.

Passing enum or object through an intent (the best solution)

about Oderik's post:

You can make your enum implement Parcelable which is quite easy for enums:

public enum MyEnum implements Parcelable { ... } You can than use Intent.putExtra(String, Parcelable).

If you define a MyEnum variable myEnum, then do intent.putExtra("Parcelable1", myEnum), you will get a "The method putExtra(String, Parcelable) is ambiguous for the type Intent" error message. because there is also a Intent.putExtra(String, Parcelable) method, and original 'Enum' type itself implements the Serializable interface, so compiler does not know choose which method(intent.putExtra(String, Parcelable/or Serializable)).

Suggest that remove the Parcelable interface from MyEnum, and move the core code into wrap class' Parcelable implementation, like this(Father2 is a Parcelable and contain an enum field):

public class Father2 implements Parcelable {

AnotherEnum mAnotherEnum;
int mField;

public Father2(AnotherEnum myEnum, int field) {
    mAnotherEnum = myEnum;
    mField = field;
}

private Father2(Parcel in) {
    mField = in.readInt();
    mAnotherEnum = AnotherEnum.values()[in.readInt()];
}

public static final Parcelable.Creator<Father2> CREATOR = new Parcelable.Creator<Father2>() {

    public Father2 createFromParcel(Parcel in) {
        return new Father2(in);
    }

    @Override
    public Father2[] newArray(int size) {
        return new Father2[size];
    }

};

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(mField);
    dest.writeInt(mAnotherEnum.ordinal());
}

}

then we can do:

AnotherEnum anotherEnum = AnotherEnum.Z;
intent.putExtra("Serializable2", AnotherEnum.X);   
intent.putExtra("Parcelable2", new Father2(AnotherEnum.X, 7));

beyond top level package error in relative import

if you have an __init__.py in an upper folder, you can initialize the import as import file/path as alias in that init file. Then you can use it on lower scripts as:

import alias

How to escape a while loop in C#

break or goto

while ( true ) {
  if ( conditional ) {
    break;
  }
  if ( other conditional ) {
    goto EndWhile;
  }
}
EndWhile:

How do I 'foreach' through a two-dimensional array?

Using LINQ you can do it like this:

var table_enum = table

    // Convert to IEnumerable<string>
    .OfType<string>()

    // Create anonymous type where Index1 and Index2
    // reflect the indices of the 2-dim. array
    .Select((_string, _index) => new {
        Index1 = (_index / 2),
        Index2 = (_index % 2), // ? I added this only for completeness
        Value = _string
    })

    // Group by Index1, which generates IEnmurable<string> for all Index1 values
    .GroupBy(v => v.Index1)

    // Convert all Groups of anonymous type to String-Arrays
    .Select(group => group.Select(v => v.Value).ToArray());

// Now you can use the foreach-Loop as you planned
foreach(string[] str_arr in table_enum) {
    // …
}

This way it is also possible to use the foreach for looping through the columns instead of the rows by using Index2 in the GroupBy instead of Index 1. If you don't know the dimension of your array then you have to use the GetLength() method to determine the dimension and use that value in the quotient.

Python 3.4.0 with MySQL database

Use mysql-connector-python. I prefer to install it with pip from PyPI:

pip install --allow-external mysql-connector-python mysql-connector-python

Have a look at its documentation and examples.

If you are going to use pooling make sure your database has enough connections available as the default settings may not be enough.

How to create a trie in Python

Modified from senderle's method (above). I found that Python's defaultdict is ideal for creating a trie or a prefix tree.

from collections import defaultdict

class Trie:
    """
    Implement a trie with insert, search, and startsWith methods.
    """
    def __init__(self):
        self.root = defaultdict()

    # @param {string} word
    # @return {void}
    # Inserts a word into the trie.
    def insert(self, word):
        current = self.root
        for letter in word:
            current = current.setdefault(letter, {})
        current.setdefault("_end")

    # @param {string} word
    # @return {boolean}
    # Returns if the word is in the trie.
    def search(self, word):
        current = self.root
        for letter in word:
            if letter not in current:
                return False
            current = current[letter]
        if "_end" in current:
            return True
        return False

    # @param {string} prefix
    # @return {boolean}
    # Returns if there is any word in the trie
    # that starts with the given prefix.
    def startsWith(self, prefix):
        current = self.root
        for letter in prefix:
            if letter not in current:
                return False
            current = current[letter]
        return True

# Now test the class

test = Trie()
test.insert('helloworld')
test.insert('ilikeapple')
test.insert('helloz')

print test.search('hello')
print test.startsWith('hello')
print test.search('ilikeapple')

Is key-value pair available in Typescript?

Is key-value pair available in Typescript?

If you think of a C# KeyValuePair<string, string>: No, but you can easily define one yourself:

interface KeyValuePair {
    key: string;
    value: string;
}

Usage:

let foo: KeyValuePair = { key: "k", value: "val" };

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

What is the use of "assert"?

Assertions are a systematic way to check that the internal state of a program is as the programmer expected, with the goal of catching bugs. See the example below.

>>> number = input('Enter a positive number:')
Enter a positive number:-1
>>> assert (number > 0), 'Only positive numbers are allowed!'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Only positive numbers are allowed!
>>> 

Connection refused to MongoDB errno 111

I Didn't have a /data/db directory. I created one and gave a chmod 777 permission and it worked for me

How do I plot list of tuples in Python?

With gnuplot using gplot.py

from gplot import *

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

gplot.log('y')
gplot(*zip(*l))

enter image description here

'mat-form-field' is not a known element - Angular 5 & Material2

@NgModule({
  declarations: [
    SearchComponent
  ],
  exports: [
    CommonModule,
    MatInputModule,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatDialogModule,
  ]
})
export class MaterialModule { }

Also, do not forget to import the MaterialModule in the imports array of AppModule.

How to convert string to integer in UNIX

let d=d1-d2;echo $d;

This should help.

how to call a onclick function in <a> tag?

Use the onclick as an attribute of your a, not part of the href

<a onclick='window.open("lead_data.php?leadid=1", myWin, scrollbars=yes, width=400, height=650);'>1</a>

Fiddle: http://jsfiddle.net/Wt5La/

How to find the most recent file in a directory using .NET, and without looping?

Here's a version that gets the most recent file from each subdirectory

List<string> reports = new List<string>();    
DirectoryInfo directory = new DirectoryInfo(ReportsRoot);
directory.GetFiles("*.xlsx", SearchOption.AllDirectories).GroupBy(fl => fl.DirectoryName)
.ForEach(g => reports.Add(g.OrderByDescending(fi => fi.LastWriteTime).First().FullName));

Send inline image in email

Try this

 string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";
 AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);

 LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg);
 inline.ContentId = Guid.NewGuid().ToString();
 avHtml.LinkedResources.Add(inline);

 MailMessage mail = new MailMessage();
 mail.AlternateViews.Add(avHtml);

 Attachment att = new Attachment(filePath);
 att.ContentDisposition.Inline = true;

 mail.From = from_email;
 mail.To.Add(data.email);
 mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";
 mail.Body = String.Format(
            "<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
            @"<img src=""cid:{0}"" />", att.ContentId);

 mail.IsBodyHtml = true;
 mail.Attachments.Add(att);

Get last 5 characters in a string

Checks for errors:

Dim result As String = str
If str.Length > 5 Then
    result = str.Substring(str.Length - 5)
End If

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

Moment js get first and last day of current month

As simple we can use daysInMonth() and endOf()

const firstDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').startOf('month').format('D')
const lastDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').endOf('month').format('D')

How can I stop python.exe from closing immediately after I get an output?

You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.

However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.

How to match, but not capture, part of a regex?

Update: Thanks to Germán Rodríguez Herrera!

In javascript try: /123-(apple(?=-)|banana(?=-)|(?!-))-?456/

Remember that the result is in group 1

Debuggex Demo

BeanFactory not initialized or already closed - call 'refresh' before

I had the same error and I had not made any changes to the application config or the web.xml. Multiple tries to revert back some minor changes to code was not clearing the exceptions. Finally it worked after restarting STS.

No converter found capable of converting from type to type

If you look at the exception stack trace it says that, it failed to convert from ABDeadlineType to DeadlineType. Because your repository is going to return you the objects of ABDeadlineType. How the spring-data-jpa will convert into the other one(DeadlineType). You should return the same type from repository and then have some intermediate util class to convert it into your model class.

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

Getting all selected checkboxes in an array

ES6 version:

const values = Array
  .from(document.querySelectorAll('input[type="checkbox"]'))
  .filter((checkbox) => checkbox.checked)
  .map((checkbox) => checkbox.value);

_x000D_
_x000D_
function getCheckedValues() {_x000D_
  return Array.from(document.querySelectorAll('input[type="checkbox"]'))_x000D_
  .filter((checkbox) => checkbox.checked)_x000D_
  .map((checkbox) => checkbox.value);_x000D_
}_x000D_
_x000D_
const resultEl = document.getElementById('result');_x000D_
_x000D_
document.getElementById('showResult').addEventListener('click', () => {_x000D_
  resultEl.innerHTML = getCheckedValues();_x000D_
});
_x000D_
<input type="checkbox" name="type" value="1" />1_x000D_
<input type="checkbox" name="type" value="2" />2_x000D_
<input type="checkbox" name="type" value="3" />3_x000D_
<input type="checkbox" name="type" value="4" />4_x000D_
<input type="checkbox" name="type" value="5" />5_x000D_
_x000D_
<br><br>_x000D_
<button id="showResult">Show checked values</button>_x000D_
<br><br>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

programmatically add column & rows to WPF Datagrid

I found a solution that adds columns at runtime, and binds to a DataTable.

Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me. Any suggestions?

xaml

<DataGrid
  Name="dataGrid"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>

xaml.cs using System.Windows.Data;

if (table != null) // table is a DataTable
{
  foreach (DataColumn col in table.Columns)
  {
    dataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  dataGrid.DataContext = table;
}

Creating a dictionary from a CSV file

This isn't elegant but a one line solution using pandas.

import pandas as pd
pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()

If you want to specify dtype for your index (it can't be specified in read_csv if you use the index_col argument because of a bug):

import pandas as pd
pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

If you're having this problem with Spring Boot 1.4.x and up, you might be able to use @OverrideAutoConfiguration(enabled=true) to solve the problem.

Similar to what was asked/answered here https://stackoverflow.com/a/39253304/1410035

How to implement linear interpolation?

Instead of extrapolating off the ends, you could return the extents of the y_list. Most of the time your application is well behaved, and the Interpolate[x] will be in the x_list. The (presumably) linear affects of extrapolating off the ends may mislead you to believe that your data is well behaved.

  • Returning a non-linear result (bounded by the contents of x_list and y_list) your program's behavior may alert you to an issue for values greatly outside x_list. (Linear behavior goes bananas when given non-linear inputs!)

  • Returning the extents of the y_list for Interpolate[x] outside of x_list also means you know the range of your output value. If you extrapolate based on x much, much less than x_list[0] or x much, much greater than x_list[-1], your return result could be outside of the range of values you expected.

    def __getitem__(self, x):
        if x <= self.x_list[0]:
            return self.y_list[0]
        elif x >= self.x_list[-1]:
            return self.y_list[-1]
        else:
            i = bisect_left(self.x_list, x) - 1
            return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
    

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

Here are the steps that worked for me:

  1. Enable Directions API; Geocoding API; Gelocation API console.cloud.google.com/google/maps-apis
  2. Enable APIS and Services to select APIs console.developers.google.com/apis/library

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

Just use indexing

df.iloc[:-1,:]

That's why iloc exists. You can also use head or tail.

Test if registry value exists

Personally, I do not like test functions having a chance of spitting out errors, so here is what I would do. This function also doubles as a filter that you can use to filter a list of registry keys to only keep the ones that have a certain key.

Function Test-RegistryValue {
    param(
        [Alias("PSPath")]
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [String]$Path
        ,
        [Parameter(Position = 1, Mandatory = $true)]
        [String]$Name
        ,
        [Switch]$PassThru
    ) 

    process {
        if (Test-Path $Path) {
            $Key = Get-Item -LiteralPath $Path
            if ($Key.GetValue($Name, $null) -ne $null) {
                if ($PassThru) {
                    Get-ItemProperty $Path $Name
                } else {
                    $true
                }
            } else {
                $false
            }
        } else {
            $false
        }
    }
}

How to get the difference between two dictionaries in Python?

What about this? Not as pretty but explicit.

orig_dict = {'a' : 1, 'b' : 2}
new_dict = {'a' : 2, 'v' : 'hello', 'b' : 2}

updates = {}
for k2, v2 in new_dict.items():
    if k2 in orig_dict:    
        if v2 != orig_dict[k2]:
            updates.update({k2 : v2})
    else:
        updates.update({k2 : v2})

#test it
#value of 'a' was changed
#'v' is a completely new entry
assert all(k in updates for k in ['a', 'v'])

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I had this issue because i denied keychain access and in order to solve it you need to open keychain, Then click on the lock on top right of the screen to lock it again, after that you can archive and it will work

Android, How to create option Menu

The previous answers have covered the traditional menu used in android. Their is another option you can use if you are looking for an alternative

https://github.com/AnshulBansal/Android-Pulley-Menu

Pulley menu is an alternate to the traditional Menu which allows user to select any option for an activity intuitively. The menu is revealed by dragging the screen downwards and in that gesture user can also select any of the options.

Django: Display Choice Value

Others have pointed out that a get_FOO_display method is what you need. I'm using this:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

which iterates over all of the choices that a particular item has until it finds the one that matches the items type

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

I would counsel against using if ($hash{$key}) since it will not do what you expect if the key exists but its value is zero or empty.

How are software license keys generated?

The key system must have several properties:

  • very few keys must be valid
  • valid keys must not be derivable even given everything the user has.
  • a valid key on one system is not a valid key on another.
  • others

One solution that should give you these would be to use a public key signing scheme. Start with a "system hash" (say grab the macs on any NICs, sorted, and the CPU-ID info, plus some other stuff, concatenate it all together and take an MD5 of the result (you really don't want to be handling personally identifiable information if you don't have to)) append the CD's serial number and refuse to boot unless some registry key (or some datafile) has a valid signature for the blob. The user activates the program by shipping the blob to you and you ship back the signature.

Potential issues include that you are offering to sign practically anything so you need to assume someone will run a chosen plain text and/or chosen ciphertext attacks. That can be mitigated by checking the serial number provided and refusing to handle request from invalid ones as well as refusing to handle more than a given number of queries from a given s/n in an interval (say 2 per year)

I should point out a few things: First, a skilled and determined attacker will be able to bypass any and all security in the parts that they have unrestricted access to (i.e. everything on the CD), the best you can do on that account is make it harder to get illegitimate access than it is to get legitimate access. Second, I'm no expert so there could be serious flaws in this proposed scheme.

Restoring MySQL database from physical files

In my case, simply removing the tc.log in /var/lib/mysql was enough to start mariadb/mysql again.

Can an interface extend multiple interfaces in Java?

I think your confusion lies with multiple inheritance, in which it is bad practise to do so and in Java this is also not possible. However, implementing multiple interfaces is allowed in Java and it is also safe.

IE11 meta element Breaks SVG

I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.

I had <meta http-equiv="x-ua-compatible" content="ie=edge"> on the page.

In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.

data.table vs dplyr: can one do something well the other can't or does poorly?

Reading Hadley and Arun's answers one gets the impression that those who prefer dplyr's syntax would have in some cases to switch over to data.table or compromise for long running times.

But as some have already mentioned, dplyr can use data.table as a backend. This is accomplished using the dtplyr package which recently had it's version 1.0.0 release. Learning dtplyr incurs practically zero additional effort.

When using dtplyr one uses the function lazy_dt() to declare a lazy data.table, after which standard dplyr syntax is used to specify operations on it. This would look something like the following:

new_table <- mtcars2 %>% 
  lazy_dt() %>%
  filter(wt < 5) %>% 
  mutate(l100k = 235.21 / mpg) %>% # liters / 100 km
  group_by(cyl) %>% 
  summarise(l100k = mean(l100k))

  new_table

#> Source: local data table [?? x 2]
#> Call:   `_DT1`[wt < 5][, `:=`(l100k = 235.21/mpg)][, .(l100k = mean(l100k)), 
#>     keyby = .(cyl)]
#> 
#>     cyl l100k
#>   <dbl> <dbl>
#> 1     4  9.05
#> 2     6 12.0 
#> 3     8 14.9 
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

The new_table object is not evaluated until calling on it as.data.table()/as.data.frame()/as_tibble() at which point the underlying data.table operation is executed.

I've recreated a benchmark analysis done by data.table author Matt Dowle back at December 2018 which covers the case of operations over large numbers of groups. I've found that dtplyr indeed enables for the most part those who prefer the dplyr syntax to keep using it while enjoying the speed offered by data.table.

codeigniter model error: Undefined property

You have to load the db library first. In autoload.php add :

$autoload['libraries'] = array('database');

Also, try renaming User model class for "User_model".

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

Rounding Bigdecimal values with 2 Decimal Places

You can call setScale(newScale, roundingMode) method three times with changing the newScale value from 4 to 3 to 2 like

First case

    BigDecimal a = new BigDecimal("10.12345");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1235
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.124
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.12

Second case

    BigDecimal a = new BigDecimal("10.12556");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1256
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.126
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.13

Override hosts variable of Ansible playbook from the command line

An other solution is to use the special variable ansible_limit which is the contents of the --limit CLI option for the current execution of Ansible.

- hosts: "{{ ansible_limit | default(omit) }}"

If the --limit option is omitted, then Ansible issues a warning, but does nothing since no host matched.

[WARNING]: Could not match supplied host pattern, ignoring: None

PLAY ****************************************************************
skipping: no hosts matched

Difference between return and exit in Bash functions

I don't think anyone has really fully answered the question because they don't describe how the two are used. OK, I think we know that exit kills the script, wherever it is called and you can assign a status to it as well such as exit or exit 0 or exit 7 and so forth. This can be used to determine how the script was forced to stop if called by another script, etc. Enough on exit.

return, when called, will return the value specified to indicate the function's behavior, usually a 1 or a 0. For example:

    #!/bin/bash
    isdirectory() {
      if [ -d "$1" ]
      then
        return 0
      else
        return 1
      fi
    echo "you will not see anything after the return like this text"
    }

Check like this:

    if isdirectory $1; then echo "is directory"; else echo "not a directory"; fi

Or like this:

    isdirectory || echo "not a directory"

In this example, the test can be used to indicate if the directory was found. Notice that anything after the return will not be executed in the function. 0 is true, but false is 1 in the shell, different from other programming languages.

For more information on functions: Returning Values from Bash Functions

Note: The isdirectory function is for instructional purposes only. This should not be how you perform such an option in a real script.*

How to make an Android device vibrate? with different frequency?

Kotlin update for more type safety

Use it as a top level function in some common class of your project such as Utils.kt

// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
    val vibrator = getSystemService(context, Vibrator::class.java)
    vibrator?.let {
        if (Build.VERSION.SDK_INT >= 26) {
            it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            it.vibrate(100)
        }
    }
}

And then call it anywhere in your code as following:

vibrateDevice(requireContext())

Explanation

Using Vibrator::class.java is more type safe than using String constants.

We check the vibrator for nullability using let { }, because if the vibration is not available for the device, the vibrator will be null.

It's ok to supress deprecation in else clause, because the warning is from newer SDK.

We don't need to ask for permission at runtime for using vibration. But we need to declare it in AndroidManifest.xml as following:

<uses-permission android:name="android.permission.VIBRATE"/>