Programs & Examples On #Test project

Rails and PostgreSQL: Role postgres does not exist

I ended up here after attempting to follow Ryan Bate's tutorial on deploying to AWS EC2 with rubber. Here is what happened for me: We created a new app using "

rails new blog -d postgresql

Obviosuly this creates a new app with pg as the database, but the database was not made yet. With sqlite, you just run rake db:migrate, however with pg you need to create the pg database first. Ryan did not do this step. The command is rake db:create:all, then we can run rake db:migrate

The second part is changing the database.yml file. The default for the username when the file is generated is 'appname'. However, chances are your role for postgresql admin is something different (at least it was for me). I changed it to my name (see above advice about creating a role name) and I was good to go.

Hope this helps.

conditional Updating a list using LINQ

cleaner way to do this is using foreach

foreach(var item in li.Where(w => w.name =="di"))
{
   item.age=10;
}

Convert base64 string to image

This assumes a few things, that you know what the output file name will be and that your data comes as a string. I'm sure you can modify the following to meet your needs:

// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;


def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';

// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];

// create a buffered image
BufferedImage image = null;
byte[] imageByte;

BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();

// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);

Please note, this is just an example of what parts are involved. I haven't optimized this code at all and it's written off the top of my head.

How to use DISTINCT and ORDER BY in same SELECT statement?

If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.

How to get the size of a JavaScript object?

Chrome developer tools has this functionality. I found this article very helpful and does exactly what you want: https://developers.google.com/chrome-developer-tools/docs/heap-profiling

How can I get the name of an html page in Javascript?

Single statement that works with trailing slash. If you are using IE11 you'll have to polyfill the filter function.

var name = window.location.pathname
        .split("/")
        .filter(function (c) { return c.length;})
        .pop();

Regular expression [Any number]

You can use the following function to find the biggest [number] in any string.

It returns the value of the biggest [number] as an Integer.

var biggestNumber = function(str) {
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;

    while ((match = pattern.exec(str)) !== null) {
        if (match.index === pattern.lastIndex) {
            pattern.lastIndex++;
        }
        match[1] = parseInt(match[1]);
        if(biggest < match[1]) {
            biggest = match[1];
        }
    }
    return biggest;
}

DEMO

The following demo calculates the biggest number in your textarea every time you click the button.

It allows you to play around with the textarea and re-test the function with a different text.

_x000D_
_x000D_
var biggestNumber = function(str) {_x000D_
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
    while ((match = pattern.exec(str)) !== null) {_x000D_
        if (match.index === pattern.lastIndex) {_x000D_
            pattern.lastIndex++;_x000D_
        }_x000D_
        match[1] = parseInt(match[1]);_x000D_
        if(biggest < match[1]) {_x000D_
            biggest = match[1];_x000D_
        }_x000D_
    }_x000D_
    return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
    alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
    <textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
    </textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
   <button id="myButton">Try me</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

Accessing localhost (xampp) from another computer over LAN network - how to?

This should be all you need for a basic setup

This kind of configuration doesn't break phpMyAdmin on localhost

A static IP is recommended on the device running the server

This example uses the 192.168.1.x IP. Your network configuration might use a different IP

In the httpd.conf in Apache you should have:

# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to 
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

I would leave blank the name so it gets the defaults:

# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#

Allow the guest machines and yourself. As a security caution, you might avoid Allow from all but instead use specific guest IP for example Allow from 192.168.1.xxx where xxx is the guest machine IP. In this case you might need to consider static IPs on guest machines also

# Controls who can get stuff from this server.
#
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
#     Deny from all
     Allow from all 
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost
     Allow from 192.168.1.*YOURguestIP*
     Allow from 192.168.1.*YOURselfIP*
</Directory>

Restart all services and Put Online from the tray icon

What is the difference between using constructor vs getInitialState in React / React Native?

The big difference is start from where they are coming from, so constructor is the constructor of your class in JavaScript, on the other side, getInitialState is part of the lifecycle of React . The constructor method is a special method for creating and initializing an object created with a class.

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery():

  1. will work with Action Queries only (Create,Alter,Drop,Insert,Update,Delete).
  2. Returns the count of rows effected by the Query.
  3. Return type is int
  4. Return value is optional and can be assigned to an integer variable.

ExecuteReader():

  1. will work with Action and Non-Action Queries (Select)
  2. Returns the collection of rows selected by the Query.
  3. Return type is DataReader.
  4. Return value is compulsory and should be assigned to an another object DataReader.

ExecuteScalar():

  1. will work with Non-Action Queries that contain aggregate functions.
  2. Return the first row and first column value of the query result.
  3. Return type is object.
  4. Return value is compulsory and should be assigned to a variable of required type.

Reference URL:

http://nareshkamuni.blogspot.in/2012/05/what-is-difference-between.html

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

How to check String in response body with mockMvc

Another option is:

when:

def response = mockMvc.perform(
            get('/path/to/api')
            .header("Content-Type", "application/json"))

then:

response.andExpect(status().isOk())
response.andReturn().getResponse().getContentAsString() == "what you expect"

Creating a segue programmatically

First of, suppose you have two different views in storyboard, and you want to navigate from one screen to another, so follow this steps:

1). Define all your views with class file and also storyboard id in identity inspector.

2). Make sure you add a navigation controller to the first view. Select it in the Storyboard and then Editor >Embed In > Navigation Controller

3). In your first class, import the "secondClass.h"

#import "ViewController.h
#import "secondController.h"

4). Add this command in the IBAction that has to perform the segue

secondController *next=[self.storyboard instantiateViewControllerWithIdentifier:@"second"];
[self.navigationController pushViewController:next animated:YES];

5). @"second" is secondview controller class, storyboard id.

BOOLEAN or TINYINT confusion

The Newest MySQL Versions have the new BIT data type in which you can specify the number of bits in the field, for example BIT(1) to use as Boolean type, because it can be only 0 or 1.

Provide static IP to docker containers via docker-compose

I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as

KAPACITOR_BASE_URL:  http://kapacitor:9092

In above http://[**kapacitor**]:9092 would not resolve to http://172.20.0.2:9092

I resolved the static IPs issues using subnetting configurations.

version: "3.3"

networks:
  frontend:
    ipam:
      config:
        - subnet: 172.20.0.0/24
services:
    db:
        image: postgres:9.4.4
        networks:
            frontend:
                ipv4_address: 172.20.0.5
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data

    redis:
        image: redis:latest
        networks:
            frontend:
                ipv4_address: 172.20.0.6
        ports:
            - "6379"

    influxdb:
        image: influxdb:latest
        ports:
            - "8086:8086"
            - "8083:8083"
        volumes:
            - ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
            - ../influxdb/inxdb:/var/lib/influxdb
        networks:
            frontend:
                ipv4_address: 172.20.0.4
        environment:
          INFLUXDB_HTTP_AUTH_ENABLED: "false"
          INFLUXDB_ADMIN_ENABLED: "true"
          INFLUXDB_USERNAME: "db_username"
          INFLUXDB_PASSWORD: "12345678"
          INFLUXDB_DB: db_customers

    kapacitor:
        image: kapacitor:latest
        ports: 
            - "9092:9092"
        networks:
            frontend:
                ipv4_address: 172.20.0.2
        depends_on:
            - influxdb
        volumes:
            - ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
            - ../kapacitor/kapdb:/var/lib/kapacitor
        environment:
          KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086

    web:
        build: .
        environment:
          RAILS_ENV: $RAILS_ENV
        command: bundle exec rails s -b 0.0.0.0
        ports:
            - "3000:3000"
        networks:
            frontend:
                ipv4_address: 172.20.0.3
        links:
            - db
            - kapacitor
        depends_on:
            - db
        volumes:
            - .:/var/app/current
        environment:
          DATABASE_URL: postgres://postgres@db
          DATABASE_USERNAME: postgres
          DATABASE_PASSWORD: postgres
          INFLUX_URL: http://influxdb:8086
          INFLUX_USER: db_username
          INFLUX_PWD: 12345678
          KAPACITOR_BASE_URL:  http://172.20.0.2:9092
          KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000

volumes:
  postgres_data:

copy db file with adb pull results in 'permission denied' error

Since I've updated to Android Oreo, I had to use this script to fix 'permission denied' issue.

This script on Mac OS X will copy your db file to Desktop. Just change it to match your ADB_PATH, DESTINATION_PATH and PACKAGE NAME.

#!/bin/sh
ADB_PATH="/Users/xyz/Library/Android/sdk/platform-tools"
PACKAGE_NAME="com.example.android"
DB_NAME="default.realm"
DESTINATION_PATH="/Users/xyz/Desktop/${DB_NAME}"
NOT_PRESENT="List of devices attached"
ADB_FOUND=`${ADB_PATH}/adb devices | tail -2 | head -1 | cut -f 1 | sed 's/ *$//g'`
if [[ ${ADB_FOUND} == ${NOT_PRESENT} ]]; then
    echo "Make sure a device is connected"
else
     ${ADB_PATH}/adb exec-out run-as ${PACKAGE_NAME} cat files/${DB_NAME} > ${DESTINATION_PATH}
fi

Function inside a function.?

It is possible to define a function from inside another function. the inner function does not exist until the outer function gets executed.

echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';
$x=x(2);
echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';

Output

y is not defined

y is defined

Simple thing you can not call function y before executed x

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

Only allow Numbers in input Tag without Javascript

Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.

<input type= "text" name= "name" pattern= "[0-9]"  title= "Title"/>

Purpose of ESI & EDI registers?

SI = Source Index
DI = Destination Index

