Programs & Examples On #Sqlitejdbc

SQLite JDBC is the JDBC interface of SQLite database. It supports both single thread and thread-safe operation modes. Questions tagged by this tag should also be tagged Sqlite.

How to test code dependent on environment variables using JUnit?

For JUnit 4 users, System Lambda as suggested by Stefan Birkner is a great fit.

In case you are using JUnit 5, there is the JUnit Pioneer extension pack. It comes with @ClearEnvironmentVariable and @SetEnvironmentVariable. From the docs:

The @ClearEnvironmentVariable and @SetEnvironmentVariable annotations can be used to clear, respectively, set the values of environment variables for a test execution. Both annotations work on the test method and class level, are repeatable as well as combinable. After the annotated method has been executed, the variables mentioned in the annotation will be restored to their original value or will be cleared if they didn't have one before. Other environment variables that are changed during the test, are not restored.

Example:

@Test
@ClearEnvironmentVariable(key = "SOME_VARIABLE")
@SetEnvironmentVariable(key = "ANOTHER_VARIABLE", value = "new value")
void test() {
    assertNull(System.getenv("SOME_VARIABLE"));
    assertEquals("new value", System.getenv("ANOTHER_VARIABLE"));
}

CSS container div not getting height

Try inserting this clearing div before the last </div>

<div style="clear: both; line-height: 0;">&nbsp;</div>

Forward host port to docker container

I had a similar problem accessing a LDAP-Server from a docker container. I set a fixed IP for the container and added a firewall rule.

docker-compose.yml:

version: '2'
services:
  containerName:
    image: dockerImageName:latest
    extra_hosts:
      - "dockerhost:192.168.50.1"
    networks:
      my_net:
        ipv4_address: 192.168.50.2
networks:
  my_net:
    ipam:
      config:
      - subnet: 192.168.50.0/24

iptables rule:

iptables -A INPUT -j ACCEPT -p tcp -s 192.168.50.2 -d $192.168.50.1 --dport portnumberOnHost

Inside the container access dockerhost:portnumberOnHost

Negation in Python

The negation operator in Python is not. Therefore just replace your ! with not.

For your example, do this:

if not os.path.exists("/usr/share/sounds/blues") :
    proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
    proc.wait()

For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

Example:

blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
    try:
        os.mkdir(blues_sounds_path)
    except OSError:
        # Handle the case where the directory could not be created.

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

Access files stored on Amazon S3 through web browser

Filestash is the perfect tool for that:

  1. login to your bucket from https://www.filestash.app/s3-browser.html:

enter image description here

  1. create a shared link:

enter image description here

  1. Share it with the world

Also Filestash is open source. (Disclaimer: I am the author)

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

How do I create a datetime in Python from milliseconds?

What about this? I presume it can be counted on to handle dates before 1970 and after 2038.

target_date_time_ms = 200000 # or whatever
base_datetime = datetime.datetime( 1970, 1, 1 )
delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )
target_date = base_datetime + delta

as mentioned in the Python standard lib:

fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038.

Tensorflow image reading & display

Load names with tf.train.match_filenames_once get the number of files to iterate over with tf.size open session and enjoy ;-)

import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image

matplotlib.use('Agg')
import matplotlib.pyplot as plt


filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)

reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    num_files = sess.run(count_num_files)
    for i in range(num_files):
        image=img.eval()
        print(image.shape)
        Image.fromarray(np.asarray(image)).save('te.jpeg')

how to add the missing RANDR extension

I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.

The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).

New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/ (eg /opt/firefox31/). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.

How do I show my global Git configuration?

You can also use cat ~/.gitconfig.

Get text of label with jquery

Try using the html() function.

$('#<%=Label1.ClientID%>').html();

You're also missing the # to make it an ID you're searching for. Without the #, it's looking for a tag type.

rsync - mkstemp failed: Permission denied (13)

Surprisingly nobody have mentioned all powerful SUDO. Had the same problem and sudo fixed it

How to calculate 1st and 3rd quartiles?

np.percentile DOES NOT calculate the values of Q1, median, and Q3. Consider the sorted list below:

samples = [1, 1, 8, 12, 13, 13, 14, 16, 19, 22, 27, 28, 31]

running np.percentile(samples, [25, 50, 75]) returns the actual values from the list:

Out[1]: array([12., 14., 22.])

However, the quartiles are Q1=10.0, Median=14, Q3=24.5 (you can also use this link to find the quartiles and median online). One can use the below code to calculate the quartiles and median of a sorted list (because of sorting this approach requires O(nlogn) computations where n is the number of items). Moreover, finding quartiles and median can be done in O(n) computations using the Median of medians Selection algorithm (order statistics).

samples = sorted([28, 12, 8, 27, 16, 31, 14, 13, 19, 1, 1, 22, 13])

def find_median(sorted_list):
    indices = []

    list_size = len(sorted_list)
    median = 0

    if list_size % 2 == 0:
        indices.append(int(list_size / 2) - 1)  # -1 because index starts from 0
        indices.append(int(list_size / 2))

        median = (sorted_list[indices[0]] + sorted_list[indices[1]]) / 2
        pass
    else:
        indices.append(int(list_size / 2))

        median = sorted_list[indices[0]]
        pass

    return median, indices
    pass

median, median_indices = find_median(samples)
Q1, Q1_indices = find_median(samples[:median_indices[0]])
Q2, Q2_indices = find_median(samples[median_indices[-1] + 1:])

quartiles = [Q1, median, Q2]

print("(Q1, median, Q3): {}".format(quartiles))

Count number of 1's in binary representation

In python or any other convert to bin string then split it with '0' to get rid of 0's then combine and get the length.

len(''.join(str(bin(122011)).split('0')))-1

React Native fixed footer

When flex is a positive number, it makes the component flexible and it will be sized proportional to its flex value. So a component with flex set to 2 will take twice the space as a component with flex set to 1.

_x000D_
_x000D_
   <View style={{flex: 1}>_x000D_
            _x000D_
     <ScrollView>_x000D_
        //your scroll able content will be placed above your fixed footer content. _x000D_
        //when your content will grow bigger and bigger it will hide behind _x000D_
        //footer content. _x000D_
     </ScrollView>_x000D_
_x000D_
     <View style={styles.footerContainer}>_x000D_
        //your fixed footer content will sit fixed below your screen _x000D_
     </View>_x000D_
_x000D_
</View>
_x000D_
_x000D_
_x000D_

Android, landscape only orientation?

Just two steps needed:

  1. Apply setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); after setContentView().

  2. In the AndroidMainfest.xml, put this statement <activity android:name=".YOURCLASSNAME" android:screenOrientation="landscape" />

Hope it helps and happy coding :)

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

Using multiple .cpp files in c++ program?

You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

// main.cpp
#include "second.h"
int main () {
    secondFunction();
}

// second.h
void secondFunction();

// second.cpp
#include "second.h"
void secondFunction() {
   // do stuff
}

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

Android Studio 3.0 below working method:
Find your old zipped project.
If you have built the apk, you'll find the password in file:

Project\.gradle\2.14.1\taskArtifacts\taskArtifacts.bin

Pandroid.injected.signing.store.password=password

If you don't have zipped project, search your git repositories if you have .gradle folder pushed or not.
Otherwise you'll have to recover files and search files by content "Pandroid.injected.signing.store.password".

How can I determine whether a 2D Point is within a Polygon?

Compute the oriented sum of angles between the point p and each of the polygon apices. If the total oriented angle is 360 degrees, the point is inside. If the total is 0, the point is outside.

I like this method better because it is more robust and less dependent on numerical precision.

Methods that compute evenness of number of intersections are limited because you can 'hit' an apex during the computation of the number of intersections.

EDIT: By The Way, this method works with concave and convex polygons.

EDIT: I recently found a whole Wikipedia article on the topic.

How to create custom button in Android using XML Styles

Have a look at Styled Button it will surely help you. There are lots examples please search on INTERNET.

eg:style

<style name="Widget.Button" parent="android:Widget">
    <item name="android:background">@drawable/red_dot</item>
</style>

you can use your selector instead of red_dot

red_dot:

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

    <solid android:color="#f00"/>
    <size android:width="55dip"
        android:height="55dip"/>
</shape>

Button:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        style="@style/Widget.Button"
        android:text="Button" />

Can't choose class as main class in IntelliJ

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

Where does pip install its packages?

One can import the package then consult its help

import statsmodels
help(sm)

At the very bottom of the help there is a section FILE that indicates where this package was installed.

This solution was tested with at least matplotlib (3.1.2) and statsmodels (0.11.1) (python 3.8.2).

Get the new record primary key ID from MySQL insert query?

Here what you are looking for !!!

select LAST_INSERT_ID()

This is the best alternative of SCOPE_IDENTITY() function being used in SQL Server.

You also need to keep in mind that this will only work if Last_INSERT_ID() is fired following by your Insert query. That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.

For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?

How to run VBScript from command line without Cscript/Wscript

You may follow the following steps:

  • Open your CMD(Command Prompt)
  • Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
  • Type 'CD VBS' and hit Enter. Example: D:>CD VBS
  • Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Since Spark 1.5 you can use a number of date processing functions:

import datetime
from pyspark.sql.functions import year, month, dayofmonth

elevDF = sc.parallelize([
    (datetime.datetime(1984, 1, 1, 0, 0), 1, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 2, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 3, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 4, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 5, 638.55)
]).toDF(["date", "hour", "value"])

elevDF.select(
    year("date").alias('year'), 
    month("date").alias('month'), 
    dayofmonth("date").alias('day')
).show()
# +----+-----+---+
# |year|month|day|
# +----+-----+---+
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# +----+-----+---+

You can use simple map as with any other RDD:

elevDF = sqlContext.createDataFrame(sc.parallelize([
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=1, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=2, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=3, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=4, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=5, value=638.55)]))

(elevDF
 .map(lambda (date, hour, value): (date.year, date.month, date.day))
 .collect())

and the result is:

[(1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1)]

Btw: datetime.datetime stores an hour anyway so keeping it separately seems to be a waste of memory.

How do I iterate through lines in an external file with shell?

I know the purists will hate this method, but you can cat the file.

NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
   echo "$NAME"
done

Android Studio: Add jar as library?