As others have indicated, they have special uses with the string instructions. For real mode programming, the ES segment register must be used with DI and DS with SI as in

movsb  es:di, ds:si

SI and DI can also be used as general purpose index registers. For example, the C source code

srcp [srcidx++] = argv [j];

compiles into

8B550C         mov    edx,[ebp+0C]
8B0C9A         mov    ecx,[edx+4*ebx]
894CBDAC       mov    [ebp+4*edi-54],ecx
47             inc    edi

where ebp+12 contains argv, ebx is j, and edi has srcidx. Notice the third instruction uses edi mulitplied by 4 and adds ebp offset by 0x54 (the location of srcp); brackets around the address indicate indirection.


Though I can't remember where I saw it, but this confirms most of it, and this (slide 17) others:

AX = accumulator
DX = double word accumulator
CX = counter
BX = base register

They look like general purpose registers, but there are a number of instructions which (unexpectedly?) use one of them—but which one?—implicitly.

Centering a Twitter Bootstrap button

If you have more than one button, then you can do the following.

<div class="center-block" style="max-width:400px">
  <a href="#" class="btn btn-success">Accept</a>
  <a href="#" class="btn btn-danger"> Reject</a>
</div>

How to check size of a file using Bash?

python -c 'import os; print (os.path.getsize("... filename ..."))'

portable, all flavours of python, avoids variation in stat dialects

Stop embedded youtube iframe?

Easiest ways is

var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');

Link to reload current page

None of the other answers will preseve any querystring values. Try

<a href="javascript:window.location.href=window.location.href">

Admittedly this does involve javascript but, unless your users have script disabled, this is pretty straightforward.

How to change date format in JavaScript

Using the Datejs library, this can be as easy as:

Date.parse("05/05/2010").toString("MMMM yyyy");
//          parse date             convert to
//                                 string with
//                                 custom format

How to import local packages without gopath

I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure

- projects
  - go.mod
  - go.sum
  - project1
    - main.go
  - project2
    - main.go
  - package1
    - lib.go
  - package2
    - lib.go

And I am able to import package1 and package2 from project1 and project2 by using

import (
    "projects/package1"
    "projects/package2"
)

After running go mod init projects. I can use go build from project1 and project2 directories or I can do go build -o project1/exe project1/*.go from the projects directory.

The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

It is:

<%=Html.ActionLink("Home", "Index", MyRouteValObj, new with {.class = "tab" })%>

In VB.net you set an anonymous type using

new with {.class = "tab" }

and, as other point out, your third parameter should be an object (could be an anonymous type, also).

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

creating an array of structs in c++

Try this:

Customer customerRecords[2] = {{25, "Bob Jones"},
                               {26, "Jim Smith"}};

"inappropriate ioctl for device"

I got the error Can't open file for reading. Inappropriate ioctl for device recently when I migrated an old UB2K forum with a DBM file-based database to a new host. Apparently there are multiple, incompatible implementations of DBM. I had a backup of the database, so I was able to load that, but it seems there are other options e.g. moving a perl script/dbm to a new server, and shifting out of dbm?.

How to hide a div with jQuery?

$('#myDiv').hide(); hide function is used to edit content and show function is used to show again.

For more please click on this link.

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

Go: panic: runtime error: invalid memory address or nil pointer dereference

According to the docs for func (*Client) Do:

"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.

When err is nil, resp always contains a non-nil resp.Body."

Then looking at this code:

res, err := client.Do(req)
defer res.Body.Close()

if err != nil {
    return nil, err
}

I'm guessing that err is not nil. You're accessing the .Close() method on res.Body before you check for the err.

The defer only defers the function call. The field and method are accessed immediately.


So instead, try checking the error immediately.

res, err := client.Do(req)

if err != nil {
    return nil, err
}
defer res.Body.Close()

Why maven settings.xml file is not there?

The settings.xml file is not created by itself, you need to manually create it. Here is a sample:

  <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">
      <localRepository/>
      <interactiveMode/>
      <offline/>
      <pluginGroups/>
      <servers/>
      <mirrors/>
      <proxies/>
      <profiles/>
      <activeProfiles/>
   </settings>

How does the bitwise complement operator (~ tilde) work?

As others mentioned ~ just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.

One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3 as the number to which 3 should be added in order to get zero and you'll see that this number is 1101, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.

 1101 +
 0011 // 3
    =
10000
    =
 0000 // lose carry bit because integers have a constant number of bits.

Therefore 1101 is -3, flip the bits you get 0010 which is two.

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

VB.NET: how to prevent user input in a ComboBox

Set the ReadOnly attribute to true.

Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.

How to write to an existing excel file without overwriting data (using pandas)?

With openpyxlversion 2.4.0 and pandasversion 0.19.2, the process @ski came up with gets a bit simpler:

import pandas
from openpyxl import load_workbook

with pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') as writer:
    writer.book = load_workbook('Masterfile.xlsx')
    data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])
#That's it!

How to change font in ipython notebook

The new location of the theme file is: ~/.jupyter/custom/custom.css

What is best tool to compare two SQL Server databases (schema and data)?

I've used Red Gate's tools and they are superb. However, if you can't spend any money you could try Open DBDiff to compare schemas.

Android SDK Setup under Windows 7 Pro 64 bit

just press the back button and then next button...jdk found :D

How to increase heap size of an android application?

Increasing Java Heap unfairly eats deficit mobile resurces. Sometimes it is sufficient to just wait for garbage collector and then resume your operations after heap space is reduced. Use this static method then.

Create session factory in Hibernate 4

[quote from http://www.javabeat.net/session-factory-hibernate-4/]

There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. Also each incremental version gets changes on some of the important API. One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. In our earlier versions we have created the session factory as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

To round a double in Dart to a given degree of precision AFTER the decimal point, you can use built-in solution in dart toStringAsFixed() method, but you have to convert it back to double

void main() {
  double step1 = 1/3;  
  print(step1); // 0.3333333333333333
  
  String step2 = step1.toStringAsFixed(2); 
  print(step2); // 0.33 
  
  double step3 = double.parse(step2);
  print(step3); // 0.33
}

WPF ListView turn off selection

Moore's answer doesn't work, and the page here:

Specifying the Selection Color, Content Alignment, and Background Color for items in a ListBox

explains why it cannot work.

If your listview only contains basic text, the simplest way to solve the problem is by using transparent brushes.

<Window.Resources>
  <Style TargetType="{x:Type ListViewItem}">
    <Style.Resources>
      <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#00000000"/>
      <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#00000000"/>
    </Style.Resources>
  </Style>
</Window.Resources>

This will produce undesirable results if the listview's cells are holding controls such as comboboxes, since it also changes their color. To solve this problem, you must redefine the control's template.

  <Window.Resources>
    <Style TargetType="{x:Type ListViewItem}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type ListViewItem}">
            <Border SnapsToDevicePixels="True" 
                    x:Name="Bd" 
                    Background="{TemplateBinding Background}" 
                    BorderBrush="{TemplateBinding BorderBrush}" 
                    BorderThickness="{TemplateBinding BorderThickness}" 
                    Padding="{TemplateBinding Padding}">
              <GridViewRowPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                                    Columns="{TemplateBinding GridView.ColumnCollection}" 
                                    Content="{TemplateBinding Content}"/>
            </Border>
            <ControlTemplate.Triggers>
              <Trigger Property="IsEnabled" 
                       Value="False">
                <Setter Property="Foreground" 
                        Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Window.Resources>

PostgreSQL Error: Relation already exists

In my case I was migrating from 9.5 to 9.6. So to restore a database, I was doing :

sudo -u postgres psql -d databse -f dump.sql

Of course it was executing on the old postgreSQL database where there are datas! If your new instance is on port 5433, the correct way is :

sudo -u postgres psql -d databse -f dump.sql -p 5433

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

What does MissingManifestResourceException mean and how to fix it?

I had this problem when I added another class in the file just before the class which derived from Form. Adding it after fixed the problem.

Add floating point value to android resources/values

Add a float to dimens.xml:

<item format="float" name="my_dimen" type="dimen">1.2</item>

To reference from XML:

<EditText 
    android:lineSpacingMultiplier="@dimen/my_dimen"
    ...

To read this value programmatically you can use ResourcesCompat.getFloat from androidx.core

Gradle dependency:

implementation("androidx.core:core:${version}")

Usage:

import androidx.core.content.res.ResourcesCompat;

...

float value = ResourcesCompat.getFloat(context.getResources(), R.dimen.my_dimen);

How to add a single item to a Pandas Series

You can use the append function to add another element to it. Only, make a series of the new element, before you append it:

test = test.append(pd.Series(200, index=[101]))

How can I update NodeJS and NPM to the next versions?

Sometimes it's just simpler to download the latest version from http://nodejs.org/

Especially when all other options fail.

http://nodejs.org/ -> click INSTALL -> you'll have the latest node and npm

Simple!

Rethrowing exceptions in Java without losing the stack trace

I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e; leads to an unhandeled exception, so I just did this:

try
{
...
} catch (NoSuchMethodException | SecurityException | IllegalAccessException e) {                    
    throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString());
}

Worked for me....:)

A quick and easy way to join array elements with a separator (the opposite of split) in Java

You can use replace and replaceAll with regular expressions.

String[] strings = {"a", "b", "c"};

String result = Arrays.asList(strings).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", ",");

Because Arrays.asList().toString() produces: "[a, b, c]", we do a replaceAll to remove the first and last brackets and then (optionally) you can change the ", " sequence for "," (your new separator).

A stripped version (fewer chars):

String[] strings = {"a", "b", "c"};

String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "").replace(", ", "," );

Regular expressions are very powerful, specially String methods "replaceFirst" and "replaceAll". Give them a try.

Where is Maven Installed on Ubuntu

Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.

As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.

For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:

The Apt-get installation will install all the required files in the following folder structure

/usr/bin/mvn

/usr/share/maven2/

/etc/maven2

P.S The Maven configuration is store in /etc/maven2

Note, it's not just apt-get that will do this, it's any .deb package installer.

disable a hyperlink using jQuery

function EnableHyperLink(id) {
        $('#' + id).attr('onclick', 'Pagination("' + id + '")');//onclick event which u 
        $('#' + id).addClass('enable-link');
        $('#' + id).removeClass('disable-link');
    }

    function DisableHyperLink(id) {
        $('#' + id).addClass('disable-link');
        $('#' + id).removeClass('enable-link');
        $('#' + id).removeAttr('onclick');
    }

.disable-link
{
    text-decoration: none !important;
    color: black !important;
    cursor: default;
}
.enable-link
{
    text-decoration: underline !important;
    color: #075798 !important;
    cursor: pointer !important;
}

ExecutorService that interrupts tasks after a timeout

Using John W answer I created an implementation that correctly begin the timeout when the task starts its execution. I even write a unit test for it :)

However, it does not suit my needs since some IO operations do not interrupt when Future.cancel() is called (ie when Thread.interrupt() is called). Some examples of IO operation that may not be interrupted when Thread.interrupt() is called are Socket.connect and Socket.read (and I suspect most of IO operation implemented in java.io). All IO operations in java.nio should be interruptible when Thread.interrupt() is called. For example, that is the case for SocketChannel.open and SocketChannel.read.

Anyway if anyone is interested, I created a gist for a thread pool executor that allows tasks to timeout (if they are using interruptible operations...): https://gist.github.com/amanteaux/64c54a913c1ae34ad7b86db109cbc0bf

How do I pause my shell script for a second before continuing?

And what about:

read -p "Press enter to continue"

How to change navigation bar color in iOS 7 or 6?

Try the code below in the - (void)viewDidLoad of your ViewController.m

[[[self navigationController] navigationBar] setTintColor:[UIColor yellowColor]];

this did work for me in iOS 6.. Try it..

When should I use mmap for file access?

In addition to other nice answers, a quote from Linux system programming written by Google's expert Robert Love:

Advantages of mmap( )

Manipulating files via mmap( ) has a handful of advantages over the standard read( ) and write( ) system calls. Among them are:

  • Reading from and writing to a memory-mapped file avoids the extraneous copy that occurs when using the read( ) or write( ) system calls, where the data must be copied to and from a user-space buffer.

  • Aside from any potential page faults, reading from and writing to a memory-mapped file does not incur any system call or context switch overhead. It is as simple as accessing memory.

  • When multiple processes map the same object into memory, the data is shared among all the processes. Read-only and shared writable mappings are shared in their entirety; private writable mappings have their not-yet-COW (copy-on-write) pages shared.

  • Seeking around the mapping involves trivial pointer manipulations. There is no need for the lseek( ) system call.

For these reasons, mmap( ) is a smart choice for many applications.

Disadvantages of mmap( )

There are a few points to keep in mind when using mmap( ):

  • Memory mappings are always an integer number of pages in size. Thus, the difference between the size of the backing file and an integer number of pages is "wasted" as slack space. For small files, a significant percentage of the mapping may be wasted. For example, with 4 KB pages, a 7 byte mapping wastes 4,089 bytes.

  • The memory mappings must fit into the process' address space. With a 32-bit address space, a very large number of various-sized mappings can result in fragmentation of the address space, making it hard to find large free contiguous regions. This problem, of course, is much less apparent with a 64-bit address space.

  • There is overhead in creating and maintaining the memory mappings and associated data structures inside the kernel. This overhead is generally obviated by the elimination of the double copy mentioned in the previous section, particularly for larger and frequently accessed files.

For these reasons, the benefits of mmap( ) are most greatly realized when the mapped file is large (and thus any wasted space is a small percentage of the total mapping), or when the total size of the mapped file is evenly divisible by the page size (and thus there is no wasted space).

How to split a comma separated string and process in a loop using JavaScript

Like this:

var str = 'Hello, World, etc';
var myarray = str.split(',');

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}

Set inputType for an EditText Programmatically?

This may be of help to others like me who wanted to toggle between password and free-text mode. I tried using the input methods suggested but it only worked in one direction. I could go from password to text but then I could not revert. For those trying to handle a toggle (eg a show Password check box) use

       @Override
        public void onClick(View v)
        {
            if(check.isChecked())
            {
                edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                Log.i(TAG, "Show password");
            }
            else
            {
                edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                Log.i(TAG, "Hide password");
            }
        }

I have to credit this for the solution. Wish I had found that a few hours ago!

json.dumps vs flask.jsonify

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.

See more about the jsonify() function here for full reference.

Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.

How do you put an image file in a json object?

I can think of doing it in two ways:

1.

Storing the file in file system in any directory (say dir1) and renaming it which ensures that the name is unique for every file (may be a timestamp) (say xyz123.jpg), and then storing this name in some DataBase. Then while generating the JSON you pull this filename and generate a complete URL (which will be http://example.com/dir1/xyz123.png )and insert it in the JSON.

2.

Base 64 Encoding, It's basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end. Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants. So this approach will allow you to put your image directly in the MongoDB, while storing it Encode the image and decode while fetching it, it has some of its own drawbacks:

  • base64 encoding makes file sizes roughly 33% larger than their original binary representations, which means more data down the wire (this might be exceptionally painful on mobile networks)
  • data URIs aren’t supported on IE6 or IE7.
  • base64 encoded data may possibly take longer to process than binary data.

Source

Converting Image to DATA URI

A.) Canvas

Load the image into an Image-Object, paint it to a canvas and convert the canvas back to a dataURL.

function convertToDataURLviaCanvas(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}

Usage

convertToDataURLviaCanvas('http://bit.ly/18g0VNp', function(base64Img){
    // Base64DataURL
});

Supported input formats image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx

B.) FileReader

Load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a data URL.

function convertFileToBase64viaFileReader(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
      var reader  = new FileReader();
      reader.onloadend = function () {
          callback(reader.result);
      }
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

This approach

  • lacks in browser support
  • has better compression
  • works for other file types as well.

Usage

convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){
    // Base64DataURL
});

Source

C# "must declare a body because it is not marked abstract, extern, or partial"

I got the same error message because I had a function with a parameter named with a reserved word.

   public int SaveDelegate(MyModel.Delegate delegate)

Renaming the variable delegate solved the problem.

form confirm before submit

Simply...

  $('#myForm').submit(function() {
   return confirm("Click OK to continue?");
  });

or

  $('#myForm').submit(function() {
   var status = confirm("Click OK to continue?");
   if(status == false){
   return false;
   }
   else{
   return true; 
   }
  });

Recursively find all files newer than a given time

You can also do this without a marker file.

The %s format to date is seconds since the epoch. find's -mmin flag takes an argument in minutes, so divide the difference in seconds by 60. And the "-" in front of age means find files whose last modification is less than age.

time=1312603983
now=$(date +'%s')
((age = (now - time) / 60))
find . -type f -mmin -$age

With newer versions of gnu find you can use -newermt, which makes it trivial.

SET NAMES utf8 in MySQL?

Instead of doing this via an SQL query use the php function: mysqli::set_charset mysqli_set_charset

Note:

This is the preferred way to change the charset. Using mysqli_query() to set it (such as SET NAMES utf8) is not recommended.

See the MySQL character set concepts section for more information.

from http://www.php.net/manual/en/mysqli.set-charset.php

ASP.NET Core Get Json Array using IConfiguration

To get all values of all sections from appsettings.json

        public static string[] Sections = { "LogDirectory", "Application", "Email" };
        Dictionary<string, string> sectionDictionary = new Dictionary<string, string>();

        List<string> sectionNames = new List<string>(Sections);
        
        sectionNames.ForEach(section =>
        {
            List<KeyValuePair<string, string>> sectionValues = configuration.GetSection(section)
                    .AsEnumerable()
                    .Where(p => p.Value != null)
                    .ToList();
            foreach (var subSection in sectionValues)
            {
                sectionDictionary.Add(subSection.Key, subSection.Value);
            }
        });
        return sectionDictionary;

How to convert JSON to XML or XML to JSON?

Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:

XML -> JSON

  1. All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
  2. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
  3. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
  4. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

A new update changes how null can be handled (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

JSON -> XML

  1. You need a top level object that will convert to a root XML element or the parser will fail.
  2. Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.

Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.

curl: (6) Could not resolve host: application

In my case, putting space after colon was wrong.

# Not work
curl -H Content-Type: application/json ~
# OK
curl -H Content-Type:application/json ~

Make child div stretch across width of page

I know this post is old, in case someone stumbles upon it in 2019, this would work try it.

//html
<div id="container">
<div id="help_panel">
<div class="help_panel_extra_if_you_want"> //then if you want to add some height and width if you want, do this.

</div>
</div>
</div>

//css
#container{
left: 0px;
top: 0px;
right: 0px;
z-index: 100;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;    
position: relative;
height:650px;
margin-top:55px;
margin-bottom:-20px;
}

#help_panel {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
padding-right: 24px;
padding-left: 18px;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;

.help_panel_extra_if_you_want{
height:650px;
position: relative;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
align-items: center;
display: flex;
width: 95%;
max-width: 1200px;
}

SHOULD GIVE YOU SOMETHING LIKE THIS This is how it would look, adjust the width and margin and padding to achieve what you want

Date Format in Swift

Convert @BatyrCan answer to Swift 5.3 with extra formats. Tested in Xcode 12.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!

dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000

dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600

dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16

dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM

dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000

dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000

dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000

dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM

dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000

dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00

//Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm

// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)

How to connect HTML Divs with Lines?

You can use https://github.com/musclesoft/jquery-connections. This allows you connect block elements in DOM.

How to change the application launcher icon on Flutter?

you can achieve this by using flutter_launcher_icons in pubspec.yaml

another way is to use one for android and another one for iOS

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Different connections pools have different configs.

For example Tomcat (default) expects:

spring.datasource.ourdb.url=...

and HikariCP will be happy with:

spring.datasource.ourdb.jdbc-url=...

We can satisfy both without boilerplate configuration:

spring.datasource.ourdb.jdbc-url=${spring.datasource.ourdb.url}

There is no property to define connection pool provider.

Take a look at source DataSourceBuilder.java

If Tomcat, HikariCP or Commons DBCP are on the classpath one of them will be selected (in that order with Tomcat first).

... so, we can easily replace connection pool provider using this maven configuration (pom.xml):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>       

    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
    </dependency>

How to iterate through property names of Javascript object?

Use for...in loop:

for (var key in obj) {
   console.log(' name=' + key + ' value=' + obj[key]);

   // do some more stuff with obj[key]
}

Handling MySQL datetimes and timestamps in Java

In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date. It is basically backed by the Epoch time in flavor of a long, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.

In SQL side, there are several standard date and time types, DATE, TIME and TIMESTAMP (at some DB's also called DATETIME), which are represented in JDBC as java.sql.Date, java.sql.Time and java.sql.Timestamp, all subclasses of java.util.Date. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.

In contrary to java.util.Date, the java.sql.Date contains only information about the date part (year, month, day). The Time contains only information about the time part (hours, minutes, seconds) and the Timestamp contains information about the both parts, like as java.util.Date does.

The normal practice to store a timestamp in the DB (thus, java.util.Date in Java side and java.sql.Timestamp in JDBC side) is to use PreparedStatement#setTimestamp().

java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);

The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp().

Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.

Mask for an Input to allow phone numbers?

Reactive Form


See at Stackblitz

Addition to the @Günter Zöchbauer's answer above, I tried as follows and it seems to be working but I'm not sure whether it is a efficient way.

I use valueChanges observable to listen for change events in the reactive form by subscribing to it. For special handling of backspace, I get the data from subscribe and check it with userForm.value.phone(from [formGroup]="userForm"). Because, at that moment, the data changes to the new value but the latter refers to the previous value because of not setting yet. If the data is less than previous value then the user should remove character from input. In this case, change pattern as follows:

from : newVal = newVal.replace(/^(\d{0,3})/, '($1)');

to : newVal = newVal.replace(/^(\d{0,3})/, '($1');

Otherwise, as Günter Zöchbauer mentioned above, deleting of non-numeric characters is not recognized because when we remove parentheses from input, digits still remain the same and added again parentheses from pattern match.

Controller:

import { Component,OnInit } from '@angular/core';
import { FormGroup,FormBuilder,AbstractControl,Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  constructor(private fb:FormBuilder) { 
    this.createForm();
  }

  createForm(){
    this.userForm = this.fb.group({
      phone:['',[Validators.pattern(/^\(\d{3}\)\s\d{3}-\d{4}$/),Validators.required]],
    });
  }

  ngOnInit() {
   this.phoneValidate();
  }

  phoneValidate(){
    const phoneControl:AbstractControl = this.userForm.controls['phone'];

    phoneControl.valueChanges.subscribe(data => {
    /**the most of code from @Günter Zöchbauer's answer.*/

    /**we remove from input but: 
       @preInputValue still keep the previous value because of not setting.
    */
    let preInputValue:string = this.userForm.value.phone;
    let lastChar:string = preInputValue.substr(preInputValue.length - 1);

    var newVal = data.replace(/\D/g, '');
    //when removed value from input
    if (data.length < preInputValue.length) {

      /**while removing if we encounter ) character,
         then remove the last digit too.*/
      if(lastChar == ')'){
         newVal = newVal.substr(0,newVal.length-1); 
      }
      if (newVal.length == 0) {
        newVal = '';
      } 
      else if (newVal.length <= 3) {
        /**when removing, we change pattern match.
        "otherwise deleting of non-numeric characters is not recognized"*/
        newVal = newVal.replace(/^(\d{0,3})/, '($1');
      } else if (newVal.length <= 6) {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
      } else {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
      }
    //when typed value in input
    } else{


    if (newVal.length == 0) {
      newVal = '';
    } 
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
    }

  }
    this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});
  });
 }

}