I don' know why but my Android Studio 0.8.14 goes crazy when I try to implement these solutions using Gradle. I admit my poor knowledge of this great build tool but what does Studio mutilate my project for? I manage to get it working this way: put android-support-v13.jar into 'libs' directory, then F4 on my project and add File dependency where I pointed android-support-v13.jar.

How do I pass data between Activities in Android application?

I use public static fields to store shared data between activities, but to minimize its side effects, you may:

  • Make only one field, or as few as possible, and reuse them, make them of type object and cast it to desired type in the receiving activity.
  • Whenever any of them isn't useful anymore, set it explicitly to null to be collected by the garbage collector, before the next assignment.

Byte array to image conversion

This is inspired by Holstebroe's answer, plus comments here: Getting an Image object from a byte array

Bitmap newBitmap;
using (MemoryStream memoryStream = new MemoryStream(byteArrayIn))
    using (Image newImage = Image.FromStream(memoryStream))
        newBitmap = new Bitmap(newImage);
return newBitmap;

Index inside map() function

Array.prototype.map() index:

One can access the index Array.prototype.map() via the second argument of the callback function. Here is an example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
_x000D_
const map = array.map((x, index) => {_x000D_
  console.log(index);_x000D_
  return x + index;_x000D_
});_x000D_
_x000D_
console.log(map);
_x000D_
_x000D_
_x000D_

Other arguments of Array.prototype.map():

  • The third argument of the callback function exposes the array on which map was called upon
  • The second argument of Array.map() is a object which will be the this value for the callback function. Keep in mind that you have to use the regular function keyword in order to declare the callback since an arrow function doesn't have its own binding to the this keyword.

For example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
const thisObj = {prop1: 1}_x000D_
_x000D_
_x000D_
const map = array.map( function (x, index, array) {_x000D_
  console.log(array);_x000D_
  console.log(this)_x000D_
}, thisObj);
_x000D_
_x000D_
_x000D_

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Can I have onScrollListener for a ScrollView?

you can define a custom ScrollView class, & add an interface be called when scrolling like this:

public class ScrollChangeListenerScrollView extends HorizontalScrollView {


private MyScrollListener mMyScrollListener;

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

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

public ScrollChangeListenerScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}


public void setOnMyScrollListener(MyScrollListener myScrollListener){
    this.mMyScrollListener = myScrollListener;
}


@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    super.onScrollChanged(l, t, oldl, oldt);
    if(mMyScrollListener!=null){
        mMyScrollListener.onScrollChange(this,l,t,oldl,oldt);
    }

}

public interface MyScrollListener {
    void onScrollChange(View view,int scrollX,int scrollY,int oldScrollX, int oldScrollY);
}

}

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

I figured it out. Read the MSDN documentation and it says to use .Load instead of LoadXml when reading from strings. Found out this works 100% of time. Oddly enough using StringReader causes problems. I think the main reason is that this is a Unicode encoded string and that could cause problems because StringReader is UTF-8 only.

MemoryStream stream = new MemoryStream();
            byte[] data = body.PayloadEncoding.GetBytes(body.Payload);
            stream.Write(data, 0, data.Length);
            stream.Seek(0, SeekOrigin.Begin);

            XmlTextReader reader = new XmlTextReader(stream);

            // MSDN reccomends we use Load instead of LoadXml when using in memory XML payloads
            bodyDoc.Load(reader);

ES6 exporting/importing in index file

Nav.js comp inside components folder

export {Nav}

index.js in component folder

export {Nav} from './Nav';
export {Another} from './Another';

import anywhere

import {Nav, Another} from './components'

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

How do I set hostname in docker-compose?

The simplest way I have found is to just set the container name in the docker-compose.yml See container_name documentation. It is applicable to docker-compose v1+. It works for container to container, not from the host machine to container.

services:
  dns:
    image: phensley/docker-dns
    container_name: affy

Now you should be able to access affy from other containers using the container name. I had to do this for multiple redis servers in a development environment.

NOTE The solution works so long as you don't need to scale. Such as consistant individual developer environments.

Case insensitive regular expression without re.compile?

#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located from the start of the string. 
#'re.search' returns location of the where the match is found 
#'re.compile' creates a regex object that can be used for multiple matches

 >>> s = r'TeSt'   
 >>> print (re.match(s, r'test123', re.I))
 <_sre.SRE_Match object; span=(0, 4), match='test'>
 # OR
 >>> pattern = re.compile(s, re.I)
 >>> print(pattern.match(r'test123'))
 <_sre.SRE_Match object; span=(0, 4), match='test'>

How to change the order of DataFrame columns?

To set an existing column right/left of another, based on their names:

def df_move_column(df, col_to_move, col_left_of_destiny="", right_of_col_bool=True):
    cols = list(df.columns.values)
    index_max = len(cols) - 1

    if not right_of_col_bool:
        # set left of a column "c", is like putting right of column previous to "c"
        # ... except if left of 1st column, then recursive call to set rest right to it
        aux = cols.index(col_left_of_destiny)
        if not aux:
            for g in [x for x in cols[::-1] if x != col_to_move]:
                df = df_move_column(
                        df, 
                        col_to_move=g, 
                        col_left_of_destiny=col_to_move
                        )
            return df
        col_left_of_destiny = cols[aux - 1]

    index_old = cols.index(col_to_move)
    index_new = 0
    if len(col_left_of_destiny):
        index_new = cols.index(col_left_of_destiny) + 1

    if index_old == index_new:
        return df

    if index_new < index_old:
        index_new = np.min([index_new, index_max])
        cols = (
            cols[:index_new]
            + [cols[index_old]]
            + cols[index_new:index_old]
            + cols[index_old + 1 :]
        )
    else:
        cols = (
            cols[:index_old]
            + cols[index_old + 1 : index_new]
            + [cols[index_old]]
            + cols[index_new:]
        )

    df = df[cols]
    return df

E.g.

cols = list("ABCD")
df2 = pd.DataFrame(np.arange(4)[np.newaxis, :], columns=cols)
for k in cols:
    print(30 * "-")
    for g in [x for x in cols if x != k]:
        df_new = df_move_column(df2, k, g)
        print(f"{k} after {g}:  {df_new.columns.values}")
for k in cols:
    print(30 * "-")
    for g in [x for x in cols if x != k]:
        df_new = df_move_column(df2, k, g, right_of_col_bool=False)
        print(f"{k} before {g}:  {df_new.columns.values}")

Output:

enter image description here

What exceptions should be thrown for invalid or unexpected parameters in .NET?

ArgumentException:

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of ArgumentException should carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument.

A few subclasses also exist for specific types of invalidity. The link has summaries of the subtypes and when they should apply.

Passing a Bundle on startActivity()?

Passing data from one Activity to Activity in android

An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra() method. Data is passed as extras and are key/value pairs. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable objects from one activity to other.

Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);

Retrieving bundle data from android activity

You can retrieve the information using getData() methods on the Intent object. The Intent object can be retrieved via the getIntent() method.

 Intent intent = getIntent();
  if (null != intent) { //Null Checking
    String StrData= intent.getStringExtra(KEY);
    int NoOfData = intent.getIntExtra(KEY, defaultValue);
    boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
    char charData = intent.getCharExtra(KEY, defaultValue); 
  }

Android XXHDPI resources

According to the post linked in the G+ resource:

The gorgeous screen on the Nexus 10 falls into the XHDPI density bucket. On tablets, Launcher uses icons from one density bucket up [0] to render them slightly larger. To ensure that your launcher icon (arguably your apps most important asset) is crisp you need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.

So it looks like the xxhdpi is set for 480dpi. According to that, tablets use the assets from one dpi bucket higher than the one they're in for the launcher. The Nexus 10 being in bucket xhdpi will pull the launcher icon from the xxhdpi.

Source

Also, was not aware that tablets take resources from the asset bucket above their level. Noted.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

You should define the __unicode__ method on your model, and the template will call it automatically when you reference the instance.

What are some reasons for jquery .focus() not working?

You need to either put the code below the HTML or load if using the document load event:

<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
    $("#goal-input").focus();
});
</script>

Update:

Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:

if (goal) {
      step1.fadeOut('fast', function() {
          step1.hide();
          step2.fadeIn('fast', function() {  
              $("#name").focus();
          });
      });
}

Preventing form resubmission

I really like @Angelin's answer. But if you're dealing with some legacy code where this is not practical, this technique might work for you.

At the top of the file

// Protect against resubmits
if (empty($_POST))  {
   $_POST['last_pos_sub'] = time();
} else {
     if (isset($_POST['last_pos_sub'])){
        if ($_POST['last_pos_sub'] == $_SESSION['curr_pos_sub']) {
           redirect back to the file so POST data is not preserved
        }
        $_SESSION['curr_pos_sub'] = $_POST['last_pos_sub'];
     }
}

Then at the end of the form, stick in last_pos_sub as follows:

<input type="hidden" name="last_pos_sub" value=<?php echo $_POST['last_pos_sub']; ?>>

SSIS Text was truncated with status value 4

I suspect the or one or more characters had no match in the target code page part of the error.

If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

Run this in SSMS, it shows how line breaks in the SQL itself become part of string values that span lines :

PRINT 'Line 1
Line 2
Line 3'
PRINT ''