Template:

<form [formGroup]="userForm"  novalidate>
  <div class="form-group">
    <label for="tel">Tel:</label>
    <input id="tel" formControlName="phone" maxlength="14">
  </div>
  <button [disabled]="userForm.status == 'INVALID'" type="submit">Send</button>
</form>

UPDATE

Is there a way to preserve cursor position while backspacing in the middle of the string? Currently, it jumps back to the end.

Define an id <input id="tel" formControlName="phone" #phoneRef> and renderer2#selectRootElement to get the native element in the component.

So we can get the cursor position using:

let start = this.renderer.selectRootElement('#tel').selectionStart;
let end = this.renderer.selectRootElement('#tel').selectionEnd;

and then we can apply it after the input is updated to new value:

this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});
//keep cursor the appropriate position after setting the input above.
this.renderer.selectRootElement('#tel').setSelectionRange(start,end);

UPDATE 2

It's probably better to put this sort of logic inside a directive rather than in the component

I also put the logic into a directive. This makes it easier to apply it to other elements.

See at Stackblitz

Note: It is specific to (123) 123-4567 pattern.

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

Count number of rows by group using dplyr

I think what you are looking for is as follows.

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())

This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You can use this tool to create appropriate c# classes:

http://jsonclassgenerator.codeplex.com/

and when you will have classes created you can simply convert string to object:

    public static T ParseJsonObject<T>(string json) where T : class, new()
    {
        JObject jobject = JObject.Parse(json);
        return JsonConvert.DeserializeObject<T>(jobject.ToString());
    }

Here that classes: http://ge.tt/2KGtbPT/v/0?c

Just fix namespaces.

Convert datetime to Unix timestamp and convert it back in python

def datetime_to_epoch(d1):

    # create 1,1,1970 in same timezone as d1
    d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
    time_delta = d1 - d2
    ts = int(time_delta.total_seconds())
    return ts


def epoch_to_datetime_string(ts, tz_name="UTC"):
    x_timezone = timezone(tz_name)
    d1 = datetime.fromtimestamp(ts, x_timezone)
    x = d1.strftime("%d %B %Y %H:%M:%S")
    return x

How to handle the modal closing event in Twitter Bootstrap?

Bootstrap Modal Events:

  1. hide.bs.modal => Occurs when the modal is about to be hidden.
  2. hidden.bs.modal => Occurs when the modal is fully hidden (after CSS transitions have completed).
<script type="text/javascript">
    $("#salesitems_modal").on('hide.bs.modal', function () {
        //actions you want to perform after modal is closed.
    });
</script>

I hope this will Help.

How do I execute cmd commands through a batch file?

cmd /c "command" syntax works well. Also, if you want to include an executable that contains a space in the path, you will need two sets of quotes.

cmd /c ""path to executable""

and if your executable needs a file input with a space in the path a another set

cmd /c ""path to executable" -f "path to file"" 

How can one grab a stack trace in C?

For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.

Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.

Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.

Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).

I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.

How can I solve the error LNK2019: unresolved external symbol - function?

In my case, set the cpp file to "C/C++ compiler" in "property"->"general", resolve the LNK2019 error.

How to make join queries using Sequelize on Node.js

Model1.belongsTo(Model2, { as: 'alias' })

Model1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

what is the difference between OLE DB and ODBC data sources?

At Microsoft website, it shows that native OLEDB provider is applied to SQL server directly and another OLEDB provider called OLEDB Provider for ODBC to access other Database, such as Sysbase, DB2 etc. There are different kinds of component under OLEDB Provider. See Distributed Queries on MSDN for more.

Showing empty view when ListView is empty

Activity code, its important to extend ListActivity.

package com.example.mylistactivity;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import com.example.mylistactivity.R;

// It's important to extend ListActivity rather than Activity
public class MyListActivity extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylist);

        // shows list view
        String[] values = new String[] { "foo", "bar" };

        // shows empty view
        values = new String[] { };

        setListAdapter(new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                android.R.id.text1,
                values));
    }
}

Layout xml, the id in both views are important.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- the android:id is important -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

    <!-- the android:id is important -->
    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="i am empty"/>
</LinearLayout>

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

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

How to make a <div> always full screen?

I don't have IE Josh, could you please test this for me. Thanks.

<html>
<head>
    <title>Hellomoto</title>
    <style text="text/javascript">
        .hellomoto
        {
            background-color:#ccc;
            position:absolute;
            top:0px;
            left:0px;
            width:100%;
            height:100%;
            overflow:auto;
        }
        body
        {
            background-color:#ff00ff;
            padding:0px;
            margin:0px;
            width:100%;
            height:100%;
            overflow:hidden;
        }
        .text
        {
            background-color:#cc00cc;
            height:800px;
            width:500px;
        }
    </style>