PRINT 'How long is a blank line feed?'
PRINT LEN('
')
PRINT ''

PRINT 'What are the ASCII values?'
PRINT ASCII(SUBSTRING('
',1,1))
PRINT ASCII(SUBSTRING('
',2,1))

Result :
Line 1
Line 2
Line 3

How long is a blank line feed?
2

What are the ASCII values?
13
10

Or if you'd rather specify your string on one line (almost!) you could employ REPLACE() like this (optionally use CHAR(13)+CHAR(10) as the replacement) :

PRINT REPLACE('Line 1`Line 2`Line 3','`','
')

Uncompress tar.gz file

Try this:

tar -zxvf file.tar.gz

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

You will find newest version of the chromedriver here: http://chromedriver.storage.googleapis.com/index.html - there is a 64bit version for linux.

Free space in a CMD shell

Using paxdiablo excellent solution I wrote a little bit more sophisticated batch script, which uses drive letter as the incoming argument and checks if drive exists on a tricky (but not beauty) way:

@echo off
setlocal enableextensions enabledelayedexpansion
set chkfile=drivechk.tmp
if "%1" == "" goto :usage
set drive=%1
set drive=%drive:\=%
set drive=%drive::=%
dir %drive%:>nul 2>%chkfile%
for %%? in (%chkfile%) do (
  set chksize=%%~z?
)
if %chksize% neq 0 (
  more %chkfile%
  del %chkfile%
  goto :eof
)
del %chkfile%
for /f "tokens=3" %%a in ('dir %drive%:\') do (
  set bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
echo %bytesfree% byte(s) free on volume %drive%:
endlocal

goto :eof
:usage
  echo.
  echo   usage: freedisk ^<driveletter^> (eg.: freedisk c)

note1: you may type simple letter (eg. x) or may use x: or x:\ format as drive letter in the argument

note2: script will display stderr from %chkfile% only if the size bigger than 0

note3: I saved this script as freedisk.cmd (see usage)

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

Maven2: Missing artifact but jars are in place

If the other solutions didn't work and you know the correct jars are in your repository then:

The problem is that eclipse caches the errors for some reason.

I solved this problem by deleting the errors in the Problems tab and then I refreshed the project explorer and all the exclamation points and errors never returned.

How to import Google Web Font in CSS file?

  1. Just go to https://fonts.google.com/
  2. Add font by clicking +
  3. Go to selected font > Embed > @IMPORT > copy url and paste in your .css file above body tag.
  4. It's done.

Align HTML input fields by :

I know that this approach has been taken before, But I believe that using tables, the layout can be generated easily, Though this may not be the best practice.

JSFiddle

HTML

<table>

    <tr><td>Name:</td><td><input type="text"/></td></tr>

    <tr><td>Age:</td><td><input type="text"/></td></tr>

</table>

<!--You can add the fields as you want-->

CSS

td{
    text-align:right;
}

How do I collapse sections of code in Visual Studio Code for Windows?

As of version 1.3.1 (2016-07-17), Block Collapse is much more convenient.

Any line followed by an indented line will have a '-' character to allow collapse. If the block is collapsed, it will then be replaced by a '+' character that will open the collapsed block.

The (Ctrl + Shift + Alt + ]) will still affect all blocks, closing one level. Each repeated use closed one more level. The (Ctrl + Shift + Alt + [) works in the opposite way.

Hooray, block collapse finally works usefully.

pull out p-values and r-squared from a linear regression

x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call"          "terms"        
 [3] "residuals"     "coefficients" 
 [5] "aliased"       "sigma"        
 [7] "df"            "r.squared"    
 [9] "adj.r.squared" "fstatistic"   
[11] "cov.unscaled" 
    summary(fit)$r.squared

CodeIgniter Active Record not equal

It worked fine with me,

$this->db->where("your_id !=",$your_id);

Or try this one,

$this->db->where("your_id <>",$your_id);

Or try this one,

$this->db->where("your_id IS NOT NULL");

all will work.

How to resize image (Bitmap) to a given size?

The other answers are correct as to "how" to resize them, but I would also thrown in the recommendation to just grab the resolution you are interested in, to begin with. Most Android devices offer a range of resolutions and you should pick one that gives you a file size that you're comfortable with. The biggest reason for this is that the native Android scaling algorithm (as detailed by Jin35 and Padma Kumar) produces pretty crappy results. It's not going to give you Photoshop quality resizing, even downscaling (to say nothing of upscaling, which I know you're not asking about, but that's just a non-starter).

So, you should try their solution and if you're happy with the outcome, great. But if not, I'd write a function that offers a range of width that you're happy with, and looks for that dimension (or whatever's closest) in the device's available picture size array and just set it and use it.

Best way to check if a drop down list contains a value?

If 0 is your default value, you can just use a simple assignment:

ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();

This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.

I use this mechanism quite a lot and find it very handy.

TypeScript: Interfaces vs Types

Here's another difference. I will... buy you a beer if you can explain the reasoning or reason as to this state of affairs:

enum Foo { a = 'a', b = 'b' }

type TFoo = {
  [k in Foo]: boolean;
}

const foo1: TFoo = { a: true, b: false} // good
// const foo2: TFoo = { a: true }       // bad: missing b
// const foo3: TFoo = { a: true, b: 0}  // bad: b is not a boolean

// So type does roughly what I'd expect and want

interface IFoo {
//  [k in Foo]: boolean;
/*
  Uncommenting the above line gives the following errors:
  A computed property name in an interface must refer to an expression whose type is a      
    literal type or a 'unique symbol' type.
  A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
  Cannot find name 'k'.
*/
}

// ???

This sort of makes me want to say the hell with interfaces unless I'm intentionally implementing some OOP design pattern, or require merging as described above (which I'd never do unless I had a very good reason for it).

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:

CREATE TABLE dbo.T(D DATETIME)

--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))

No warnings

What is size_t in C?

size_t is an unsigned integer data type which can assign only 0 and greater than 0 integer values. It measure bytes of any object's size and returned by sizeof operator. const is the syntax representation of size_t, but without const you can run the programm.

const size_t number;

size_t regularly used for array indexing and loop counting. If the compiler is 32-bit it would work on unsigned int. If the compiler is 64-bit it would work on unsigned long long int also. There for maximum size of size_t depending on compiler type.

size_t already define on <stdio.h> header file, but It can also define by <stddef.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h> headers.

  • Example (with const)
#include <stdio.h>

int main()
{
    const size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800


  • Example (without const)
#include <stdio.h>

int main()
{
    size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800

Cannot get a text value from a numeric cell “Poi”

Formatter will work fine in this case.

import org.apache.poi.ss.usermodel.DataFormatter;

FileInputStream fis = new FileInputStream(workbookName);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
DataFormatter formatter = new DataFormatter();
String val = formatter.formatCellValue(sheet.getRow(row).getCell(col));
list.add(val);   //Adding value to list

How to remove leading and trailing zeros in a string? Python

str.strip is the best approach for this situation, but more_itertools.strip is also a general solution that strips both leading and trailing elements from an iterable:

Code

import more_itertools as mit


iterables = ["231512-n\n","  12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']

Details

Notice, here we strip both leading and trailing "0"s among other elements that satisfy a predicate. This tool is not limited to strings.

See also docs for more examples of

more_itertools is a third-party library installable via > pip install more_itertools.

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

What happened to Lodash _.pluck?

Use _.map instead of _.pluck. In the latest version the _.pluck has been removed.

Convert String to Float in Swift

Works on Swift 5+

import Foundation

let myString:String = "50"
let temp = myString as NSString
let myFloat = temp.floatValue
print(myFloat)  //50.0
print(type(of: myFloat)) // Float

// Also you can guard your value in order to check what is happening whenever your app crashes.

guard let myFloat = temp.floatValue else {
fatalError(" fail to change string to float value.")
}

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

In seeking to fix the problem of pop-up, I discovered that Apple had a way around this concern.

Indeed, when you click on this link, if you installed the application, it is rerouted to it; otherwise, you will be redirected to the webpage, without any pop-up.

Link a photo with the cell in excel

Select both the column you are sorting, and the column that the picture is in (I am assuming the picture is small compared to the cell, i.e. it is "in" the cell). Make sure that the object positioning property is set as "move but don't size with cells". Now if you do a sort, the pictures will move with the list being sorted.

Note - you must include the column with the picture in your range when you sort, and the picture must fit inside the cell.

The following VBA snippet will make sure all pictures in your spreadsheet have their "move and size" property set:

Sub moveAndSize()
Dim s As Shape
For Each s In ActiveSheet.Shapes
  If s.Type = msoPicture Or s.Type = msoLinkedPicture Or s.Type = msoPlaceholder Then
    s.Placement = xlMove
  End If
Next
End Sub

If you want to make sure the picture continues to fit after you move it, you can use xlMoveAndSize instead of xlMove.

How to delete all files older than 3 days when "Argument list too long"?

To delete all files and directories within the current directory:

find . -mtime +3 | xargs rm -Rf

Or alternatively, more in line with the OP's original command:

find . -mtime +3 -exec rm -Rf -- {} \;

How to handle floats and decimal separators with html5 input type number

When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

How to convert an enum type variable to a string?

Did you try this:

#define stringify( name ) # name

enum enMyErrorValue
  {
  ERROR_INVALIDINPUT = 0,
  ERROR_NULLINPUT,
  ERROR_INPUTTOOMUCH,
  ERROR_IAMBUSY
  };

const char* enMyErrorValueNames[] = 
  {
  stringify( ERROR_INVALIDINPUT ),
  stringify( ERROR_NULLINPUT ),
  stringify( ERROR_INPUTTOOMUCH ),
  stringify( ERROR_IAMBUSY )
  };

void vPrintError( enMyErrorValue enError )
  {
  cout << enMyErrorValueNames[ enError ] << endl;
  }

int main()
  {
  vPrintError((enMyErrorValue)1);
  }

The stringify() macro can be used to turn any text in your code into a string, but only the exact text between the parentheses. There are no variable dereferencing or macro substitutions or any other sort of thing done.

http://www.cplusplus.com/forum/general/2949/

ASP.NET MVC Page Won't Load and says "The resource cannot be found"


Step 1 : Check to see if you have received the following update? http://support.microsoft.com/kb/894670 If you have you might want to follow this procedure and see if it works for you. It worked partially for me. The item where it mentions the additional "/" to be removed is not entirely true but it did give me some insight to change my project properties just a bit.

step 2 : Right click on your properties for your Web Project in your Solun. Select WEB > Choose Current Page instead of Specific Page.

step 3 : Go into your project where you keep your *.aspx's select a start page. (Should be the same as the current page or choose another one of your choice :) ) Hit Debug Run.

Check if String / Record exists in DataTable

I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...

string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
 //You have it ...
 }

jQuery remove options from select

When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)

$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list

Intellij Cannot resolve symbol on import

Simple Restart worked for me.

I would suggest first try with restart and then you may opt for invalidating the cache.

PS : Cleaning out the system caches will result in clearing the local history.

How do I compile C++ with Clang?

I do not know why there is no answer directly addressing the problem. When you want to compile C++ program, it is best to use clang++. For example, the following works for me:

clang++ -Wall -std=c++11 test.cc -o test

If compiled correctly, it will produce the executable file test, and you can run the file by using ./test.

Or you can just use clang++ test.cc to compile the program. It will produce a default executable file named a.out. Use ./a.out to run the file.

The whole process is a lot like g++ if you are familiar with g++. See this post to check which warnings are included with -Wall option. This page shows a list of diagnostic flags supported by Clang.

A note on using clang -x c++: Kim Gräsman says that you can also use clang -x c++ to compile cpp programs, but that may not be true. For example, I am having a simple program below:

#include <iostream>
#include <vector>

int main() {
    /* std::vector<int> v = {1, 2, 3, 4, 5}; */
    std::vector<int> v(10, 5);
    int sum = 0;
    for (int i = 0; i < v.size(); i++){
        sum += v[i]*2;
    }
    std::cout << "sum is " << sum << std::endl;
    return 0;
}                                                      

clang++ test.cc -o test will compile successfully, but clang -x c++ will not, showing a lot undefined references errors. So I guess they are not exactly equivalent. It is best to use clang++ instead of clang -x c++ when compiling c++ programs to avoid extra troubles.

  • clang version: 11.0.0
  • Platform: Ubuntu 16.04

nuget 'packages' element is not declared warning

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

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

...and you're done :)

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

Install-Package NuGet.Manifest.Schema -Version 2.0.0

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

%VisualStudioPath%\Xml\Schemas

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

How do I check out a remote Git branch?

If the remote branch name begins with special characteres you need to use single quotes around it in the checkout command, or else git won't know which branch you are talking about.

For example, I tried to checkout a remote branch named as #9773 but the command didn't work properly, as shown in the picture below:

enter image description here

For some reason I wondered if the sharp symbol (#) could have something to do with it, and then I tried surrounding the branch name with single quotes, like '#9773' rathen than just #9773, and fortunately it worked fine.

$ git checkout -b '#9773' origin/'#9773'

What is the difference between Promises and Observables?

Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.

Angular uses Observables which is from RxJS instead of promises for dealing with HTTP

Below are some important differences in promises & Observables.

difference between Promises and Observables

Working copy XXX locked and cleanup failed in SVN

Clean up certainly is not enough to solve this issue sometimes.

If you use TortoiseSVN v1.7.2 or greater, right click on the Parent directory of the locked file and select TortoiseSVN -> Repo Browser from the menu. In the Repro Browser GUI right click the file that is locked and there will be an option to remove the lock.

Adding a new line/break tag in XML

This solution worked to me:

<summary>Tootsie roll tiramisu macaroon wafer carrot cake. &#xD;Danish topping sugar plum tart bonbon caramels cake.</summary>

You will have the text in two lines.

This worked to me using the XmlReader.Read method.

Int or Number DataType for DataAnnotation validation attribute

ASP.NET Core 3.1

This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:

The attribute:

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
        }

        public override bool IsValid(object value)
        {
            return int.TryParse(value?.ToString() ?? "", out int newVal);
        }

        private bool MergeAttribute(
              IDictionary<string, string> attributes,
              string key,
              string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

Client side logic:

$.validator.addMethod("mustbeinteger",
    function (value, element, parameters) {
        return !isNaN(parseInt(value)) && isFinite(value);
    });

$.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
    options.rules.mustbeinteger = {};
    options.messages["mustbeinteger"] = options.message;
});

And finally the Usage:

 [MustBeInteger(ErrorMessage = "You must provide a valid number")]
 public int SomeNumber { get; set; }

How to simulate a click with JavaScript?

const Discord = require("discord.js");
const superagent = require("superagent");

module.exports = {
    name: "hug",
    category: "action",
    description: "hug a user!",
    usage: "hug <user>",
    run: async (client, message, args) => {
    let hugUser = message.mentions.users.first() 
    if(!hugUser) return message.channel.send("You forgot to mention somebody.");
    let hugEmbed2 = new Discord.MessageEmbed()
    .setColor("#36393F")
    .setDescription(`**${message.author.username}** hugged **himself**`)
    .setImage("https://i.kym-cdn.com/photos/images/original/000/859/605/3e7.gif")
     .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
  if (hugUser.id === message.author.id) return message.channel.send(hugEmbed2);
    const {body} = await superagent
    .get(`https://nekos.life/api/v2/img/hug`);

    let hugEmbed = new Discord.MessageEmbed()
    .setDescription(`**${message.author.username}** hugged **${message.mentions.users.first().username}**`)
    .setImage(body.url)
    .setColor("#36393F")
     .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
    message.channel.send(hugEmbed)
}
}

How to change Navigation Bar color in iOS 7?

If you need to support ios6 and ios7 then you get that particular light blue using this in your UIViewController:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    if ([[ver objectAtIndex:0] intValue] >= 7) {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:89/255.0f green:174/255.0f blue:235/255.0f alpha:1.0f];
        self.navigationController.navigationBar.translucent = NO;
    }else{
        self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:89/255.0f green:174/255.0f blue:235/255.0f alpha:1.0f];
    }
}