</head>
<body>
<div class="hellomoto">
    <div class="text">hellomoto</div>
</div>
</body>
</html>

How to implement LIMIT with SQL Server?

If i remember correctly (it's been a while since i dabbed with SQL Server) you may be able to use something like this: (2005 and up)

SELECT
    *
   ,ROW_NUMBER() OVER(ORDER BY SomeFields) AS [RowNum]
FROM SomeTable
WHERE RowNum BETWEEN 10 AND 20

Subset data.frame by date

Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:

 EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")

After that you can do this:

 EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )

R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.

Find which rows have different values for a given column in Teradata SQL

Personally, I would print them to a file using Perl or Python in the format

<COL_NAME>:  <COL_VAL>

for each row so that the file has as many lines as there are columns. Then I'd do a diff between the two files, assuming you are on Unix or compare them using some equivalent utilty on another OS. If you have multiple recordsets (i.e. more than one row), I would prepend to each file row and then the file would have NUM_DB_ROWS * NUM_COLS lines

jQuery UI accordion that keeps multiple sections open?

Pretty simple:

<script type="text/javascript">
    (function($) {
        $(function() {
            $("#accordion > div").accordion({ header: "h3", collapsible: true });
        })
    })(jQuery);
</script>

<div id="accordion">
    <div>
        <h3><a href="#">First</a></h3>
        <div>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</div>
    </div>
    <div>
        <h3><a href="#">Second</a></h3>
        <div>Phasellus mattis tincidunt nibh.</div>
    </div>
    <div>
        <h3><a href="#">Third</a></h3>
        <div>Nam dui erat, auctor a, dignissim quis.</div>
    </div>
</div>

how do I get eclipse to use a different compiler version for Java?

From the menu bar: Project -> Properties -> Java Compiler

Enable project specific settings (checked) Uncheck "use Compliance from execution environment '.... Select the desired "compiler compliance level"

That will allow you to compile "1.5" code using a "1.6" JDK.

If you want to acutally use a 1.5 JDK to produce "1.5" compliant code, then install a suitable 1.5 JDK and tell eclipse where it is installed via:

Window -> preferences -> Installed JREs

And then go back to your project

Project -> properties -> Java Build Path -> libraries

remove the 1.6 system libaries, and: add library... -> JRE System LIbrary -> Alternate JRE -> The JRE you want.

Verify that the correct JRE is on the project's build path, save everything, and enjoy!

How do I align a number like this in C?

Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf() format using sprintf(), or using %*d with the number of digits being passed as an int for the * and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf() with the buffer length of zero, the format %d and null for the string; the return value tells you how many characters would have been formatted.

If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.

Min and max value of input in angular4 application

If you are looking to validate length use minLength and maxLength instead.

open resource with relative path in Java

In the hopes of providing additional information for those who don't pick this up as quickly as others, I'd like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):

Project/
  src/                // application source code
    org/
      myproject/
        MyClass.java
  test/               // unit tests
  res/                // resources
    images/           // PNG images for icons
      my-image.png
    xml/              // XSD files for validating XML files with JAXB
      my-schema.xsd
    conf/             // default .conf file for Log4j
      log4j.conf
  lib/                // libraries added to build-path via project settings

I was having issues loading my resources from the res directory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the res directory to the build-path and then access the resource via:

static final ClassLoader loader = MyClass.class.getClassLoader();

// in some function
loader.getResource("images/my-image.png");
loader.getResource("xml/my-schema.xsd");
loader.getResource("conf/log4j.conf");

NOTE: The / is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String) instead of Class.getResource(String).

Suppress/ print without b' prefix for bytes in Python 3

you can use this code for showing or print :

<byte_object>.decode("utf-8")

and you can use this for encode or saving :

<str_object>.encode('utf-8')

How to use if statements in underscore.js templates?

Responding to blackdivine above (about how to stripe one's results), you may have already found your answer (if so, shame on you for not sharing!), but the easiest way of doing so is by using the modulus operator. say, for example, you're working in a for loop:

<% for(i=0, l=myLongArray.length; i<l; ++i) { %>
...
<% } %>

Within that loop, simply check the value of your index (i, in my case):

<% if(i%2) { %>class="odd"<% } else { %>class="even" <% }%>

Doing this will check the remainder of my index divided by two (toggling between 1 and 0 for each index row).

Deleting multiple columns based on column names in Pandas

My personal favorite, and easier than the answers I have seen here (for multiple columns):

df.drop(df.columns[22:56], axis=1, inplace=True)

Python urllib2, basic HTTP authentication, and tr.im

This seems to work really well (taken from another thread)

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

If you are connecting to an old SQL Server:

Switch from System.Data.SqlClient.SqlConnection to System.Data.OleDb.OleDbConnection

Use an OleDb connection string:

<connectionStrings>
<add name="Northwind" connectionString="Provider=SQLOLEDB.1; Data Source=MyServer; Initial Catalog=Northwind;  Persist Security Info=True; User ID=abc; Password=xyz;" providerName="System.Data.OleDb" />
</connectionStrings>

Javascript onload not working

Try this one:

<body onload="imageRefreshBig();">

Also you might want to check Javascript console for errors (in Chrome it's under Shift + Ctrl + J).

How to set JVM parameters for Junit Unit Tests?

You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.4</version>
    <configuration>
        <systemPropertyVariables>
            <java.protocol.handler.pkgs>com.zunix.base</java.protocol.handler.pkgs>
            <log4j.configuration>log4j-core.properties</log4j.configuration>
        </systemPropertyVariables>
    </configuration>
</plugin>

http://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

The answer is for the problem:

Exception in thread "main" java.lang.UnsupportedClassVersionError: edu/stevens/cs549/dhts/main/LocalContext : Unsupported major.minor version 52.0

I was having the same problem. For those who were having this trouble in AWS ec2 instances, and have somehow got redirected here to this question. I am answering for those, and would like to share that how I did it. I was having the trouble because Amazon EC2 instances were running java version 1.7 and maybe my project was not compatible with it because I was using Maven and it kind of preconfigured for java 1.8. So I installed new version of java:

sudo yum -y install java-1.8.0

And then the important step is to remove the older version:

sudo yum remove java-1.7.0-openjdk

Remember to delete it after installing the new version, else it would continuously be using the same older version and I hope it resolves your problem, which did in my case.

How to open new browser window on button click event?

It can be done all on the client-side using the OnClientClick[MSDN] event handler and window.open[MDN]:

<asp:Button 
     runat="server" 
     OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
     Open a new window!
</asp:Button>

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)) - so use it.

The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.

The specifics of this change can be viewed at:

Some additional references:

Download File Using jQuery

Here's a nice article that shows many ways of hiding files from search engines:

http://antezeta.com/news/avoid-search-engine-indexing

JavaScript isn't a good way not to index a page; it won't prevent users from linking directly to your files (and thus revealing it to crawlers), and as Rob mentioned, wouldn't work for all users.
An easy fix is to add the rel="nofollow" attribute, though again, it's not complete without robots.txt.

<a href="uploads/file.doc" rel="nofollow">Download Here</a>

How to find difference between two Joda-Time DateTimes in minutes

Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after

Python+OpenCV: cv2.imwrite

enter image description here enter image description here enter image description here

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

how to use php DateTime() function in Laravel 5

If you just want to get the current UNIX timestamp I'd just use time()

$timestamp = time(); 

what is the basic difference between stack and queue?

A stack is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in reverse order of their time of storage, i.e. the latest element stored is the next element to be retrieved. A stack is sometimes referred to as a Last-In-First-Out (LIFO) or First-In-Last-Out (FILO) structure. Elements previously stored cannot be retrieved until the latest element (usually referred to as the 'top' element) has been retrieved.

A queue is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in order of their time of storage, i.e. the first element stored is the next element to be retrieved. A queue is sometimes referred to as a First-In-First-Out (FIFO) or Last-In-Last-Out (LILO) structure. Elements subsequently stored cannot be retrieved until the first element (usually referred to as the 'front' element) has been retrieved.

how to convert 2d list to 2d numpy array?

I am using large data sets exported to a python file in the form

XVals1 = [.........] 
XVals2 = [.........] 

Each list is of identical length. I use

>>> a1 = np.array(SV.XVals1)

>>> a2 = np.array(SV.XVals2)

Then

>>> A = np.matrix([a1,a2])

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had a such problem too because i was using IMG tag and UL tag.

Try to apply the 'corners' plugin to elements such as $('#mydiv').corner(), $('#myspan').corner(), $('#myp').corner() but NOT for $('#img').corner()! This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.

I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.

Good luck!

How to wrap text around an image using HTML/CSS

With CSS Shapes you can go one step further than just float text around a rectangular image.

You can actually wrap text such that it takes the shape of the edge of the image or polygon that you are wrapping it around.

DEMO FIDDLE (Currently working on webkit - caniuse)

_x000D_
_x000D_
.oval {_x000D_
  width: 400px;_x000D_
  height: 250px;_x000D_
  color: #111;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  font-size: 90px;_x000D_
  float: left;_x000D_
  shape-outside: ellipse();_x000D_
  padding: 10px;_x000D_
  background-color: MediumPurple;_x000D_
  background-clip: content-box;_x000D_
}_x000D_
span {_x000D_
  padding-top: 70px;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="oval"><span>PHP</span>_x000D_
</div>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has_x000D_
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing_x000D_
  software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley_x000D_
  of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing_x000D_
  Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy_x000D_
  text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised_x000D_
  in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
_x000D_
_x000D_
_x000D_

Also, here is a good list apart article on CSS Shapes

Configure active profile in SpringBoot via Maven

I would like to run an automation test in different environments.
So I add this to command maven command:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"

Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

Assert that a WebElement is not present using Selenium WebDriver with java

The way that I have found best - and also to show in Allure report as fail - is to try-catch the findelement and in the catch block, set the assertTrue to false, like this:

    try {
        element = driver.findElement(By.linkText("Test Search"));
    }catch(Exception e) {
        assertTrue(false, "Test Search link was not displayed");
    }

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

I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.

This two threads explain it better:

pandas: merge (join) two data frames on multiple columns

the problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:

new_df = pd.merge(A_df, B_df,  how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')

And this is the correct way of using the function:

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

How to remove underline from a link in HTML?

This will remove all underlines from all links:

a {text-decoration: none; }

If you have specific links that you want to apply this to, give them a class name, like nounderline and do this:

a.nounderline {text-decoration: none; }

That will apply only to those links and leave all others unaffected.

This code belongs in the <head> of your document or in a stylesheet:

<head>
    <style type="text/css">
        a.nounderline {text-decoration: none; }
    </style>
</head>

And in the body:

<a href="#" class="nounderline">Link</a>

What's the most efficient way to test two integer ranges for overlap?

If someone is looking for a one-liner which calculates the actual overlap:

int overlap = ( x2 > y1 || y2 < x1 ) ? 0 : (y2 >= y1 && x2 <= y1 ? y1 : y2) - ( x2 <= x1 && y2 >= x1 ? x1 : x2) + 1; //max 11 operations

If you want a couple fewer operations, but a couple more variables:

bool b1 = x2 <= y1;
bool b2 = y2 >= x1;
int overlap = ( !b1 || !b2 ) ? 0 : (y2 >= y1 && b1 ? y1 : y2) - ( x2 <= x1 && b2 ? x1 : x2) + 1; // max 9 operations

How do I validate a date in rails?

A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:

Inside your model.rb

validate :date_field_must_be_a_date_or_blank

# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
  date_field_before_type_cast.to_date
rescue ArgumentError
  errors.add(:birthday, :invalid)
end

Remote branch is not showing up in "git branch -r"

The remote section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:

fetch = +refs/heads/*:refs/remotes/origin/*

(Or replace origin with bitbucket.)

Please read about it here: 10.5 Git Internals - The Refspec

Python convert decimal to hex

To get a pure hex value this might be useful. It's based on Joe's answer:

def gethex(decimal):
    return hex(decimal)[2:]

How to get the IP address of the docker host from inside a docker container

For those running Docker in AWS, the instance meta-data for the host is still available from inside the container.

curl http://169.254.169.254/latest/meta-data/local-ipv4

For example:

$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238

$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238

Number of days in particular month of particular year?

String date = "11-02-2000";
String[] input = date.split("-");
int day = Integer.valueOf(input[0]);
int month = Integer.valueOf(input[1]);
int year = Integer.valueOf(input[2]);
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month-1);
cal.set(Calendar.DATE, day);
//since month number starts from 0 (i.e jan 0, feb 1), 
//we are subtracting original month by 1
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(days);

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

mySQL Error 1040: Too Many Connection

I was getting this error even though I had all my Connections wrapped in using statements. The thing I was overlooking is how long those connections were staying open.

I was doing something like this:

using (MySqlConnection conn = new MySqlConnection(ConnectionString))
{
    conn.Open();
    foreach(var m in conn.Query<model>(sql))
    {
        // do something that takes a while, accesses disk or even open up other connections
    }
}

Remember that connection will not close until everything in the loop is done and if the loop creates more connections, they can really start adding up.

This is better:

List<model> models = null;
using (MySqlConnection conn = new MySqlConnection(ConnectionString))
{
    conn.Open();

    models = conn.Query<model>(sql).ToList(); // to list is needed here since once the connection is closed you can't step through an IEnumerable   
}

foreach(var m in models)
{
    // do something that takes a while, accesses disk or even open up other connections
}

That way your connection is allowed to close and is released back to the thread pool before you go to do other things

Is there a way to compile node.js source files?

I maybe very late but you can use "nexe" module that compile nodejs + your script in one executable: https://github.com/crcn/nexe

Eclipse doesn't stop at breakpoints

Breakpoints have seemed to work and not-work on the versions of Eclipse I've used the last couple years. Currently I'm using Juno and just experienced breakpoints-not-working again. The solutions above, although good ones, didn't work in my case.

Here's what worked in my case:

  1. deleted the project

  2. check it back out from svn

  3. import it into Eclipse again

  4. run "mvn eclipse:eclipse"

Since the project is also a Groovy/Http-bulder/junit-test project, I had to:

  1. convert the project from Java to Groovy

  2. add /src/test/groovy to the Java Build Path (Source folders on build path)

  3. include "**/*.groovy" on the Java Build Path for /src/test/groovy

How to get the list of all installed color schemes in Vim?

You can see the list of color schemes under /usr/share/vim/vimNN/colors (with NN being the version, e.g. vim74 for vim 7.4).

This is explained here.

On the linux servers I use via ssh, TAB prints ^I and CTRLd prints ^D.

Declare a variable in DB2 SQL

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;

CSV file written with Python has blank lines between each row

Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle.

Instead, you should keep it in text mode, but override the newline as empty. Like so:

with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

Don't know if this has been solved yet but I was getting similar problems with Anaconda python 3.7.3 and Idle on Windows 10. Fixed it by adding:

<path>\Anaconda3
<path>\Anaconda3\scripts
<path>\Anaconda3\Library\bin

to the PATH variable.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

To simply explain the difference,

  response.sendRedirect("login.jsp");

doesn't prepend the contextpath (refers to the application/module in which the servlet is bundled)

but, whereas

 request.getRequestDispathcer("login.jsp").forward(request, response);

will prepend the contextpath of the respective application

Furthermore, Redirect request is used to redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url.

Forward request is used to forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved.

Should I use <i> tag for icons instead of <span>?

I take a totally different approach to everyone else's answers here altogether. Let me prefix my solution and argue by stating that sometimes standards and conventions are meant to be broken, especially in the context of the standard HTML lexical tag definitions.

There's nothing to stop you from creating custom elements that are self-descriptive to it's very purpose.

Both modern browsers and even IE 6+ (w/ shim) can support things like:

<icon class="plus">

or

<icon-add>

Just make sure to normalize the tag:

 icon { display:block; margin:0; padding:0; border:0; ... }

and use a shim if you need to support IE9 or earlier (see post below).

Check out this StackOverflow Post:

Is there a way to create your own html tag in HTML5

To further my argument, both Google's Angular Directives and the new Polymer projects utilize the concept of custom HTML tags.

Python unexpected EOF while parsing

Check if all the parameters of functions are defined before they are called. I faced this problem while practicing Kaggle.

Is there a REAL performance difference between INT and VARCHAR primary keys?

As for Primary Key, whatever physically makes a row unique should be determined as the primary key.

For a reference as a foreign key, using an auto incrementing integer as a surrogate is a nice idea for two main reasons.
- First, there's less overhead incurred in the join usually.
- Second, if you need to update the table that contains the unique varchar then the update has to cascade down to all the child tables and update all of them as well as the indexes, whereas with the int surrogate, it only has to update the master table and it's indexes.

The drawaback to using the surrogate is that you could possibly allow changing of the meaning of the surrogate:

ex.
id value
1 A
2 B
3 C

Update 3 to D
id value
1 A
2 B
3 D

Update 2 to C
id value
1 A
2 C
3 D

Update 3 to B
id value
1 A
2 C
3 B

It all depends on what you really need to worry about in your structure and what means most.

How to use Fiddler to monitor WCF service

So simple, all you need is to change the address in the config client: instead of 'localhost' change to the machine name or IP

How to do an INNER JOIN on multiple columns

You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:

SELECT 
    airline, flt_no, fairport, tairport, depart, arrive, fare
FROM 
    flights
INNER JOIN 
    airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
    airports to_port ON (to_port.code = flights.tairport)
WHERE 
    from_port.code = '?' OR to_port.code = '?' OR airports.city='?'

Note that the to_port and from_port are aliases for the first and second copies of the airports table.

HTML Entity Decode

I recommend against using the jQuery code that was accepted as the answer. While it does not insert the string to decode into the page, it does cause things such as scripts and HTML elements to get created. This is way more code than we need. Instead, I suggest using a safer, more optimized function.

var decodeEntities = (function() {
  // this prevents any overhead from creating the object each time
  var element = document.createElement('div');

  function decodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
})();

http://jsfiddle.net/LYteC/4/

To use this function, just call decodeEntities("&amp;") and it will use the same underlying techniques as the jQuery version will—but without jQuery's overhead, and after sanitizing the HTML tags in the input. See Mike Samuel's comment on the accepted answer for how to filter out HTML tags.

This function can be easily used as a jQuery plugin by adding the following line in your project.

jQuery.decodeEntities = decodeEntities;

How can I hide the Android keyboard using JavaScript?

For anyone using vuejs or jquery with cordova, use document.activeElement.blur() ;

hideKeyboard() {
    document.activeElement.blur();
}

..and from my text box, I just call that function:

For VueJS : v-on:keyup.enter="hideKeyboard" Pressing the enter button closes the android keyboard.

for jQuery:

$('element').keypress(function(e) {
  if(e.keyCode===13) document.activeElement.blur();
}

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

return SQL table as JSON in python

If you are using an MSSQL Server 2008 and above, you can perform your SELECT query to return json by using the FOR JSON AUTO clause E.G

SELECT name, surname FROM users FOR JSON AUTO

Will return Json as

[{"name": "Jane","surname": "Doe" }, {"name": "Foo","surname": "Samantha" }, ..., {"name": "John", "surname": "boo" }]

HTML5 Canvas background image

Make sure that in case your image is not in the dom, and you get it from local directory or server, you should wait for the image to load and just after that to draw it on the canvas.

something like that:

function drawBgImg() {
    let bgImg = new Image();
    bgImg.src = '/images/1.jpg';
    bgImg.onload = () => {
        gCtx.drawImage(bgImg, 0, 0, gElCanvas.width, gElCanvas.height);
    }
}

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

How do I use select with date condition?

Another feature is between:

Select * from table where date between '2009/01/30' and '2009/03/30'

Why isn't textarea an input[type="textarea"]?

Maybe this is going a bit too far back but…

Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.

Marc Andreessen, 11 October 1993

How do I find the maximum of 2 numbers?

Just for the fun of it, after the party has finished and the horse bolted.

The answer is: max() !

Correct way to load a Nib for a UIView subclass

Well you could either initialize the xib using a view controller and use viewController.view. or do it the way you did it. Only making a UIView subclass as the controller for UIView is a bad idea.

If you don't have any outlets from your custom view then you can directly use a UIViewController class to initialize it.

Update: In your case:

UIViewController *genericViewCon = [[UIViewController alloc] initWithNibName:@"CustomView"];
//Assuming you have a reference for the activity indicator in your custom view class
CustomView *myView = (CustomView *)genericViewCon.view;
[parentView addSubview:myView];
//And when necessary
[myView.activityIndicator startAnimating]; //or stop

Otherwise you have to make a custom UIViewController(to make it as the file's owner so that the outlets are properly wired up).

YourCustomController *yCustCon = [[YourCustomController alloc] initWithNibName:@"YourXibName"].

Wherever you want to add the view you can use.

[parentView addSubview:yCustCon.view];

However passing the another view controller(already being used for another view) as the owner while loading the xib is not a good idea as the view property of the controller will be changed and when you want to access the original view, you won't have a reference to it.

EDIT: You will face this problem if you have setup your new xib with file's owner as the same main UIViewController class and tied the view property to the new xib view.

i.e;

  • YourMainViewController -- manages -- mainView
  • CustomView -- needs to load from xib as and when required.

The below code will cause confusion later on, if you write it inside view did load of YourMainViewController. That is because self.view from this point on will refer to your customview

-(void)viewDidLoad:(){
  UIView *childView= [[[NSBundle mainBundle] loadNibNamed:@"YourXibName" owner:self options:nil] objectAtIndex:0];
}

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

If you are using Spring MVC, then you need to declare default action servlet for static contents. Add the following entries in spring-action-servlet.xml. It worked for me.

NOTE: keep all the static contents outside WEB-INF.

<!-- Enable annotation-based controllers using @Controller annotations -->
<bean id="annotationUrlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="order" value="0" />
</bean>

<bean id="controllerClassNameHandlerMapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
    <property name="order" value="1" />
</bean>

<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

How does autowiring work in Spring?

There are 3 ways you can create an instance using @Autowired.

1. @Autowired on Properties

The annotation can be used directly on properties, therefore eliminating the need for getters and setters:

    @Component("userService")
    public class UserService {

        public String getName() {
            return "service name";
        }
    }

    @Component
    public class UserController {

        @Autowired
        UserService userService

    }

In the above example, Spring looks for and injects userService when UserController is created.

2. @Autowired on Setters

The @Autowired annotation can be used on setter methods. In the below example, when the annotation is used on the setter method, the setter method is called with the instance of userService when UserController is created:

public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
            this.userService = userService;
    }
}

3. @Autowired on Constructors

The @Autowired annotation can also be used on constructors. In the below example, when the annotation is used on a constructor, an instance of userService is injected as an argument to the constructor when UserController is created:

public class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService= userService;
    }
}