C# - Substring: index and length must refer to a location within the string

Your mistake is the parameters to Substring. The first parameter should be the start index and the second should be the length or offset from the startindex.

string newString = url.Substring(18, 7);

If the length of the substring can vary you need to calculate the length.

Something in the direction of (url.Length - 18) - 4 (or url.Length - 22)

In the end it will look something like this

string newString = url.Substring(18, url.Length - 22);

Display a message in Visual Studio's output window when not debug mode?

The Trace messages can occur in the output window as well, even if you're not in debug mode. You just have to make sure the the TRACE compiler constant is defined.

Maven Jacoco Configuration - Exclude classes/packages from report not working

Though Andrew already answered question with details , i am giving code how to exclude it in pom

           <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <configuration>
                    <excludes>
                        <exclude>**/*com/test/vaquar/khan/HealthChecker.class</exclude>
                    </excludes>
                </configuration>
                <executions>
                    <!-- prepare agent for measuring integration tests -->
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>jacoco-site</id>
                        <phase>package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

For Springboot application

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.sonarsource.scanner.maven</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                       <!-- Exclude class from test coverage -->
                        <exclude>**/*com/khan/vaquar/Application.class</exclude>
                        <!-- Exclude full package from test coverage -->
                        <exclude>**/*com/khan/vaquar/config/**</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

I assume the question is already answered. If above solution doesn't help in solving the issue then can use below to solve the issue.

The issue occurs if sometimes your maven user settings is not reflecting correct settings.xml file.

To update the settings file go to Windows > Preferences > Maven > User Settings and update the settings.xml to it correct location.

Once this is doen re-build the project, these should solve the issue. Thanks.

Sum values in foreach loop php

$total=0;
foreach($group as $key=>$value)
{
   echo $key. " = " .$value. "<br>"; 
   $total+= $value;
}
echo $total;

Why number 9 in kill -9 command in unix?

why kill -9 : the number 9 in the list of signals has been chosen to be SIGKILL in reference to "kill the 9 lives of a cat".

Multiple files upload in Codeigniter

private function upload_files($path, $title, $files)
{
    $config = array(
        'upload_path'   => $path,
        'allowed_types' => 'jpg|gif|png',
        'overwrite'     => 1,
    );

    $this->load->library('upload', $config);

    $images = array();

    foreach ($files['name'] as $key => $image) {
        $_FILES['images[]']['name']= $files['name'][$key];
        $_FILES['images[]']['type']= $files['type'][$key];
        $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
        $_FILES['images[]']['error']= $files['error'][$key];
        $_FILES['images[]']['size']= $files['size'][$key];

        $fileName = $title .'_'. $image;

        $images[] = $fileName;

        $config['file_name'] = $fileName;

        $this->upload->initialize($config);

        if ($this->upload->do_upload('images[]')) {
            $this->upload->data();
        } else {
            return false;
        }
    }
    return true;
}

Change the background color of a row in a JTable

The other answers given here work well since you use the same renderer in every column.

However, I tend to believe that generally when using a JTable you will have different types of data in each columm and therefore you won't be using the same renderer for each column. In these cases you may find the Table Row Rendering approach helpfull.

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

How to undo 'git reset'?

1.Use git reflog to get all references update.

2.git reset <id_of_commit_to_which_you_want_restore>

How Spring Security Filter Chain works

UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

No, UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, and this contains a RequestMatcher, that means you can define your own processing url, this filter only handle the RequestMatcher matches the request url, the default processing url is /login.

Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter executes chain.doFilter(request, response);.

More details about core fitlers

Does the form-login namespace element auto-configure these filters?

UsernamePasswordAuthenticationFilter is created by <form-login>, these are Standard Filter Aliases and Ordering

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

It depends on whether the before fitlers are successful, but FilterSecurityInterceptor is the last fitler normally.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, every fitlerChain has a RequestMatcher, if the RequestMatcher matches the request, the request will be handled by the fitlers in the fitler chain.

The default RequestMatcher matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**").

If you want to konw more about the fitlers, I think you can check source code in spring security. doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

Change the background color of a pop-up dialog

Only update your import.

import android.app.AlertDialog;

to

import android.support.v7.app.AlertDialog;

It will be fixed.

Add a pipe separator after items in an unordered list unless that item is the last on a line

You can use the following CSS to solve.

ul li { float: left; }
ul li:before { content: "|"; padding: 0 .5em; }
ul li:first-child:before { content: ""; padding: 0; }

Should work on IE8+ as well.

Is an HTTPS query string secure?

I don't agree with the statement about [...] HTTP referrer leakage (an external image in the target page might leak the password) in Slough's response.

The HTTP 1.1 RFC explicitly states:

Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP request if the referring page was transferred with a secure protocol.

Anyway, server logs and browser history are more than sufficient reasons not to put sensitive data in the query string.

How to get a cookie from an AJAX response?

Similar to yebmouxing I could not the

 xhr.getResponseHeader('Set-Cookie');

method to work. It would only return null even if I had set HTTPOnly to false on my server.

I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:

function getCookie(cookieName){
  var cookieArray = document.cookie.split(';');
  for(var i=0; i<cookieArray.length; i++){
    var cookie = cookieArray[i];
    while (cookie.charAt(0)==' '){
      cookie = cookie.substring(1);
    }
    cookieHalves = cookie.split('=');
    if(cookieHalves[0]== cookieName){
      return cookieHalves[1];
    }
  }
  return "";
}

How to change the display name for LabelFor in razor in mvc3?

This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.

You have 3 options:

  • Add a [DisplayName("Name goes here")] attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.
  • Add a string parameter to your Html.LabelFor. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"}) Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.
  • Third option. Use a meta-data class attached to the data class (details follow).

Option 3 - Add a Meta-Data Class:

Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.

For example, if your data class is MyModel with a SomekingStatus property, you could do it like this:

First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:

[MetadataType(typeof(MyModelMetaData))]
public partial class MyModel
{
}

All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).

Step 2: add a metatadata class referenced by your new partial class:

public class MyModelMetaData
{
    // Apply DisplayNameAttribute (or any other attributes)
    [DisplayName("My New Label")]
    public string SomekingStatus;
}

Reference: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx

Notes:

  • From memory, if you start using a metadata class, it may ignore existing attributes on the actual class ([required] etc) so you may need to duplicate those in the Meta-data class.
  • This does not operate by magic and will not just work with any classes. The code that looks for UI decoration attributes is designed to look for a meta-data class first.

Android Studio: /dev/kvm device permission denied

Running the below command in Ubuntu 18.04 worked for me sudo chown -R /dev/kvm

Pull all images from a specified directory and then display them

You need to change the loop from for ($i=1; $i<count($files); $i++) to for ($i=0; $i<count($files); $i++):

So the correct code is

<?php
$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print $image ."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}

?>

Bower: ENOGIT Git is not installed or not in the PATH

Just use the Git Bash instead of cmd.

How to store and retrieve a dictionary with redis

you can pickle your dict and save as string.

import pickle
import redis

r = redis.StrictRedis('localhost')
mydict = {1:2,2:3,3:4}
p_mydict = pickle.dumps(mydict)
r.set('mydict',p_mydict)

read_dict = r.get('mydict')
yourdict = pickle.loads(read_dict)

How to create empty text file from a batch file?

There are infinite approaches.

Commands that output nothing:

break
cls
color
goto
pushd
popd
prompt
title

Weird Commands:

CD.
REM.
@echo off
cmd /c
START >FILE

The outdated print command produces a blank file:

print /d:EMPTY_TEXT_FILE nul

PDF Blob - Pop up window not showing content

If you set { responseType: 'blob' }, no need to create Blob on your own. You can simply create url based with response content:

$http({
    url: "...",
    method: "POST",
    responseType: "blob"
}).then(function(response) {
    var fileURL = URL.createObjectURL(response.data);
    window.open(fileURL);
});

How do I make a simple crawler in PHP?

Thank you @hobodave.

However I found two weaknesses in your code. Your parsing of the original url to get the "host" segment stops at the first single slash. This presumes that all relative links start in the root directory. This only true sometimes.

original url   :  http://example.com/game/index.html
href in <a> tag:  highscore.html
author's intent:  http://example.com/game/highscore.html  <-200->
crawler result :  http://example.com/highscore.html       <-404->

fix this by breaking at the last single slash not the first

a second unrelated bug, is that $depth does not really track recursion depth, it tracks breadth of the first level of recursion.

If I believed this page were in active use I might debug this second issue, but I suspect the text I am writing now will never be read by anyone, human or robot, since this issue is six years old and I do not even have enough reputation to notify +hobodave directly about these defects by commmenting on his code. Thanks anyway hobodave.

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

The SQL Server login required is DOMAIN\machinename$. This is the how the calling NT AUTHORITY\NETWORK SERVICE appears to SQL Server (and file servers etc)

In SQL,

CREATE LOGIN [XYZ\Gandalf$] FROM WINDOWS

How to find out the MySQL root password

In your "hostname".err file inside the data folder MySQL works on, try to look for a string that starts with:

"A temporary password is generated for roor@localhost "

you can use

less /mysql/data/dir/hostname.err 

then slash command followed by the string you wish to look for

/"A temporary password"

Then press n, to go to the Next result.

SecurityError: The operation is insecure - window.history.pushState()

In my case I was missing 'www.' from the url I was pushing. It must be exact match, if you're working on www.test.com, you must push to www.test.com and not test.com

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

How to get the element clicked (for the whole document)?

Use delegate and event.target. delegate takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target is the jQ-normalized property of the event object representing the object from which the event originated.

$(document).delegate('*', 'click', function (event) {
    // event.target is the element
    // $(event.target).text() gets its text
});

Demo: http://jsfiddle.net/xXTbP/

NSURLErrorDomain error codes description

I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.

Variable number of arguments in C++?

In C++11 there is a way to do variable argument templates which lead to a really elegant and type safe way to have variable argument functions. Bjarne himself gives a nice example of printf using variable argument templates in the C++11FAQ.

Personally, I consider this so elegant that I wouldn't even bother with a variable argument function in C++ until that compiler has support for C++11 variable argument templates.

How can I install a local gem?

You can download gems from https://rubygems.org/gems/ or build you local gem via bundle and rack.

eg:

  • bundle gem yourGemName
  • rake install

Take care of installing dependencies before installing actual gems.

  • gem install --local /pathToFolder/xxx-2.6.1.gem

Note: If using fluentd td-agent and ruby on same machine. Please make sure to use td-agent's td-agent-gem command. td-agent has own Ruby.

Define an <img>'s src attribute in CSS

CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.

Declare a dictionary inside a static class

You can use the static/class constructor to initialize your dictionary:

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic;
    public static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

Java program to get the current date without timestamp

I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.

Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();

Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates

Date compareToDate;  // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
    today.get( Calendar.DAY_OF_YEAR  ) == compareTo.get( Calendar.DAY_OF_YEAR  ) ) {
  // They are the same day!
}

How to execute a stored procedure inside a select query

Thanks @twoleggedhorse.

Here is the solution.

  1. First we created a function

    CREATE FUNCTION GetAIntFromStoredProc(@parm Nvarchar(50)) RETURNS INTEGER
    
    AS
    BEGIN
       DECLARE @id INTEGER
    
       set @id= (select TOP(1) id From tbl where col=@parm)
    
       RETURN @id
    END
    
  2. then we do the select query

    Select col1, col2, col3,
    GetAIntFromStoredProc(T.col1) As col4
    From Tbl as T
    Where col2=@parm
    

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

fetch gives an empty response body

I just ran into this. As mentioned in this answer, using mode: "no-cors" will give you an opaque response, which doesn't seem to return data in the body.

opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.

In my case I was using Express. After I installed cors for Express and configured it and removed mode: "no-cors", I was returned a promise. The response data will be in the promise, e.g.

fetch('http://example.com/api/node', {
  // mode: 'no-cors',
  method: 'GET',
  headers: {
    Accept: 'application/json',
  },
},
).then(response => {
  if (response.ok) {
    response.json().then(json => {
      console.log(json);
    });
  }
});

Difference between Apache CXF and Axis

As per my experience CXF is good in terms of configuring it into Spring environment. Also the generated classes are simple to understand. And as it is more active, we get better support in comparison to AXIS or AXIS2.

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

You can do it with a separate UPDATE statement

UPDATE report.TEST target
SET    is Deleted = 'Y'
WHERE  NOT EXISTS (SELECT 1
                   FROM   main.TEST source
                   WHERE  source.ID = target.ID);

I don't know of any way to integrate this into your MERGE statement.

How can I monitor the thread count of a process on linux?

Newer JDK distributions ship with JConsole and VisualVM. Both are fantastic tools for getting the dirty details from a running Java process. If you have to do this programmatically, investigate JMX.

How to detect a textbox's content has changed

Use the onchange event in HTML/standard JavaScript.

In jQuery that is the change() event. For example:

$('element').change(function() { // do something } );

EDIT

After reading some comments, what about:

$(function() {
    var content = $('#myContent').val();

    $('#myContent').keyup(function() { 
        if ($('#myContent').val() != content) {
            content = $('#myContent').val();
            alert('Content has been changed');
        }
    });
});

Console.log(); How to & Debugging javascript

I like to add these functions in the head.

window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};

Now log won't break IE I can enable it or disable it in one place I can log inline

$(".classname").log(); //show an array of all elements with classname class

Change the selected value of a drop-down list with jQuery

jQuery's documentation states:

[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.

This behavior is in jQuery versions 1.2 and above.

You most likely want this:

$("._statusDDL").val('2');

CustomErrors mode="Off"

For me it was an error higher up in the web.config above the system.web.

the file blah didn't exist so it was throwing an error at that point. Because it hadn't yet got to the System.Web section yet it was using the server default setting for CUstomErrors (On)

How to do Select All(*) in linq to sql

You can use simple linq query as follow to select all records from sql table

var qry = ent.tableName.Select(x => x).ToList();

Restricting input to textbox: allowing only numbers and decimal point

I chose to tackle this on the oninput event in order to handle the issue for keyboard pasting, mouse pasting and key strokes. Pass true or false to indicate decimal or integer validation.

It's basically three steps in three one liners. If you don't want to truncate the decimals comment the third step. Adjustments for rounding can be made in the third step as well.

// Example Decimal usage;
// <input type="text"  oninput="ValidateNumber(this, true);" />
// Example Integer usage:
// <input type="text"  oninput="ValidateNumber(this, false);" />
function ValidateNumber(elm, isDecimal) {
    try {

        // For integers, replace everything except for numbers with blanks.
        if (!isDecimal) 
            elm.value = elm.value.replace(/[^0-9]/g, ''); 
        else {
            // 1. For decimals, replace everything except for numbers and periods with blanks.
            // 2. Then we'll remove all leading ocurrences (duplicate) periods
            // 3. Then we'll chop off anything after two decimal places.

            // 1. replace everything except for numbers and periods with blanks.
            elm.value = elm.value.replace(/[^0-9.]/g, '');

            //2. remove all leading ocurrences (duplicate) periods
            elm.value = elm.value.replace(/\.(?=.*\.)/g, '');

            // 3. chop off anything after two decimal places.
            // In comparison to lengh, our index is behind one count, then we add two for our decimal places.
            var decimalIndex = elm.value.indexOf('.');
            if (decimalIndex != -1) { elm.value = elm.value.substr(0, decimalIndex + 3); }
        }
    }
    catch (err) {
        alert("ValidateNumber " + err);
    }
}

PostgreSQL JOIN data from 3 tables

Maybe the following is what you are looking for:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';

How can I generate a list or array of sequential integers in Java?

This one might works for you....

void List<Integer> makeSequence(int begin, int end) {

  AtomicInteger ai=new AtomicInteger(begin);
  List<Integer> ret = new ArrayList(end-begin+1);

  while ( end-->begin) {

    ret.add(ai.getAndIncrement());

  }
  return ret;  
}

How to count number of records per day?

This one is like the answer above which uses the MySql DATE_FORMAT() function. I also selected just one specific week in Jan.

SELECT 
    DatePart(day, DateAdded) AS date, 
    COUNT(entryhash) AS count 
FROM Responses 
    where DateAdded > '2020-01-25' and DateAdded < '2020-02-01' 
GROUP BY 
    DatePart(day, DateAdded )

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

These solutions work, but they work for your code ONLY on your machine. I would add a couple of lines to your code that look like this:

import sys
if "C:\\My_Python_Lib" not in sys.path:
    sys.path.append("C:\\My_Python_Lib")

That should take care of your problems

"Eliminate render-blocking CSS in above-the-fold content"

Few tips that may help:

  • I came across this article in CSS optimization yesterday: CSS profiling for ... optimization
    A lot of useful info on CSS and what CSS causes the most performance drains.

  • I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.

  • Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.

Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.

How to specify HTTP error code?

I'd like to centralize the creation of the error response in this way:

app.get('/test', function(req, res){
  throw {status: 500, message: 'detailed message'};
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500).json({status: err.status, message: err.message})
});

So I have always the same error output format.

PS: of course you could create an object to extend the standard error like this:

const AppError = require('./lib/app-error');
app.get('/test', function(req, res){
  throw new AppError('Detail Message', 500)
});

'use strict';

module.exports = function AppError(message, httpStatus) {
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.message = message;
  this.status = httpStatus;
};

require('util').inherits(module.exports, Error);

PHP find difference between two datetimes

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;

How can I create a product key for my C# application?

Another good inexpensive tool for product keys and activations is a product called InstallKey. Take a look at www.lomacons.com

ggplot2: sorting a plot

Here are a couple of ways.

The first will order things based on the order seen in the data frame:

x$variable <- factor(x$variable, levels=unique(as.character(x$variable)) )

The second orders the levels based on another variable (value in this case):

x <- transform(x, variable=reorder(variable, -value) ) 

if...else within JSP or JSTL

<c:choose>
<c:when test="${not empty userid and userid ne null}">
      <sql:query dataSource="${dbsource}" var="usersql">
                SELECT * FROM newuser WHERE ID = ?;
                <sql:param value="${param.userid}" />
      </sql:query>
 </c:when>
 <c:otherwise >
       <sql:query dataSource="${dbsource}" var="usersql">
                 SELECT * FROM newuser WHERE username = ?;
                 <sql:param value="${param.username}" />
       </sql:query>                              
  </c:otherwise>

Using ls to list directories and their total sizes

du -sm * | sort -nr

Output by size

How can I escape latex code received through user input?

a='\nu + \lambda + \theta'
d=a.encode('string_escape').replace('\\\\','\\')
print(d)
# \nu + \lambda + \theta

This shows that there is a single backslash before the n, l and t:

print(list(d))
# ['\\', 'n', 'u', ' ', '+', ' ', '\\', 'l', 'a', 'm', 'b', 'd', 'a', ' ', '+', ' ', '\\', 't', 'h', 'e', 't', 'a']

There is something funky going on with your GUI. Here is a simple example of grabbing some user input through a Tkinter.Entry. Notice that the text retrieved only has a single backslash before the n, l, and t. Thus no extra processing should be necessary:

import Tkinter as tk

def callback():
    print(list(text.get()))

root = tk.Tk()
root.config()

b = tk.Button(root, text="get", width=10, command=callback)

text=tk.StringVar()

entry = tk.Entry(root,textvariable=text)
b.pack(padx=5, pady=5)
entry.pack(padx=5, pady=5)
root.mainloop()

If you type \nu + \lambda + \theta into the Entry box, the console will (correctly) print:

['\\', 'n', 'u', ' ', '+', ' ', '\\', 'l', 'a', 'm', 'b', 'd', 'a', ' ', '+', ' ', '\\', 't', 'h', 'e', 't', 'a']

If your GUI is not returning similar results (as your post seems to suggest), then I'd recommend looking into fixing the GUI problem, rather than mucking around with string_escape and string replace.

How to sync with a remote Git repository?

Generally git pull is enough, but I'm not sure what layout you have chosen (or has github chosen for you).

PHP 7 RC3: How to install missing MySQL PDO

Had the same issue, resolved by actually enabling the extension in the php.ini with the right file name. It was listed as php_pdo_mysql.so but the module name in /lib/php/modules was called just pdo_mysql.so

So just remove the "php_" prefix from the php.ini file and then restart the httpd service and it worked like a charm.

Please note that I'm using Arch and thus path names and services may be different depending on your distrubution.

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.


You can indeed use filters inside a boolean query.

LaTeX beamer: way to change the bullet indentation?

I use the package enumitem. You may then set such margins when you declare your lists (enumerate, description, itemize):

\begin{itemize}[leftmargin=0cm]
    \item Foo
    \item Bar
\end{itemize}

Naturally, the package provides lots of other nice customizations for lists (use 'label=' to change the bullet, use 'itemsep=' to change the spacing between items, etc...)

Error in finding last used cell in Excel with VBA

For the last 3+ years these are the functions that I am using for finding last row and last column per defined column(for row) and row(for column):

Last Column:

Function lastCol(Optional wsName As String, Optional rowToCheck As Long = 1) As Long

    Dim ws  As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    lastCol = ws.Cells(rowToCheck, ws.Columns.Count).End(xlToLeft).Column

End Function

Last Row:

Function lastRow(Optional wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row

End Function

For the case of the OP, this is the way to get the last row in column E:

Debug.Print lastRow(columnToCheck:=Range("E4:E48").Column)

Last Row, counting empty rows with data:

Here we may use the well-known Excel formulas, which give us the last row of a worksheet in Excel, without involving VBA - =IFERROR(LOOKUP(2,1/(NOT(ISBLANK(A:A))),ROW(A:A)),0)

In order to put this in VBA and not to write anything in Excel, using the parameters for the latter functions, something like this could be in mind:

Public Function LastRowWithHidden(Optional wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    Dim letters As String
    letters = ColLettersGenerator(columnToCheck)
    LastRowWithHidden = ws.Evaluate("=IFERROR(LOOKUP(2,1/(NOT(ISBLANK(" & letters & "))),ROW(" & letters & " )),0)")

End Function

Function ColLettersGenerator(col As Long) As String

    Dim result As Variant
    result = Split(Cells(1, col).Address(True, False), "$")
    ColLettersGenerator = result(0) & ":" & result(0)

End Function

Set Locale programmatically

 /**
 * Requests the system to update the list of system locales.
 * Note that the system looks halted for a while during the Locale migration,
 * so the caller need to take care of it.
 */