Make REST API call in Swift

swift 4

USE ALAMOFIRE in our App plz install pod file

pod 'Alamofire', '~> 4.0'

We can Use API for Json Data -https://swapi.co/api/people/

Then We can create A networking class for Our project- networkingService.swift

import Foundation
import Alamofire
typealias JSON = [String:Any]
class networkingService{
     static let shared = networkingService()
    private init() {}
    func getPeople(success successblock: @escaping (GetPeopleResponse) -> Void)
    {
    Alamofire.request("https://swapi.co/api/people/").responseJSON { response in
        guard let json = response.result.value as? JSON else {return}
       // print(json)
        do {
                let getPeopleResponse = try GetPeopleResponse(json: json)
                successblock(getPeopleResponse)
            }catch{}
    }
    }
    func getHomeWorld(homeWorldLink:String,completion: @escaping(String) ->Void){
        Alamofire.request(homeWorldLink).responseJSON {(response) in
            guard let json = response.result.value as? JSON,
            let name = json["name"] as? String
                else{return}
            completion(name)
        }
}
}

Then Create NetworkingError.swift class

import Foundation
enum networkingError : Error{
    case badNetworkigStuff

}

Then create Person.swift class

import Foundation
struct Person {
    private let homeWorldLink : String
    let birthyear : String
    let gender : String
    let haircolor : String
    let eyecolor : String
    let height : String
    let mass : String
    let name : String
    let skincolor : String
    init?(json : JSON) {
        guard let birthyear = json["birth_year"] as? String,
        let eyecolor = json["eye_color"] as? String,
        let gender = json["gender"] as? String,
        let haircolor = json["hair_color"] as? String,
        let height = json["height"] as? String,
        let homeWorldLink = json["homeworld"] as? String,
        let mass = json["mass"] as? String,
        let name = json["name"] as? String,
        let skincolor = json["skin_color"] as? String
        else { return nil }
        self.homeWorldLink = homeWorldLink
        self.birthyear = birthyear
        self.gender = gender
        self.haircolor = haircolor
        self.eyecolor = eyecolor
        self.height = height
        self.mass = mass
        self.name = name
        self.skincolor = skincolor
    }
    func homeWorld(_ completion: @escaping (String) -> Void)  {
        networkingService.shared.getHomeWorld(homeWorldLink: homeWorldLink){ (homeWorld) in
            completion(homeWorld)
        }
    }
}

Then create DetailVC.swift

import UIKit
class DetailVC: UIViewController {
    var person :Person!
    @IBOutlet var name: UILabel!
    @IBOutlet var birthyear: UILabel!
    @IBOutlet var homeworld: UILabel!
    @IBOutlet var eyeColor: UILabel!
    @IBOutlet var skinColor: UILabel!
    @IBOutlet var gender: UILabel!
    @IBOutlet var hairColor: UILabel!
    @IBOutlet var mass: UILabel!
    @IBOutlet var height: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
       print(person)
        name.text = person.name
        birthyear.text = person.birthyear
        eyeColor.text = person.eyecolor
        gender.text = person.gender
        hairColor.text = person.haircolor
        mass.text = person.mass
        height.text = person.height
        skinColor.text = person.skincolor
        person.homeWorld{(homeWorld) in
            self.homeworld.text = homeWorld
        }
    }
}

Then Create GetPeopleResponse.swift class

import Foundation
struct GetPeopleResponse {
    let people : [Person]
    init(json :JSON) throws {
        guard let results = json["results"] as? [JSON] else { throw networkingError.badNetworkigStuff}
        let people = results.map{Person(json: $0)}.flatMap{ $0 }
        self.people = people
        }
}

Then Our View controller class

import UIKit

class ViewController: UIViewController {

    @IBOutlet var tableVieww: UITableView!
    var people = [Person]()


    @IBAction func getAction(_ sender: Any)
    {
    print("GET")
        networkingService.shared.getPeople{ response in
            self.people = response.people
           self.tableVieww.reloadData()
        }
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        guard segue.identifier == "peopleToDetails",
        let detailVC = segue.destination as? DetailVC,
        let person = sender as AnyObject as? Person
        else {return}
        detailVC.person = person
        }
}
    extension ViewController:UITableViewDataSource{
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return people.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = UITableViewCell()
            cell.textLabel?.text = people[indexPath.row].name

            return cell

        }
    }
extension ViewController:UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "peopleToDetails", sender: people[indexPath.row])
    }
}

In our StoryBoard

plz Connect with our View with another one using segue with identifier -peopleToDetails

  • Use UITableView In our First View

  • Use UIButton For get the Data

  • Use 9 Labels in our DetailVc

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Using a scanner to accept String input and storing in a String Array

A cleaner approach would be to create a Person object that contains contactName, contactPhone, etc. Then, use an ArrayList rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:

while (!done) {
   Person person = new Person();
   String name = input.nextLine();
   person.setContactName(name);
   ...

   myPersonList.add(person);
}

Using the list will remove the need for array bounds checking.

Prepend line to beginning of a file

To put code to NPE's answer, I think the most efficient way to do this is:

def insert(originalfile,string):
    with open(originalfile,'r') as f:
        with open('newfile.txt','w') as f2: 
            f2.write(string)
            f2.write(f.read())
    os.rename('newfile.txt',originalfile)

Plot multiple boxplot in one graph

Since you don't mention a plot package , I propose here using Lattice version( I think there is more ggplot2 answers than lattice ones, at least since I am here in SO).

 ## reshaping the data( similar to the other answer)
 library(reshape2)
 dat.m <- melt(TestData,id.vars='Label')
 library(lattice)
 bwplot(value~Label |variable,    ## see the powerful conditional formula 
        data=dat.m,
        between=list(y=1),
        main="Bad or Good")

enter image description here

Index (zero based) must be greater than or equal to zero

Change this line:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Python SQL query string formatting

sql = ("select field1, field2, field3, field4 "
       "from table "
       "where condition1={} "
       "and condition2={}").format(1, 2)

Output: 'select field1, field2, field3, field4 from table 
         where condition1=1 and condition2=2'

if the value of condition should be a string, you can do like this:

sql = ("select field1, field2, field3, field4 "
       "from table "
       "where condition1='{0}' "
       "and condition2='{1}'").format('2016-10-12', '2017-10-12')

Output: "select field1, field2, field3, field4 from table where
         condition1='2016-10-12' and condition2='2017-10-12'"

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.

However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.

If you had a row named full_brand_name and you wanted to use the first two letters as a short name in the field small_name you could use:

CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
  SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END

How do I delete unpushed git commits?

Don't delete it: for just one commit git cherry-pick is enough.

But if you had several commits on the wrong branch, that is where git rebase --onto shines:

Suppose you have this:

 x--x--x--x <-- master
           \
            -y--y--m--m <- y branch, with commits which should have been on master

, then you can mark master and move it where you would want to be:

 git checkout master
 git branch tmp
 git checkout y
 git branch -f master

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- y branch, master branch

, reset y branch where it should have been:

 git checkout y
 git reset --hard HEAD~2 # ~1 in your case, 
                         # or ~n, n = number of commits to cancel

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- master branch
                ^
                |
                -- y branch

, and finally move your commits (reapply them, making actually new commits)

 git rebase --onto tmp y master
 git branch -D tmp


 x--x--x--x--m'--m' <-- master
           \
            -y--y <- y branch

Dynamically update values of a chartjs chart

You can check instance of Chart by using Chart.instances. This will give you all the charts instances. Now you can iterate on that instances and and change the data, which is present inside config. suppose you have only one chart in your page.

for (var _chartjsindex in Chart.instances) {
/* 
 * Here in the config your actual data and options which you have given at the 
   time of creating chart so no need for changing option only you can change data
*/
 Chart.instances[_chartjsindex].config.data = [];
 // here you can give add your data
 Chart.instances[_chartjsindex].update();
 // update will rewrite your whole chart with new value
 }

Generate Java class from JSON?

As far as I know there is no such tool. Yet.

The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.

However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.

So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).

Using number_format method in Laravel

If you are using Eloquent, in your model put:

public function getPriceAttribute($price)
{
    return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));
}

Where getPriceAttribute is your field on database. getSomethingAttribute.

How to restart a node.js server

Using "kill -9 [PID]" or "killall -9 node" worked for me where "kill -2 [PID]" did not work.

How to Set focus to first text input in a bootstrap modal after shown

I got that bootstrap added the following info on their page:

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
})

http://getbootstrap.com/javascript/#modals

Integer value in TextView

tv.setText(Integer.toString(intValue))

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

Action Image MVC3 Razor

This turned out to be a very useful thread.

For those who are allergic to curly braces, here is the VB.NET version of Lucas' and Crake's answers:

Public Module ActionImage
    <System.Runtime.CompilerServices.Extension()>
    Function ActionImage(html As HtmlHelper, Action As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

    <Extension()>
    Function ActionImage(html As HtmlHelper, Action As String, Controller As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, Controller, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

End Module

How to show/hide JPanels in a JFrame?

Call parent.remove(panel), where parent is the container that you want the frame in and panel is the panel you want to add.

"Use the new keyword if hiding was intended" warning

@wdavo is correct. The same is also true for functions.

If you override a base function, like Update, then in your subclass you need:

new void Update()
{
  //do stufff
}

Without the new at the start of the function decleration you will get the warning flag.

Add Twitter Bootstrap icon to Input box

Bootstrap 4.x

With Bootstrap 4 (and Font Awesome), we still can use the input-group wrapper around our form-control element, and now we can use an input-group-append (or input-group-prepend) wrapper with an input-group-text to get the job done:

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="my-search">
  <div class="input-group-append">
    <span class="input-group-text" id="my-search"><i class="fas fa-filter"></i></span>
  </div>
</div>

It will look something like this (thanks to KyleMit for the screenshot):

enter image description here

Learn more by visiting the Input group documentation.

Where can I find "make" program for Mac OS X Lion?

You need to install Xcode from App Store.

Then start Xcode, go to Xcode->Preferences->Downloads and install component named "Command Line Tools". After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.

Batch script loop

Probbally use goto like

@echo off
:Whatever
echo hello world
pause
echo TEST
goto Whatever

This does a inf (infinite) loop.

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If you don't care about checking the validity of the certificate just add the --no-check-certificate option on the wget command-line. This worked well for me.

NOTE: This opens you up to man-in-the-middle (MitM) attacks, and is not recommended for anything where you care about security.

Calling a phone number in swift

Swift 5: iOS >= 10.0

Only works on physical device.

private func callNumber(phoneNumber: String) {
    guard let url = URL(string: "telprompt://\(phoneNumber)"),
        UIApplication.shared.canOpenURL(url) else {
        return
    }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

SOLUTIONS

  1. Sometimes the project is created before installing g++. So install g++ first and then recreate your project. This worked for me.
  2. Paste the following line in CMakeCache.txt: CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++

Note the path to g++ depends on OS. I have used my fedora path obtained using which g++

How do I use floating-point division in bash?

Use calc. It's the easiest I found example:

calc 1+1

 2

calc 1/10

 0.1

How to compare two dates?

For calculating days in two dates difference, can be done like below:

import datetime
import math

issuedate = datetime(2019,5,9)   #calculate the issue datetime
current_date = datetime.datetime.now() #calculate the current datetime
diff_date = current_date - issuedate #//calculate the date difference with time also
amount = fine  #you want change

if diff_date.total_seconds() > 0.0:   #its matching your condition
    days = math.ceil(diff_date.total_seconds()/86400)  #calculate days (in 
    one day 86400 seconds)
    deductable_amount = round(amount,2)*days #calclulated fine for all days

Becuase if one second is more with the due date then we have to charge

View not attached to window manager crash

How to reproduce the bug:

  1. Enable this option on your device: Settings -> Developer Options -> Don't keep Activities.
  2. Press Home button while the AsyncTask is executing and the ProgressDialog is showing.

The Android OS will destroy an activity as soon as it is hidden. When onPostExecute is called the Activity will be in "finishing" state and the ProgressDialog will be not attached to Activity.

How to fix it:

  1. Check for the activity state in your onPostExecute method.
  2. Dismiss the ProgressDialog in onDestroy method. Otherwise, android.view.WindowLeaked exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing.

Try this fixed code:

public class YourActivity extends Activity {

    private void showProgressDialog() {
        if (pDialog == null) {
            pDialog = new ProgressDialog(StartActivity.this);
            pDialog.setMessage("Loading. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
        }
        pDialog.show();
    }

    private void dismissProgressDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        dismissProgressDialog();
        super.onDestroy();
    }

    class LoadAllProducts extends AsyncTask<String, String, String> {

        // Before starting background thread Show Progress Dialog
        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }

        //getting All products from url
        protected String doInBackground(String... args) {
            doMoreStuff("internet");
            return null;
        }

        // After completing background task Dismiss the progress dialog
        protected void onPostExecute(String file_url) {
            if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
                return;
            }
            dismissProgressDialog();
            something(note);
        }
    }
}

Set initial value in datepicker with jquery?

Use setDate

.datepicker( "setDate" , date )

Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

Java - Change int to ascii

Do you want to convert ints to chars?:

int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !

Or do you want to convert ints to Strings?

int yourInt = 33;
String str = String.valueOf(yourInt);

Or what is it that you mean?

How to force uninstallation of windows service

Just in case this answer helps someone: as found here, you might save yourself a lot of trouble running Sysinternals Autoruns as administrator. Just go to the "Services" tab and delete your service.

It did the trick for me on a machine where I didn't have any permission to edit the registry.

How can I close a browser window without receiving the "Do you want to close this window" prompt?

This works in Chrome 26, Internet Explorer 9 and Safari 5.1.7 (without the use of a helper page, ala Nick's answer):

<script type="text/javascript">
    window.open('javascript:window.open("", "_self", "");window.close();', '_self');
</script>

The nested window.open is to make IE not display the Do you want to close this window prompt.

Unfortunately it is impossible to get Firefox to close the window.

PHP - Move a file into a different folder on the server

I using shell read all data file then assign to array. Then i move file in top position.

i=0 
for file in /home/*.gz; do
    $file
    arr[i]=$file
    i=$((i+1)) 
done 
mv -f "${arr[0]}" /var/www/html/

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

I was trying to launch the app on the URL "http://192.168.0.1:4000/", and the above answers didn't help. Finally, I added the *:4000:localhost HTTP binding to the .vs/.../applicationhost.config, so now the binding section looks like this:

<bindings>
  <binding protocol="http" bindingInformation="*:4000:localhost" />
  <binding protocol="http" bindingInformation="*:4000:192.168.0.1" />
</bindings>

And it did the trick

How do I redirect output to a variable in shell?

read hash < <(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)

This technique uses Bash's "process substitution" not to be confused with "command substitution".

Here are a few good references:

Easiest way to compare arrays in C#

For unit tests, you can use CollectionAssert.AreEqual instead of Assert.AreEqual.

It is probably the easiest way.

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

You might use one of our plugins: the JQL enhancement functions - check out https://plugins.atlassian.com/plugin/details/22514

There is no interval on day, but we might add it in a next iteration, if you think it is usefull.

Francis.