public static void updateLocales(LocaleList locales) {
    try {
        final IActivityManager am = ActivityManager.getService();
        final Configuration config = am.getConfiguration();

        config.setLocales(locales);
        config.userSetLocale = true;

        am.updatePersistentConfiguration(config);
    } catch (RemoteException e) {
        // Intentionally left blank
    }
}

How to count frequency of characters in a string?

You can use a java Map and map a char to an int. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.

For example:

HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    Integer val = map.get(c);
    if (val != null) {
        map.put(c, new Integer(val + 1));
    }
    else {
       map.put(c, 1);
   }
}

At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.

Alternatively, you can use Bozho's solution of using a Multiset and counting the total occurences.

Two Divs on the same row and center align both of them

Could this do for you? Check my JSFiddle

And the code:

HTML

<div class="container">
    <div class="div1">Div 1</div>
    <div class="div2">Div 2</div>
</div>

CSS

div.container {
    background-color: #FF0000;
    margin: auto;   
    width: 304px;
}

div.div1 {
    border: 1px solid #000;
    float: left;
    width: 150px;
}

div.div2 {
    border: 1px solid red;
    float: left;
    width: 150px;
}

How to use a RELATIVE path with AuthUserFile in htaccess?

you may put your Auth settings into a Environment. Like:

SetEnvIf HTTP_HOST testsite.local APPLICATION_ENV=development
<IfDefine !APPLICATION_ENV>
  Allow from all
  AuthType Basic
  AuthName "My Testseite - Login" 
  AuthUserFile /Users/tho/htdocs/wgh_staging/.htpasswd
  Require user username
</IfDefine>

The Auth is working, but I couldn't get my environment really running.

When to use self over $this?

$this-> is used to refer to a specific instance of a class's variables (member variables) or methods.

Example: 
$derek = new Person();

$derek is now a specific instance of Person. Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name

ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word "static" with "shared". Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).

Static Variables Example: Pretend we have a database class with a single member variable: static $num_connections; Now, put this in the constructor:

function __construct()
{
    if(!isset $num_connections || $num_connections==null)
    {
        $num_connections=0;
    }
    else
    {
        $num_connections++;
    }
}

Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:

function __destruct()
{
    $num_connections--;
}

Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:

echo DB::num_connections;

Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it's best to create just one, and share it (this is called a Singleton Pattern).

Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).

Static Method Example:

public static function prettyName($first_name, $last_name)
{
    echo ucfirst($first_name).' '.ucfirst($last_name);
}

echo Person::prettyName($derek->first_name, $derek->last_name);

As you can see, public static function prettyName knows nothing about the object. It's just working with the parameters you pass in, like a normal function that's not part of an object. Why bother, then, if we could just have it not as part of the object?

  1. First, attaching functions to objects helps you keep things organized, so you know where to find them.
  2. Second, it prevents naming conflicts. In a big project, you're likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it's no problem at all. No conflict. Yay static methods!

SELF:: If you are coding outside the object that has the static method you want to refer to, you must call it using the object's name View::format_phone_number($phone_number); If you are coding inside the object that has the static method you want to refer to, you can either use the object's name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut

The same goes for static variables: Example: View::templates_path versus self::templates_path

Inside the DB class, if we were referring to a static method of some other object, we would use the object's name: Example: Session::getUsersOnline();

But if the DB class wanted to refer to its own static variable, it would just say self: Example: self::connection;

Hope that helps clear things up :)

How to convert a double to long without casting?

If you have a strong suspicion that the DOUBLE is actually a LONG, and you want to

1) get a handle on its EXACT value as a LONG

2) throw an error when its not a LONG

you can try something like this:

public class NumberUtils {

    /**
    * Convert a {@link Double} to a {@link Long}.
    * Method is for {@link Double}s that are actually {@link Long}s and we just
    * want to get a handle on it as one.
    */
    public static long getDoubleAsLong(double specifiedNumber) {
        Assert.isTrue(NumberUtils.isWhole(specifiedNumber));
        Assert.isTrue(specifiedNumber <= Long.MAX_VALUE && specifiedNumber >= Long.MIN_VALUE);
        // we already know its whole and in the Long range
        return Double.valueOf(specifiedNumber).longValue();
    }

    public static boolean isWhole(double specifiedNumber) {
        // http://stackoverflow.com/questions/15963895/how-to-check-if-a-double-value-has-no-decimal-part
        return (specifiedNumber % 1 == 0);
    }
}

Long is a subset of Double, so you might get some strange results if you unknowingly try to convert a Double that is outside of Long's range:

@Test
public void test() throws Exception {
    // Confirm that LONG is a subset of DOUBLE, so numbers outside of the range can be problematic
    Assert.isTrue(Long.MAX_VALUE < Double.MAX_VALUE);
    Assert.isTrue(Long.MIN_VALUE > -Double.MAX_VALUE); // Not Double.MIN_VALUE => read the Javadocs, Double.MIN_VALUE is the smallest POSITIVE double, not the bottom of the range of values that Double can possible be

    // Double.longValue() failure due to being out of range => results are the same even though I minus ten
    System.out.println("Double.valueOf(Double.MAX_VALUE).longValue(): " + Double.valueOf(Double.MAX_VALUE).longValue());
    System.out.println("Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + Double.valueOf(Double.MAX_VALUE - 10).longValue());

    // casting failure due to being out of range => results are the same even though I minus ten
    System.out.println("(long) Double.valueOf(Double.MAX_VALUE): " + (long) Double.valueOf(Double.MAX_VALUE).doubleValue());
    System.out.println("(long) Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + (long) Double.valueOf(Double.MAX_VALUE - 10).doubleValue());
}

Get the records of last month in SQL server

Add the options which have been provided so far won't use your indexes at all.

Something like this will do the trick, and make use of an index on the table (if one exists).

DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = dateadd(mm, -1, getdate())
SET @StartDate = dateadd(dd, datepart(dd, getdate())*-1, @StartDate)
SET @EndDate = dateadd(mm, 1, @StartDate)

SELECT *
FROM Member
WHERE date_created BETWEEN @StartDate AND @EndDate

Easiest way to rotate by 90 degrees an image using OpenCV?

Update for transposition:

You should use cvTranspose() or cv::transpose() because (as you rightly pointed out) it's more efficient. Again, I recommend upgrading to OpenCV2.0 since most of the cvXXX functions just convert IplImage* structures to Mat objects (no deep copies). If you stored the image in a Mat object, Mat.t() would return the transpose.

Any rotation:

You should use cvWarpAffine by defining the rotation matrix in the general framework of the transformation matrix. I would highly recommend upgrading to OpenCV2.0 which has several features as well as a Mat class which encapsulates matrices and images. With 2.0 you can use warpAffine to the above.

How to upgrade safely php version in wamp server

  1. Simply Download the PHP version that you want from this url: http://wampserver.aviatechno.net/
  2. Goto your wamp\bin\php directory and extract it like this(Note: you need to rename your folder to phpversionOfPhp list of installed version in the directory
  3. Start wamp and click wamp icon and choose the version of php you want to use: https://gyazo.com/de5727d7e254795e238422783dec3758

Adding Git-Bash to the new Windows Terminal

Adding "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i" doesn't work for me. Because of space symbol (which is separator in cmd) in %PROGRAMFILES% terminal executes command "C:\Program" instead of "C:\Program Files\Git\bin\bash.exe -l -i". The solution should be something like adding quotation marks in json file, but I didn't figure out how. The only solution is to add "C:\Program Files\Git\bin" to %PATH% and write "commandline": "bash.exe" in profiles.json

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

Imply bit with constant 1 or 0 in SQL Server

Enjoy this :) Without cast each value individually.

SELECT ...,
  IsCoursedBased = CAST(
      CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
    AS BIT
  )
FROM fc

Is there a real solution to debug cordova apps

You can use Intel XDK IDE to develop and debug on emulator or on real device

I also found Visual Studio 2015 RC tools for cordova very good, with it's ripple emulator

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How to set minDate to current date in jQuery UI Datepicker?

Set minDate to current date in jQuery Datepicker :

$("input.DateFrom").datepicker({
    minDate: new Date()
});

How to disable text selection using jQuery?

Here's a more comprehensive solution to the disconnect selection, and the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)

(function($){

  $.fn.ctrlCmd = function(key) {

    var allowDefault = true;

    if (!$.isArray(key)) {
       key = [key];
    }

    return this.keydown(function(e) {
        for (var i = 0, l = key.length; i < l; i++) {
            if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
                allowDefault = false;
            }
        };
        return allowDefault;
    });
};


$.fn.disableSelection = function() {

    this.ctrlCmd(['a', 'c']);

    return this.attr('unselectable', 'on')
               .css({'-moz-user-select':'-moz-none',
                     '-moz-user-select':'none',
                     '-o-user-select':'none',
                     '-khtml-user-select':'none',
                     '-webkit-user-select':'none',
                     '-ms-user-select':'none',
                     'user-select':'none'})
               .bind('selectstart', false);
};

})(jQuery);

and call example:

$(':not(input,select,textarea)').disableSelection();

jsfiddle.net/JBxnQ/

This could be also not enough for old versions of FireFox (I can't tell which). If all this does not work, add the following:

.on('mousedown', false)

PHP - Session destroy after closing browser

Use the following code to destroy the session:

 <?php
    session_start();
    unset($_SESSION['sessionvariable']);
    header("Location:index.php");
    ?>

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.props.name}</span>
        </div>
      );
    }
});

Invalidating JSON Web Tokens

Keep an in-memory list like this

user_id   revoke_tokens_issued_before
-------------------------------------
123       2018-07-02T15:55:33
567       2018-07-01T12:34:21

If your tokens expire in one week then clean or ignore the records older than that. Also keep only the most recent record of each user. The size of the list will depend on how long you keep your tokens and how often users revoke their tokens. Use db only when the table changes. Load the table in memory when your application starts.

Java "lambda expressions not supported at this language level"

For me none of the solutions provided worked.

This should be your last resort: -> Open .iml file of your project change the LANGUAGE_LEVEL to JDK_1_8 or whatever version you wish. -> If this didn't help, you should grep "JDK" in your project root directory and find the file which contains version setting and set it to your preferred version.

Save Dataframe to csv directly to s3 Python

I use AWS Data Wrangler. For example:

import awswrangler as wr
import pandas as pd

# read a local dataframe
df = pd.read_parquet('my_local_file.gz')

# upload to S3 bucket
wr.s3.to_parquet(df=df, path='s3://mys3bucket/file_name.gz')

The same applies to csv files. Instead of read_parquet and to_parquet, use read_csv and to_csv with the proper file extension.

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

I think that you can just catch org.openqa.selenium.NoSuchElementException that will be thrown by driver.findElement if there's no such element:

import org.openqa.selenium.NoSuchElementException;

....

public static void assertLinkNotPresent(WebDriver driver, String text) {
    try {
        driver.findElement(By.linkText(text));
        fail("Link with text <" + text + "> is present");
    } catch (NoSuchElementException ex) { 
        /* do nothing, link is not present, assert is passed */ 
    }
}

How to find out the number of CPUs using python

Another option is to use the psutil library, which always turn out useful in these situations:

>>> import psutil
>>> psutil.cpu_count()
2

This should work on any platform supported by psutil(Unix and Windows).

Note that in some occasions multiprocessing.cpu_count may raise a NotImplementedError while psutil will be able to obtain the number of CPUs. This is simply because psutil first tries to use the same techniques used by multiprocessing and, if those fail, it also uses other techniques.

How to find all the subclasses of a class given its name?

How can I find all subclasses of a class given its name?

We can certainly easily do this given access to the object itself, yes.

Simply given its name is a poor idea, as there can be multiple classes of the same name, even defined in the same module.

I created an implementation for another answer, and since it answers this question and it's a little more elegant than the other solutions here, here it is:

def get_subclasses(cls):
    """returns all subclasses of argument, cls"""
    if issubclass(cls, type):
        subclasses = cls.__subclasses__(cls)
    else:
        subclasses = cls.__subclasses__()
    for subclass in subclasses:
        subclasses.extend(get_subclasses(subclass))
    return subclasses

Usage:

>>> import pprint
>>> list_of_classes = get_subclasses(int)
>>> pprint.pprint(list_of_classes)
[<class 'bool'>,
 <enum 'IntEnum'>,
 <enum 'IntFlag'>,
 <class 'sre_constants._NamedIntConstant'>,
 <class 'subprocess.Handle'>,
 <enum '_ParameterKind'>,
 <enum 'Signals'>,
 <enum 'Handlers'>,
 <enum 'RegexFlag'>]

Change column type in pandas

I thought I had the same problem but actually I have a slight difference that makes the problem easier to solve. For others looking at this question it's worth checking the format of your input list. In my case the numbers are initially floats not strings as in the question:

a = [['a', 1.2, 4.2], ['b', 70, 0.03], ['x', 5, 0]]

but by processing the list too much before creating the dataframe I lose the types and everything becomes a string.

Creating the data frame via a numpy array

df = pd.DataFrame(np.array(a))

df
Out[5]: 
   0    1     2
0  a  1.2   4.2
1  b   70  0.03
2  x    5     0

df[1].dtype
Out[7]: dtype('O')

gives the same data frame as in the question, where the entries in columns 1 and 2 are considered as strings. However doing

df = pd.DataFrame(a)

df
Out[10]: 
   0     1     2
0  a   1.2  4.20
1  b  70.0  0.03
2  x   5.0  0.00

df[1].dtype
Out[11]: dtype('float64')

does actually give a data frame with the columns in the correct format

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

"Could not find the main class" error when running jar exported by Eclipse

Right click on the project. Go to properties. Click on Run/Debug Settings. Now delete the run config of your main class that you are trying to run. Now, when you hit run again, things would work just fine.

Getting DOM node from React child element

I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.setRef = this.setRef.bind(this)
  }

  setRef(node) {
    this.childRef = node
  }

  render() {
    return <Child setRef={ this.setRef }/>
  }
}

const Child = ({ setRef }) => (
    <div ref={ setRef }>
    </div>
)

Here's an example of doing this with a modal:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      modalOpen: false
    }
    this.open = this.open.bind(this)
    this.close = this.close.bind(this)
    this.setModal = this.setModal.bind(this)
  }

  open() {
    this.setState({ open: true })
  }

  close(event) {
    if (!this.modal.contains(event.target)) {
      this.setState({ open: false })
    }
  }

  setModal(node) {
    this.modal = node
  }

  render() {
    let { modalOpen } = this.state
    return (
      <div>
        <button onClick={ this.open }>Open</button>
        {
          modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
        }
      </div>
    )
  }
}

const Modal = ({ close, setModal }) => (
  <div className='modal' onClick={ close }>
    <div className='modal-window' ref={ setModal }>
    </div>
  </div>
)

Select entries between dates in doctrine 2

Look how I format my date $jour in the parameters. It depends if you use a expr()->like or a expr()->lte

$qb
        ->select('e')
        ->from('LdbPlanningBundle:EventEntity', 'e')
        ->where(
            $qb->expr()->andX(
                $qb->expr()->orX(
                    $qb->expr()->like('e.start', ':jour1'),
                    $qb->expr()->like('e.end', ':jour1'),
                    $qb->expr()->andX(
                        $qb->expr()->lte('e.start', ':jour2'),
                        $qb->expr()->gte('e.end', ':jour2')
                    )
                ),
                $qb->expr()->eq('e.user', ':user')
            )
        )
        ->andWhere('e.user = :user ')
        ->setParameter('user', $user)
        ->setParameter('jour1', '%'.$jour->format('Y-m-d').'%')
        ->setParameter('jour2', $jour->format('Y-m-d'))
        ->getQuery()
        ->getArrayResult()
    ;

Print current call stack from a method in Python code

import traceback
traceback.print_stack()

How to do one-liner if else statement?

Sometimes, I try to use anonymous function to achieve defining and assigning happen at the same line. like below:

a, b = 4, 8

c := func() int {
    if a >b {
      return a
    } 
    return b
  } ()

https://play.golang.org/p/rMjqytMYeQ0

Changing .gitconfig location on Windows

As someone who has been interested in this for a VERY LONG TIME. See from the manual:

$XDG_CONFIG_HOME/git/config - Second user-specific configuration file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/config will be used. Any single-valued variable set in this file will be overwritten by whatever is in ~/.gitconfig. It is a good idea not to create this file if you sometimes use older versions of Git, as support for this file was added fairly recently.

Which was only recently added. This dump is from 2.15.0.

Works for me.

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

WebAPI Multiple Put/Post parameters

[HttpPost]
public string MyMethod([FromBody]JObject data)
{
    Customer customer = data["customerData"].ToObject<Customer>();
    Product product = data["productData"].ToObject<Product>();
    Employee employee = data["employeeData"].ToObject<Employee>();
    //... other class....
}

using referance

using Newtonsoft.Json.Linq;

Use Request for JQuery Ajax

var customer = {
    "Name": "jhon",
    "Id": 1,
};
var product = {
    "Name": "table",
    "CategoryId": 5,
    "Count": 100
};
var employee = {
    "Name": "Fatih",
    "Id": 4,
};

var myData = {};
myData.customerData = customer;
myData.productData = product;
myData.employeeData = employee;

$.ajax({
    type: 'POST',
    async: true,
    dataType: "json",
    url: "Your Url",
    data: myData,
    success: function (data) {
        console.log("Response Data ?");
        console.log(data);
    },
    error: function (err) {
        console.log(err);
    }
});

Load RSA public key from file

Once you have your key stored in a PEM file, you can read it back easily using PemObject and PemReader classes provided by BouncyCastle, as shown in this this tutorial.

Create a PemFile class that encapsulates file handling:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

public class PemFile {

    private PemObject pemObject;

    public PemFile(String filename) throws FileNotFoundException, IOException {
        PemReader pemReader = new PemReader(new InputStreamReader(
                new FileInputStream(filename)));
        try {
            this.pemObject = pemReader.readPemObject();
        } finally {
            pemReader.close();
        }
    }

    public PemObject getPemObject() {
        return pemObject;
    }
}

Then instantiate private and public keys as usual:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Main {

    protected final static Logger LOGGER = Logger.getLogger(Main.class);

    public final static String RESOURCES_DIR = "src/main/resources/rsa-sample/";

    public static void main(String[] args) throws FileNotFoundException,
            IOException, NoSuchAlgorithmException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        LOGGER.info("BouncyCastle provider added.");

        KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
        try {
            PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
                    + "id_rsa");
            LOGGER.info(String.format("Instantiated private key: %s", priv));

            PublicKey pub = generatePublicKey(factory, RESOURCES_DIR
                    + "id_rsa.pub");
            LOGGER.info(String.format("Instantiated public key: %s", pub));
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }

    private static PrivateKey generatePrivateKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
        return factory.generatePrivate(privKeySpec);
    }

    private static PublicKey generatePublicKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
        return factory.generatePublic(pubKeySpec);
    }
}

Hope this helps.

Why would you use String.Equals over ==?

There is practical difference between string.Equals and ==

bool result = false;

object obj = "String";    
string str2 = "String";
string str3 = typeof(string).Name;
string str4 = "String";
object obj2 = str3;

// Comparision between object obj and string str2 -- Com 1
result = string.Equals(obj, str2);// true
result = String.ReferenceEquals(obj, str2); // true
result = (obj == str2);// true

// Comparision between object obj and string str3 -- Com 2
result = string.Equals(obj, str3);// true
result = String.ReferenceEquals(obj, str3); // false
result = (obj == str3);// false

// Comparision between object obj and string str4 -- Com 3
result = string.Equals(obj, str4);// true
result = String.ReferenceEquals(obj, str4); // true
result = (obj == str4);// true

// Comparision between string str2 and string str3 -- Com 4
result = string.Equals(str2, str3);// true
result = String.ReferenceEquals(str2, str3); // false
result = (str2 == str3);// true

// Comparision between string str2 and string str4 -- Com 5
result = string.Equals(str2, str4);// true
result = String.ReferenceEquals(str2, str4); // true
result = (str2 == str4);// true

// Comparision between string str3 and string str4 -- Com 6
result = string.Equals(str3, str4);// true
result = String.ReferenceEquals(str3, str4); // false
result = (str3 == str4);// true

// Comparision between object obj and object obj2 -- Com 7
result = String.Equals(obj, obj2);// true
result = String.ReferenceEquals(obj, obj2); // false
result = (obj == obj2);// false

Adding Watch

obj     "String" {1#}   object {string}
str2    "String" {1#}   string
str3    "String" {5#}   string
str4    "String" {1#}   string
obj2    "String" {5#}   object {string}

Now look at {1#} and {5#}

obj, str2, str4 and obj2 references are same.

obj and obj2 are object type and others are string type

Conclusion:

  1. com1: result = (obj == str2);// true
    • compares object and string so performs a reference equality check
    • obj and str2 point to the same reference so the result is true
  2. com2: result = (obj == str3);// false
    • compares object and string so performs a reference equality check
    • obj and str3 point to the different references so the result is false
  3. com3: result = (obj == str4);// true
    • compares object and string so performs a reference equality check
    • obj and str4 point to the same reference so the result is true
  4. com4: result = (str2 == str3);// true
    • compares string and string so performs a string value check
    • str2 and str3 are both "String" so the result is true
  5. com5: result = (str2 == str4);// true
    • compares string and string so performs a string value check
    • str2 and str4 are both "String" so the result is true
  6. com6: result = (str3 == str4);// true
    • compares string and string so performs a string value check
    • str3 and str4 are both "String" so the result is true
  7. com7: result = (obj == obj2);// false  - compares object and object so performs a reference equality check      - obj and obj2 point to the different references so the result is false

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

What is the use of adding a null key or value to a HashMap in Java?

One example of usage for null values is when using a HashMap as a cache for results of an expensive operation (such as a call to an external web service) which may return null.

Putting a null value in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey) returns false), and where the operation has been performed but returned a null value (cache.containsKey(someKey) returns true, cache.get(someKey) returns null).

Without null values, you would have to either put some special value in the cache to indicate a null response, or simply not cache that response at all and perform the operation every time.

How to run a program automatically as admin on Windows 7 at startup?

You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.

This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks will create by default a priority of 7.

Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();

public void EnsureStarupTaskExists()
{
    try
    {
        m_runAtStartupLock.EnterWriteLock();


        using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
        {
            // Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
            ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);

            // Create a new task definition and assign properties
            using(var td = ts.NewTask())
            {
                td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                // This is not normally necessary. RealTime is the highest priority that
                // there is.
                td.Settings.Priority = ProcessPriorityClass.RealTime;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.WakeToRun = false;
                td.Settings.AllowDemandStart = false;
                td.Settings.IdleSettings.RestartOnIdle = false;                    
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.RestartCount = 0;                    
                td.Settings.AllowHardTerminate = false;
                td.Settings.Hidden = true;
                td.Settings.Volatile = false;
                td.Settings.Enabled = true;
                td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.RegistrationInfo.Description = "Runs the content filter at startup.";

                // Create a trigger that will fire the task at this time every other day
                var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
                logonTrigger.Enabled = true;                    
                logonTrigger.Repetition.StopAtDurationEnd = false;
                logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
                td.Triggers.Add(logonTrigger);

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
            }
        }                
    }
    finally
    {
        m_runAtStartupLock.ExitWriteLock();
    }
}