Programs & Examples On #Kbhit

How can I disable all views inside the layout?

For me RelativeLayout or any other layout at the end of the xml file with width and height set to match_parent with attribute focusable and clickable set to true.

 <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true"
            android:focusable="true">

        <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true" />

    </RelativeLayout>

Clean out Eclipse workspace metadata

There is no easy way to remove the "outdated" stuff from an existing workspace. Using the "clean" parameter will not really help, as many of the files you refer to are "free form data", only known to the plugins that are no longer available.

Your best bet is to optimize the re-import, where I would like to point out the following:

  • When creating a new workspace, you can already choose to have some settings being copied from the current to the new workspace.
  • You can export the preferences of the current workspace (using the Export menu) and re-import them in the new workspace.
  • There are lots of recommendations on the Internet to just copy the ${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings folder from the old to the new workspace. This is surely the fastest way, but it may lead to weird behaviour, because some of your plugins may depend on these settings and on some of the mentioned "free form data" stored elsewhere. (There are even people symlinking these folders over multiple workspaces, but this really requires to use the same plugins on all workspaces.)
  • You may want to consider using more project specific settings than workspace preferences in the future. So for instance all the Java compiler settings can either be set on the workspace level or on the project level. If set on the project level, you can put them under version control and are independent of the workspace.

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

Here is my python cv2 implementation:

import cv2

img=cv2.imread("path_to_image.jpg")

# rotate ccw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=0)

# rotate cw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=1)

cv2.imwrite("rotated.jpg", out)

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

You shouldn't change the npm registry using .bat files. Instead try to use modify the .npmrc file which is the configuration for npm. The correct command for changing registry is

npm config set registry <registry url>

you can find more information with npm help config command, also check for privileges when and if you are running .bat files this way.

How to properly apply a lambda function into a pandas data frame column

You need to add else in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.

sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x) 

How to check if variable is array?... or something array-like

<?php
$var = new ArrayIterator();

var_dump(is_array($var), ($var instanceof ArrayIterator));

returns bool(false) or bool(true)

How to use variables in a command in sed?

This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1

#include errors detected in vscode

In my case I did not need to close the whole VS-Code, closing the opened file (and sometimes even saving it) solved the issue.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Using local makefile for CLion instead of CMake

I am not very familiar with CMake and could not use Mondkin's solution directly.

Here is what I came up with in my CMakeLists.txt using the latest version of CLion (1.2.4) and MinGW on Windows (I guess you will just need to replace all: g++ mytest.cpp -o bin/mytest by make if you are not using the same setup):

cmake_minimum_required(VERSION 3.3)
project(mytest)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

add_custom_target(mytest ALL COMMAND mingw32-make WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

And the custom Makefile is like this (it is located at the root of my project and generates the executable in a bin directory):

all:
    g++ mytest.cpp -o bin/mytest

I am able to build the executable and errors in the log window are clickable.

Hints in the IDE are quite limited through, which is a big limitation compared to pure CMake projects...

How do I get the object if it exists, or None if it does not exist?

It's one of those annoying functions that you might not want to re-implement:

from annoying.functions import get_object_or_None
#...
user = get_object_or_None(Content, name="baby")

How do you set, clear, and toggle a single bit?

Check a bit at an arbitrary location in a variable of arbitrary type:

#define bit_test(x, y)  ( ( ((const char*)&(x))[(y)>>3] & 0x80 >> ((y)&0x07)) >> (7-((y)&0x07) ) )

Sample usage:

int main(void)
{
    unsigned char arr[8] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };

    for (int ix = 0; ix < 64; ++ix)
        printf("bit %d is %d\n", ix, bit_test(arr, ix));

    return 0;
}

Notes: This is designed to be fast (given its flexibility) and non-branchy. It results in efficient SPARC machine code when compiled Sun Studio 8; I've also tested it using MSVC++ 2008 on amd64. It's possible to make similar macros for setting and clearing bits. The key difference of this solution compared with many others here is that it works for any location in pretty much any type of variable.

Calculate AUC in R?

As mentioned by others, you can compute the AUC using the ROCR package. With the ROCR package you can also plot the ROC curve, lift curve and other model selection measures.

You can compute the AUC directly without using any package by using the fact that the AUC is equal to the probability that a true positive is scored greater than a true negative.

For example, if pos.scores is a vector containing a score of the positive examples, and neg.scores is a vector containing the negative examples then the AUC is approximated by:

> mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T))
[1] 0.7261

will give an approximation of the AUC. You can also estimate the variance of the AUC by bootstrapping:

> aucs = replicate(1000,mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T)))

How to change UIPickerView height

Swift: You need to add a subview with clip to bounds

    var DateView = UIView(frame: CGRectMake(0, 0, view.frame.width, 100))
    DateView.layer.borderWidth=1
    DateView.clipsToBounds = true

    var myDatepicker = UIDatePicker(frame:CGRectMake(0,-20,view.frame.width,162));
    DateView.addSubview(myDatepicker);
    self.view.addSubview(DateView)

This should add a clipped 100 height date picker in the top of the view controller.

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

I have also faced the similar problem with the following details Java 1.8.0_121, Spark spark-1.6.1-bin-hadoop2.6, Windows 10 and Eclipse Oxygen.When I ran my WordCount.java in Eclipse using HADOOP_HOME as a system variable as mentioned in the previous post, it did not work, what worked for me is -

System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR");

PATH/TO/THE/DIR/bin=winutils.exe whether you run within Eclipse as a Java application or by spark-submit from cmd using

spark-submit --class groupid.artifactid.classname --master local[2] /path to the jar file created using maven /path to a demo test file /path to output directory command

Example: Go to the bin location of Spark/home/location/bin and execute the spark-submit as mentioned,

D:\BigData\spark-2.3.0-bin-hadoop2.7\bin>spark-submit --class com.bigdata.abdus.sparkdemo.WordCount --master local[1] D:\BigData\spark-quickstart\target\spark-quickstart-0.0.1-SNAPSHOT.jar D:\BigData\spark-quickstart\wordcount.txt

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

How to pass variable from jade template file to a script file?

It's a little late but...

script.
  loginName="#{login}";

This is working fine in my script. In Express, I am doing this:

exports.index = function(req, res){
  res.render( 'index',  { layout:false, login: req.session.login } );
};

I guess the latest jade is different?

Merc.

edit: added "." after script to prevent Jade warning.

How to get back to the latest commit after checking out a previous commit?

If you know the commit you want to return to is the head of some branch, or is tagged, then you can just

git checkout branchname

You can also use git reflog to see what other commits your HEAD (or any other ref) has pointed to in the past.


Edited to add:

In newer versions of Git, if you only ran git checkout or something else to move your HEAD once, you can also do

git checkout -

to switch back to wherever it was before the last checkout. This was motivated by the analogy to the shell idiom cd - to go back to whatever working directory one was previously in.

Applying a single font to an entire website with CSS

Put the font-family declaration into a body selector:

body {
  font-family: Algerian;
}

All the elements on your page will inherit this font-family then (unless, of course you override it later).

Install Windows Service created in Visual Studio

You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".

It won't install right out of the box... you need to create the installer class first.

Some reference on service installer:

How to: Add Installers to Your Service Application

Quite old... but this is what I am talking about:

Windows Services in C#: Adding the Installer (part 3)

By doing this, a ProjectInstaller.cs will be automaticaly created. Then you can double click this, enter the designer, and configure the components:

  • serviceInstaller1 has the properties of the service itself: Description, DisplayName, ServiceName and StartType are the most important.

  • serviceProcessInstaller1 has this important property: Account that is the account in which the service will run.

For example:

this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;

Get all variables sent with POST?

Using this u can get all post variable

print_r($_POST)

HttpWebRequest-The remote server returned an error: (400) Bad Request

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

How to attach a file using mail command on Linux?

On Linux I would suggest,

# FILE_TO_BE_ATTACHED=abc.gz

uuencode abc.gz abc.gz > abc.gz.enc # This is optional, but good to have
                                    # to prevent binary file corruption.
                                    # also it make sure to get original 
                                    # file on other system, w/o worry of endianness

# Sending Mail, multiple attachments, and multiple receivers.
echo "Body Part of Mail" | mailx -s "Subject Line" -a attachment1 -a abc.gz.enc "[email protected] [email protected]"

Upon receiving mail attachment, if you have used uuencode, you would need uudecode

uudecode abc.gz.enc

# This will generate file as original with name as same as the 2nd argument for uuencode.

How to get current memory usage in android?

you can also use DDMS tool which is part of android SDK it self. it helps in getting memory allocations of java code and native c/c++ code as well.

Turn a string into a valid filename?

You can use list comprehension together with the string methods.

>>> s
'foo-bar#baz?qux@127/\\9]'
>>> "".join(x for x in s if x.isalnum())
'foobarbazqux1279'

Sending cookies with postman

You can enable Interceptor in browser and in Postman separately. For send/recieve cookies you should enable Interceptor in Postman. So if you enable interceptor only in browser - it will not work. Actually you don't need enable Interceptor in browser at all - if you don't want to flood your postman history with unnecessary requests.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Microsoft listed the following methods for getting the a View definition: http://technet.microsoft.com/en-us/library/ms175067.aspx


USE AdventureWorks2012;
GO
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('HumanResources.vEmployee'); 
GO

USE AdventureWorks2012; 
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) 
AS ObjectDefinition; 
GO

EXEC sp_helptext 'HumanResources.vEmployee';

How to use QTimer

  1. It's good practice to give a parent to your QTimer to use Qt's memory management system.

  2. update() is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.

  3. If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.

  4. Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.

Set time to 00:00:00

You would better to primarily set time zone to the DateFormat component like this:

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

Then you can get "00:00:00" time by passing 0 milliseconds to formatter:

String time = dateFormat.format(0);

or you can create Date object:

Date date = new Date(0); // also pass milliseconds
String time = dateFormat.foramt(date);

or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.SECOND, 27);

dateFormat.format(calendar.getTime());

In R, how to find the standard error of the mean?

As I'm going back to this question every now and then and because this question is old, I'm posting a benchmark for the most voted answers.

Note, that for @Ian's and @John's answers I created another version. Instead of using length(x), I used sum(!is.na(x)) (to avoid NAs). I used a vector of 10^6, with 1,000 repetitions.

library(microbenchmark)

set.seed(123)
myVec <- rnorm(10^6)

IanStd <- function(x) sd(x)/sqrt(length(x))

JohnSe <- function(x) sqrt(var(x)/length(x))

IanStdisNA <- function(x) sd(x)/sqrt(sum(!is.na(x)))

JohnSeisNA <- function(x) sqrt(var(x)/sum(!is.na(x)))

AranStderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

mbm <- microbenchmark(
  "plotrix" = {plotrix::std.error(myVec)},
  "IanStd" = {IanStd(myVec)},
  "JohnSe" = {JohnSe(myVec)},
  "IanStdisNA" = {IanStdisNA(myVec)},
  "JohnSeisNA" = {JohnSeisNA(myVec)},
  "AranStderr" = {AranStderr(myVec)}, 
  times = 1000)

mbm

Results:

Unit: milliseconds
       expr     min       lq      mean   median       uq      max neval cld
    plotrix 10.3033 10.89360 13.869947 11.36050 15.89165 125.8733  1000   c
     IanStd  4.3132  4.41730  4.618690  4.47425  4.63185   8.4388  1000 a  
     JohnSe  4.3324  4.41875  4.640725  4.48330  4.64935   9.4435  1000 a  
 IanStdisNA  8.4976  8.99980 11.278352  9.34315 12.62075 120.8937  1000  b 
 JohnSeisNA  8.5138  8.96600 11.127796  9.35725 12.63630 118.4796  1000  b 
 AranStderr  4.3324  4.41995  4.634949  4.47440  4.62620  14.3511  1000 a  


library(ggplot2)
autoplot(mbm)

enter image description here

What is the default encoding of the JVM?

The default character set of the JVM is that of the system it's running on. There's no specific value for this and you shouldn't generally depend on the default encoding being any particular value.

It can be accessed at runtime via Charset.defaultCharset(), if that's any use to you, though really you should make a point of always specifying encoding explicitly when you can do so.

Word wrapping in phpstorm

For Word Wrapping in Php Storm 1. Select File from the menu 2. From File select setting 3. From setting select Editor 4. Select General from Editor 5. In general checked Use soft wraps in editor from Soft wraps section

Button inside of anchor link works in Firefox but not in Internet Explorer?

i found that this works for me

<input type="button" value="click me" onclick="window.open('http://someurl', 'targetname');">

Delete entire row if cell contains the string X

Try this ...

Dim r as Range
Dim x as Integer

For x = 5000 to 4 step -1 '---> or change as you want //Thanx 4 KazJaw

  set r = range("E" & format(x))
  if ucase(r.Value) = "NONE" then
    Rows(x).EntireRow.Delete
  end if 

Next

How to avoid "RuntimeError: dictionary changed size during iteration" error?

I would try to avoid inserting empty lists in the first place, but, would generally use:

d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty

If prior to 2.7:

d = dict( (k, v) for k,v in d.iteritems() if v )

or just:

empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
    del[k]

Recursion or Iteration?

it depends on "recursion depth". it depends on how much the function call overhead will influence the total execution time.

For example, calculating the classical factorial in a recursive way is very inefficient due to: - risk of data overflowing - risk of stack overflowing - function call overhead occupy 80% of execution time

while developing a min-max algorithm for position analysis in the game of chess that will analyze subsequent N moves can be implemented in recursion over the "analysis depth" (as I'm doing ^_^)

What is perm space?

  • JVM has an internal representation of Java objects and those internal representations are stored in the heap (in the young generation or the tenured generation).
  • JVM also has an internal representation of the Java classes and those are stored in the permanent generation

enter image description here

assignment operator overloading in c++

There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.

Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.

Determine what user created objects in SQL Server

If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":

enter image description here

You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.

Convert an ArrayList to an object array

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

Is it better to use path() or url() in urls.py for django 2.0?

From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows

from django.contrib import admin
from django.urls import path

from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^posts/$', post_home, name='post_home'),

]

where posts is an application & post_home is a function in views.py

What is the exact meaning of Git Bash?

I think the question asker is (was) thinking that git bash is a command like git init or git checkout. Git bash is not a command, it is an interface. I will also assume the asker is not a linux user because bash is very popular the unix/linux world. The name "bash" is an acronym for "Bourne Again SHell". Bash is a text-only command interface that has features which allow automated scripts to be run. A good analogy would be to compare bash to the new PowerShell interface in Windows7/8. A poor analogy (but one likely to be more readily understood by more people) is the combination of the command prompt and .BAT (batch) command files from the days of DOS and early versions of Windows.

REFERENCES:

Slide a layout up from bottom of screen

Use this layout. If you want to animate the main view shrinking you'll need to add animation to the height of the hidden bar, buy it may be good enough to use the translate animation on the bar, and have the main view height jump instead of animate.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<RelativeLayout
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/hello_world" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_world" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="slideUpDown"
        android:text="Slide up / down" />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/hidden_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="#fcc"
    android:visibility="visible" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />
</RelativeLayout>

</LinearLayout>

Convert DataTable to IEnumerable<T>

Nothing wrong with that implementation. You might give the yield keyword a shot, see how you like it:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
    {
        foreach (DataRow row in dataTable.Rows)
        {
            yield return new TankReading
                                  {
                                      TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                                      TankID = Convert.ToInt32(row["TankID"]),
                                      ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                                      ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                                      ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                                      MaterialNumber = row["MaterialNumber"].ToString(),
                                      EnteredBy = row["EnteredBy"].ToString(),
                                      ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                                      MaterialID = Convert.ToInt32(row["MaterialID"]),
                                      Submitted = Convert.ToBoolean(row["Submitted"]),
                                  };
        }

    }

Also the AsEnumerable isn't necessary, as List<T> is already an IEnumerable<T>

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

React Checkbox not sending onChange

If you have a handleChange function that looks like this:

handleChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value,
  });
}

You can create a custom onChange function so that it acts like an text input would:

<input
  type="checkbox"
  name="check"
  checked={this.state.check}
  onChange={(e) => {
    this.handleChange({
      target: {
        name: e.target.name,
        value: e.target.checked,
      },
    });
  }}
/>

How to get the size of a file in MB (Megabytes)?

You can use FileChannel in Java.

FileChannel has the size() method to determine the size of the file.

    String fileName = "D://words.txt";

    Path filePath = Paths.get(fileName);

    FileChannel fileChannel = FileChannel.open(filePath);
    long fileSize = fileChannel.size();

    System.out.format("The size of the file: %d bytes", fileSize);

Or you can determine the file size using Apache Commons' FileUtils' sizeOf() method. If you are using maven, add this to pom.xml file.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Try the following coding,

    String fileName = "D://words.txt";
    File f = new File(fileName);

    long fileSize = FileUtils.sizeOf(f);        

    System.out.format("The size of the file: %d bytes", fileSize);

These methods will output the size in Bytes. So to get the MB size, you need to divide the file size from (1024*1024).

Now you can simply use the if-else conditions since the size is captured in MB.

How to use Utilities.sleep() function

Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.

Seeking useful Eclipse Java code templates

Here's a foreach that will work for iterating over a List<Stuff>. The optional content inside the loop is for finding an element in the list and return it.

for (${t:elemType(w)} elem: ${w:collection}) {
    if (elem.get.equals(${localVar})){
        return elem;
    }
}
return null;

What does "select count(1) from table_name" on any database tables mean?

Difference between count(*) and count(1) in oracle?

count(*) means it will count all records i.e each and every cell BUT

count(1) means it will add one pseudo column with value 1 and returns count of all records

T-SQL How to select only Second row from a table?

I have a much easier way than the above ones.

DECLARE @FirstId int, @SecondId int

    SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId 
    SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId  ORDER BY TableId 

SELECT @SecondId 

callback to handle completion of pipe

Code snippet for piping content from web via http(s) to filesystem. As @starbeamrainbowlabs noticed event finish does job

var tmpFile = "/tmp/somefilename.doc";

var ws = fs.createWriteStream(tmpFile);
ws.on('finish', function() {
  // pipe done here, do something with file
});

var client = url.slice(0, 5) === 'https' ? https : http;
client.get(url, function(response) {
  return response.pipe(ws);
});

How to control the width and height of the default Alert Dialog in Android?

I dont know whether you can change the default height/width of AlertDialog but if you wanted to do this, I think you can do it by creating your own custom dialog. You just have to give android:theme="@android:style/Theme.Dialog" in the android manifest.xml for your activity and can write the whole layout as per your requirement. you can set the height and width of your custom dialog from the Android Resource XML.

Declaring array of objects

If you want all elements inside an array to be objects, you can use of JavaScript Proxy to apply a validation on objects before you insert them in an array. It's quite simple,

const arr = new Proxy(new Array(), {
  set(target, key, value) {
    if ((value !== null && typeof value === 'object') || key === 'length') {
      return Reflect.set(...arguments);
    } else {
      throw new Error('Only objects are allowed');
    }
  }
});

Now if you try to do something like this:

arr[0] = 'Hello World'; // Error

It will throw an error. However if you insert an object, it will be allowed:

arr[0] = {}; // Allowed

For more details on Proxies please refer to this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

If you are looking for a polyfill implementation you can checkout this link: https://github.com/GoogleChrome/proxy-polyfill

How to set height property for SPAN

Another option of course is to use Javascript (Jquery here):

$('.box1,.box2').each(function(){
    $(this).height($(this).parent().height());
})

Objective-C - Remove last character from string

In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:


if ([string length] > 0) {
    string = [string substringToIndex:[string length] - 1];
} else {
    //no characters to delete... attempting to do so will result in a crash
}






If you want a fancy way of doing this in just one line of code you could write it as:

string = [string substringToIndex:string.length-(string.length>0)];

*Explanation of fancy one-line code snippet:

If there is a character to delete (i.e. the length of the string is greater than 0)
     (string.length>0) returns 1 thus making the code return:
          string = [string substringToIndex:string.length-1];

If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
     (string.length>0) returns 0 thus making the code return:
          string = [string substringToIndex:string.length-0];
     Which prevents crashes.

How to convert an iterator to a stream?

Use Collections.list(iterator).stream()...

Using C++ filestreams (fstream), how can you determine the size of a file?

You can open the file using the ios::ate flag (and ios::binary flag), so the tellg() function will give you directly the file size:

ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();

Change onclick action with a Javascript function

For anyone, like me, trying to set a query string on the action and wondering why it's not working-

You cannot set a query string for a GET form submission, but I have found you can for a POST.

For a GET submission you must set the values in hidden inputs e.g.

an action of: "/handleformsubmission?foo=bar" would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />

This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:

var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);

See this question for more info submitting a GET form with query string params and hidden params disappear

jQuery Multiple ID selectors

Make sure upload plugin implements this.each in it so that it will execute the logic for all the matching elements. It should ideally work

$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });

iPad WebApp Full Screen in Safari

This site has a working workaround, same effect, uses some javascript to set the first child div to total height of viewport. http://webapp-net.com/Demo/Index.html

Remove all special characters with RegExp

The first solution does not work for any UTF-8 alphabet. (It will cut text such as ????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    }
    return res;
}

Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).

Laravel Mail::send() sending to multiple to or bcc addresses

If you want to send emails simultaneously to all the admins, you can do something like this:

In your .env file add all the emails as comma separated values:

[email protected],[email protected],[email protected]

so when you going to send the email just do this (yes! the 'to' method of message builder instance accepts an array):

So,

$to = explode(',', env('ADMIN_EMAILS'));

and...

$message->to($to);

will now send the mail to all the admins.

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

Extracting Nupkg files using command line

Rename it to .zip, then extract it.

How to wait until an element is present in Selenium?

public WebElement fluientWaitforElement(WebElement element, int timoutSec, int pollingSec) {

    FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS)
        .pollingEvery(pollingSec, TimeUnit.SECONDS)
        .ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class);

    for (int i = 0; i < 2; i++) {
        try {
            //fWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@id='reportmanager-wrapper']/div[1]/div[2]/ul/li/span[3]/i[@data-original--title='We are processing through trillions of data events, this insight may take more than 15 minutes to complete.']")));
        fWait.until(ExpectedConditions.visibilityOf(element));
        fWait.until(ExpectedConditions.elementToBeClickable(element));
        } catch (Exception e) {

        System.out.println("Element Not found trying again - " + element.toString().substring(70));
        e.printStackTrace();

        }
    }

    return element;

    }

Spring JPA and persistence.xml

I'm confused. You're injecting a PU into the service layer and not the persistence layer? I don't get that.

I inject the persistence layer into the service layer. The service layer contains business logic and demarcates transaction boundaries. It can include more than one DAO in a transaction.

I don't get the magic in your save() method either. How is the data saved?

In production I configure spring like this:

<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />

along with the reference in web.xml

For unit testing I do this:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
    p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
    p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
</bean>

Filter items which array contains any of given values

Edit: The bitset stuff below is maybe an interesting read, but the answer itself is a bit dated. Some of this functionality is changing around in 2.x. Also Slawek points out in another answer that the terms query is an easy way to DRY up the search in this case. Refactored at the end for current best practices. —nz

You'll probably want a Bool Query (or more likely Filter alongside another query), with a should clause.

The bool query has three main properties: must, should, and must_not. Each of these accepts another query, or array of queries. The clause names are fairly self-explanatory; in your case, the should clause may specify a list filters, a match against any one of which will return the document you're looking for.

From the docs:

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.

Here's an example of what that Bool query might look like in isolation:

{
  "bool": {
    "should": [
      { "term": { "tag": "c" }},
      { "term": { "tag": "d" }}
    ]
  }
}

And here's another example of that Bool query as a filter within a more general-purpose Filtered Query:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "bool": {
        "should": [
          { "term": { "tag": "c" }},
          { "term": { "tag": "d" }}
        ]
      }
    }
  }
}

Whether you use Bool as a query (e.g., to influence the score of matches), or as a filter (e.g., to reduce the hits that are then being scored or post-filtered) is subjective, depending on your requirements.

It is generally preferable to use Bool in favor of an Or Filter, unless you have a reason to use And/Or/Not (such reasons do exist). The Elasticsearch blog has more information about the different implementations of each, and good examples of when you might prefer Bool over And/Or/Not, and vice-versa.

Elasticsearch blog: All About Elasticsearch Filter Bitsets

Update with a refactored query...

Now, with all of that out of the way, the terms query is a DRYer version of all of the above. It does the right thing with respect to the type of query under the hood, it behaves the same as the bool + should using the minimum_should_match options, and overall is a bit more terse.

Here's that last query refactored a bit:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tag": [ "c", "d" ],
        "minimum_should_match": 1
      }
    }
  }
}

Git blame -- prior commits?

You can use git log -L to view the evolution of a range of lines.

For example :

git log -L 15,23:filename.txt

means "trace the evolution of lines 15 to 23 in the file named filename.txt".

DateDiff to output hours and minutes

Small change like this can be done

  SELECT  EmplID
        , EmplName
        , InTime
        , [TimeOut]
        , [DateVisited]
        , CASE WHEN minpart=0 
        THEN CAST(hourpart as nvarchar(200))+':00' 
        ELSE CAST((hourpart-1) as nvarchar(200))+':'+ CAST(minpart as nvarchar(200))END as 'total time'
        FROM 
        (
        SELECT   EmplID, EmplName, InTime, [TimeOut], [DateVisited],
        DATEDIFF(Hour,InTime, [TimeOut]) as hourpart, 
        DATEDIFF(minute,InTime, [TimeOut])%60 as minpart  
        from times) source

Change priorityQueue to max priorityqueue

You can try something like:

PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> -1 * Integer.compare(x, y));

Which works for any other base comparison function you might have.

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

How to set delay in android?

Try this code:

import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 5s = 5000ms
        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    }
}, 5000);

How to add icons to React Native app

Coming in a bit late here but Android Studio has a very handy icon asset wizard. Its very self explanatory but has a few handy effects and its built right in:

enter image description here

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

How do I prevent 'git diff' from using a pager?

You can add an alias to diff with its own pager with pager.alias, like so:

[alias]
  dc = diff
  dsc = diff --staged
[pager]
  dc = cat
  dsc = cat

This will keep the color on and use 'cat' as the pager when invoked at 'git dc'.

Also, things not to do:

  • use --no-pager in your alias. Git (1.8.5.2, Apple Git-48) will complain that you are trying to modify the environment.
  • use a shell with !sh or !git. This will bypass the environment error, above, but it will reset your working directory (for the purposes of this command) to the top-level Git directory, so any references to a local file will not work if you are already in a subdirectory of your repository.

How to randomize (or permute) a dataframe rowwise and columnwise?

Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations

Create a rounded button / button with border-radius in Flutter

Another cool solution that works in 2021

TextButton(
      child: Padding(
        padding: const EdgeInsets.all(5.0),
        child: Text('Follow Us'.toUpperCase()),
      ),
      style: TextButton.styleFrom(
      backgroundColor: Colors.amber,
      shadowColor: Colors.red,
      elevation: 2,
      textStyle: TextStyle(fontSize: 18,  fontWeight: FontWeight.bold),
      shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(5.0),)
    ),
    onPressed: () {
      print('Pressed');
    },
    ),

jQuery: load txt file and insert into div

You could use jQuery.load(): http://api.jquery.com/load/

Like this:

$(".text").load("helloworld.txt");

How to replace a character from a String in SQL?

This will replace all ? with ':

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
WHERE city LIKE '%?%'

If you need to update more than one column, you can either change city each time you execute to a different column name, or list the columns like so:

UPDATE dbo.authors    
SET    city = replace(city, '?', '''')
      ,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Try this:

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8,iso,utfBytes);
string msg = iso.GetString(isoBytes);

How to create id with AUTO_INCREMENT on Oracle?

Here are three flavors:

  1. numeric. Simple increasing numeric value, e.g. 1,2,3,....
  2. GUID. globally univeral identifier, as a RAW datatype.
  3. GUID (string). Same as above, but as a string which might be easier to handle in some languages.

x is the identity column. Substitute FOO with your table name in each of the examples.

-- numerical identity, e.g. 1,2,3...
create table FOO (
    x number primary key
);
create sequence  FOO_seq;

create or replace trigger FOO_trg
before insert on FOO
for each row
begin
  select FOO_seq.nextval into :new.x from dual;
end;
/

-- GUID identity, e.g. 7CFF0C304187716EE040488AA1F9749A
-- use the commented out lines if you prefer RAW over VARCHAR2.
create table FOO (
    x varchar(32) primary key        -- string version
    -- x raw(32) primary key         -- raw version
);

create or replace trigger FOO_trg
before insert on FOO
for each row
begin
  select cast(sys_guid() as varchar2(32)) into :new.x from dual;  -- string version
  -- select sys_guid() into :new.x from dual;                     -- raw version
end;
/

update:

Oracle 12c introduces these two variants that don't depend on triggers:

create table mytable(id number default mysequence.nextval);
create table mytable(id number generated as identity);

The first one uses a sequence in the traditional way; the second manages the value internally.

How to get annotations of a member variable?

If you need know if a annotation specific is present. You can do so:

    Field[] fieldList = obj.getClass().getDeclaredFields();

        boolean isAnnotationNotNull, isAnnotationSize, isAnnotationNotEmpty;

        for (Field field : fieldList) {

            //Return the boolean value
            isAnnotationNotNull = field.isAnnotationPresent(NotNull.class);
            isAnnotationSize = field.isAnnotationPresent(Size.class);
            isAnnotationNotEmpty = field.isAnnotationPresent(NotEmpty.class);

        }

And so on for the other annotations...

I hope help someone.

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

  1. String
  2. Varchar

This is my opinion for my database as recommended by my mentor

What is the difference between null and undefined in JavaScript?

The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.

From the Eloquent Javascript book

Difference between "on-heap" and "off-heap"

Not 100%; however, it sounds like the heap is an object or set of allocated space (on RAM) that is built into the functionality of the code either Java itself or more likely functionality from ehcache itself, and the off-heap Ram is there own system as well; however, it sounds like this is one magnitude slower as it is not as organized, meaning it may not use a heap (meaning one long set of space of ram), and instead uses different address spaces likely making it slightly less efficient.

Then of course the next tier lower is hard-drive space itself.

I don't use ehcache, so you may not want to trust me, but that what is what I gathered from their documentation.

Absolute positioning ignoring padding of parent

First, let's see why this is happening.

The reason is that, surprisingly, when a box has position: absolute its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.

Here is the relevant part of the CSS specification:

In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.

The simplest approach—as suggested in Winter's answer—is to use padding: inherit on the absolutely positioned div. It only works, though, if you don't want the absolutely positioned div to have any additional padding of its own. I think the most general-purpose solutions (in that both elements can have their own independent padding) are:

  1. Add an extra relatively positioned div (with no padding) around the absolutely positioned div. That new div will respect the padding of its parent, and the absolutely positioned div will then fill it.

    The downside, of course, is that you're messing with the HTML simply for presentational purposes.

  2. Repeat the padding (or add to it) on the absolutely positioned element.

    The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like SASS or LESS you can avoid that problem by using a variable. This is the method I personally use.

XSLT string replace

Here is the XSLT function which will work similar to the String.Replace() function of C#.

This template has the 3 Parameters as below

text :- your main string

replace :- the string which you want to replace

by :- the string which will reply by new string

Below are the Template

<xsl:template name="string-replace-all">
  <xsl:param name="text" />
  <xsl:param name="replace" />
  <xsl:param name="by" />
  <xsl:choose>
    <xsl:when test="contains($text, $replace)">
      <xsl:value-of select="substring-before($text,$replace)" />
      <xsl:value-of select="$by" />
      <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="substring-after($text,$replace)" />
        <xsl:with-param name="replace" select="$replace" />
        <xsl:with-param name="by" select="$by" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$text" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Below sample shows how to call it

<xsl:variable name="myVariable ">
  <xsl:call-template name="string-replace-all">
    <xsl:with-param name="text" select="'This is a {old} text'" />
    <xsl:with-param name="replace" select="'{old}'" />
    <xsl:with-param name="by" select="'New'" />
  </xsl:call-template>
</xsl:variable>

You can also refer the below URL for the details.

Is it necessary to use # for creating temp tables in SQL server?

The difference between this two tables ItemBack1 and #ItemBack1 is that the first on is persistent (permanent) where as the other is temporary.

Now if take a look at your question again

Is it necessary to Use # for creating temp table in sql server?

The answer is Yes, because without this preceding # the table will not be a temporary table, it will be independent of all sessions and scopes.

Detecting request type in PHP (GET, POST, PUT or DELETE)

I used this code. It should work.

function get_request_method() {
    $request_method = strtolower($_SERVER['REQUEST_METHOD']);

    if($request_method != 'get' && $request_method != 'post') {
        return $request_method;
    }

    if($request_method == 'post' && isset($_POST['_method'])) {
        return strtolower($_POST['_method']);
    }

    return $request_method;
}

This above code will work with REST calls and will also work with html form

<form method="post">
    <input name="_method" type="hidden" value="delete" />
    <input type="submit" value="Submit">
</form>

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

I had a similar issue when working on Database restore operation on MS SQL Server 2012.

However, for my own scenario, I just needed to see the progress of the DATABASE RESTORE operation in the script window

All I had to do was add the STATS option to the script:

USE master;
GO

ALTER DATABASE mydb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
    
RESTORE DATABASE mydb
    FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_21-08-2020.bak'
    WITH REPLACE,
         STATS = 10,
         RESTART,
    MOVE 'my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\my_db.mdf',
    MOVE 'my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\mydb_log.ldf'
GO
    
ALTER DATABASE mydb SET MULTI_USER;
GO

And then I switched to the Messages tab of the Script window to see the progress of the DATABASE RESTORE operation:

enter image description here

If you want to get more information after the DATABASE RESTORE operation you can use this command suggested by eythort:

SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command = 'RESTORE DATABASE'

That's all.

I hope this helps

How to play videos in android from assets folder or raw folder?

It sounds maybe like you have the same issue as i do. instead of using MP4, is 3GPP possible? i think i used like HandBrake or something as the video converter... you just need to make sure you have the right encoder, like H.264x or something. sorry for being a little vague, it's been a while. Also, if it's possible, don't bother worrying about android 2.1 anymore, and also, something things just WILL NOT WORK IN EMULATOR. so if it works on a lot of devices, then just assume it works (especially with different manufacurers)

here, you can read my problem and how i solved the issue (after a long time and no one had an answer). i explained in a lot more detail here: android media player not working

Tkinter: "Python may not be configured for Tk"

To get this to work with pyenv on Ubuntu 16.04 and 18.04, I had to:

$ sudo apt-get install python-tk python3-tk tk-dev

Then install the version of Python I wanted:

$ pyenv install 3.6.2

Then I could import tkinter just fine:

import tkinter

Get all child elements

Another veneration of find_elements_by_xpath(".//*") is:

from selenium.webdriver.common.by import By


find_elements(By.XPATH, ".//*")

How to loop and render elements in React.js without an array of objects to map?

I think this is the easiest way to loop in react js

<ul>
    {yourarray.map((item)=><li>{item}</li>)}
</ul>

Paging with Oracle

Ask Tom on pagination and very, very useful analytic functions.

This is excerpt from that page:

select * from (
    select /*+ first_rows(25) */
     object_id,object_name,
     row_number() over
    (order by object_id) rn
    from all_objects
)
where rn between :n and :m
order by rn;

How can I change the Bootstrap default font family using font from Google?

This is the best and easy way to import font from google and
this is also a standard method to import font

Paste this code on your index page or on header

<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>

other method is to import on css like this:

@import url(http://fonts.googleapis.com/css?family=Oswald:400,300,700);

on your Css file as this code

body {
  font-family: 'Oswald', sans-serif !important;
}

Note : The @import code line will be the first lines in your css file (style.css, etc.css). They can be used in any of the .css files and should always be the first line in these files. The following is an example:

Change a Git remote HEAD to point to something besides master

Simple just log into your GitHub account and on the far right side in the navigation menu choose Settings, in the Settings Tab choose Default Branch and return back to main page of your repository that did the trick for me.

Visual Studio Code - Convert spaces to tabs

There are 3 options in .vscode/settings.json:

// The number of spaces a tab is equal to.
"editor.tabSize": 4,

// Insert spaces when pressing Tab.
"editor.insertSpaces": true,

// When opening a file, `editor.tabSize` and `editor.insertSpaces` will be detected based on the file contents.
"editor.detectIndentation": true

editor.detectIndentation detects it from your file, you have to disable it. If it didn't help, check that you have no settings with higher priority. For example when you save it to User settings it could be overwritten by Workspace settings which are in your project folder.

Update:

You may just open File » Preferences » Settings or use shortcut:

CTRL+, (Windows, Linux)

?+, (Mac)

Update:

Now you have alternative to editing those options manually.
Click on selector Spaces:4 at the bottom-right of the editor:
 Ln44, Col .  [Spaces:4] . UTF-8 with BOM . CTRLF . HTML . :)

When you want to convert existing ws to tab, install extension from Marketplace
EDIT:
To convert existing indentation from spaces to tabs hit Ctrl+Shift+P and type:

>Convert indentation to Tabs

This will change the indentation for your document based on the defined settings to Tabs.

how to check if List<T> element contains an item with a Particular Property Value

This is pretty easy to do using LINQ:

var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
    // Element doesn't exist
}

Simulate a click on 'a' element using javascript/jquery

Using jQuery:

$('#gift-close').click();

Focusable EditText inside ListView

Another simple solution is to define your onClickListener, in the getView(..) method, of your ListAdapter.

public View getView(final int position, View convertView, ViewGroup parent){
    //initialise your view
    ...
    View row = context.getLayoutInflater().inflate(R.layout.list_item, null);
    ...

    //define your listener on inner items

    //define your global listener
    row.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            doSomethingWithViewAndPosition(v,position);
        }
    });

    return row;

That way your row are clickable, and your inner view too :)

How to set Highcharts chart maximum yAxis value

Try this:

yAxis: {min: 0, max: 100}

See this jsfiddle example

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

You can include a legend template in the chart options:

//legendTemplate takes a template as a string, you can populate the template with values from your dataset 
var options = {
  legendTemplate : '<ul>'
                  +'<% for (var i=0; i<datasets.length; i++) { %>'
                    +'<li>'
                    +'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
                    +'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
                  +'</li>'
                +'<% } %>'
              +'</ul>'
  }

  //don't forget to pass options in when creating new Chart
  var lineChart = new Chart(element).Line(data, options);

  //then you just need to generate the legend
  var legend = lineChart.generateLegend();

  //and append it to your page somewhere
  $('#chart').append(legend);

You'll also need to add some basic css to get it looking ok.

C: How to free nodes in the linked list?

struct node{
    int position;
    char name[30];
    struct node * next;
};

void free_list(node * list){
    node* next_node;

    printf("\n\n Freeing List: \n");
    while(list != NULL)
    {
        next_node = list->next;
        printf("clear mem for: %s",list->name);
        free(list);
        list = next_node;
        printf("->");
    }
}

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

It checks whether the page has been called through POST (as opposed to GET, HEAD, etc). When you type a URL in the menu bar, the page is called through GET. However, when you submit a form with method="post" the action page is called with POST.

Order columns through Bootstrap4

I'm using Bootstrap 3, so i don't know if there is an easier way to do it Bootstrap 4 but this css should work for you:

.pull-right-xs {
    float: right;
}

@media (min-width: 768px) {
   .pull-right-xs {
      float: left;
   }
}

...and add class to second column:

<div class="row">
    <div class="col-xs-3 col-md-6">
        1
    </div>
    <div class="col-xs-3 col-md-6 pull-right-xs">
        2
    </div>
    <div class="col-xs-6 col-md-12">
        3
    </div>
</div>

EDIT:

Ohh... it looks like what i was writen above is exacly a .pull-xs-right class in Bootstrap 4 :X Just add it to second column and it should work perfectly.

Server unable to read htaccess file, denying access to be safe

GoDaddy shared server solution

I had the same issue when trying to deploy separate Laravel project on a subdomain level.

File structure

- public_html (where the main web app resides)
    [works fine]

    - booking.mydomain.com (folder for separate Laravel project)
        [showing error 403 forbidden]

Solution

  1. go to cPanel of your GoDaddy account

  2. open File Manager

  3. browse to the folder that shows 403 forbidden error

  4. in the File Manager, right-click on the folder (in my case booking.mydomain.com)

  5. select Change Permissions

  6. select following checkboxes

     a) user - read, write, execute
     b) group - read, execute
     c) world - read, execute
    
     Permission code must display as 755
    
  7. Click change permissions

How can you undo the last git add?

You could use git reset (see docs)

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

How to plot a subset of a data frame in R?

Most straightforward option:

plot(var1[var3<155],var2[var3<155])

It does not look good because of code redundancy, but is ok for fastndirty hacking.

How to kill a while loop with a keystroke?

the following code works for me. It requires openCV (import cv2).

The code is composed of an infinite loop that is continuously looking for a key pressed. In this case, when the 'q' key is pressed, the program ends. Other keys can be pressed (in this example 'b' or 'k') to perform different actions such as change a variable value or execute a function.

import cv2

while True:
    k = cv2.waitKey(1) & 0xFF
    # press 'q' to exit
    if k == ord('q'):
        break
    elif k == ord('b'):
        # change a variable / do something ...
    elif k == ord('k'):
        # change a variable / do something ...

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Git - Ignore node_modules folder everywhere

Create .gitignore file in root folder directly by code editor or by command

For Mac & Linux

 touch .gitignore 

For Windows

 echo >.gitignore 

open .gitignore declare folder or file name like this /foldername

Select records from NOW() -1 Day

Be aware that the result may be slightly different than you expect.

NOW() returns a DATETIME.

And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.

So if your script is cron'd to run at 03:00, it will miss the first three hours of records from the 'oldest' day.

To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get back to the beginning of the previous day regardless of when the script is run.

Replace a value if null or undefined in JavaScript

Logical nullish assignment, 2020+ solution

A new operator has been added, ??=. This is equivalent to value = value ?? defaultValue.

||= and &&= are similar, links below.

This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

// Equivalent to
a = a ?? true

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Functional Example

function config(options) {
    options.duration ??= 100
    options.speed ??= 25
    return options
}

config({ duration: 555 })   // { duration: 555, speed: 25 }
config({})                  // { duration: 100, speed: 25 }
config({ duration: null })  // { duration: 100, speed: 25 }

??= Browser Support Nov 2020 - 77%

??= Mozilla Documentation

||= Mozilla Documentation

&&= Mozilla Documentation

Return list of items in list greater than some value

You can use a list comprehension to filter it:

j2 = [i for i in j if i >= 5]

If you actually want it sorted like your example was, you can use sorted:

j2 = sorted(i for i in j if i >= 5)

or call sort on the final list:

j2 = [i for i in j if i >= 5]
j2.sort()

jquery to change style attribute of a div class

$('.handle').css('left','300px') try this, identificator first then the value

more on this here:

http://api.jquery.com/css/

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

The increase-memory-limit module has been deprecated now. As of Node.js v8.0 shipped August 2017, we can now use the NODE_OPTIONS env variable to set the max_old_space_size globally.

export NODE_OPTIONS=--max_old_space_size=4096

Ref URL: https://github.com/endel/increase-memory-limit

How to get cumulative sum

Lets first create a table with dummy data -->

Create Table CUMULATIVESUM (id tinyint , SomeValue tinyint)

**Now let put some data in the table**

Insert Into CUMULATIVESUM

Select 1, 10 union 
Select 2, 2  union
Select 3, 6  union
Select 4, 10 

here I am joining same table (SELF Joining)

Select c1.ID, c1.SomeValue, c2.SomeValue
From CumulativeSum c1,  CumulativeSum c2
Where c1.id >= c2.ID
Order By c1.id Asc

RESULT :

ID  SomeValue   SomeValue
1   10          10
2   2           10
2   2            2
3   6           10
3   6            2
3   6            6
4   10          10
4   10           2
4   10           6
4   10          10

here we go now just sum the Somevalue of t2 and we`ll get the ans

Select c1.ID, c1.SomeValue, Sum(c2.SomeValue) CumulativeSumValue
From CumulativeSum c1,  CumulativeSum c2
Where c1.id >= c2.ID
Group By c1.ID, c1.SomeValue
Order By c1.id Asc

FOR SQL SERVER 2012 and above(Much better perform)

Select c1.ID, c1.SomeValue, 
SUM (SomeValue) OVER (ORDER BY c1.ID )
From CumulativeSum c1
Order By c1.id Asc

Desired Result

ID  SomeValue   CumlativeSumValue
1   10          10
2   2           12
3   6           18
4   10          28

Drop Table CumulativeSum

Clear the dummytable

How do I left align these Bootstrap form items?

Just add style="text-align: left" to your label.

How to leave/exit/deactivate a Python virtualenv

I defined an alias, workoff, as the opposite of workon:

alias workoff='deactivate'

It is easy to remember:

[bobstein@host ~]$ workon django_project
(django_project)[bobstein@host ~]$ workoff
[bobstein@host ~]$

Which is the preferred way to concatenate a string in Python?

The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast, which one you choose is a matter of taste, the latter one is the most common. Here are timings with the timeit module:

a = a + b:
0.11338996887207031
a += b:
0.11040496826171875

However, those who recommend having lists and appending to them and then joining those lists, do so because appending a string to a list is presumably very fast compared to extending a string. And this can be true, in some cases. Here, for example, is one million appends of a one-character string, first to a string, then to a list:

a += b:
0.10780501365661621
a.append(b):
0.1123361587524414

OK, turns out that even when the resulting string is a million characters long, appending was still faster.

Now let's try with appending a thousand character long string a hundred thousand times:

a += b:
0.41823482513427734
a.append(b):
0.010656118392944336

The end string, therefore, ends up being about 100MB long. That was pretty slow, appending to a list was much faster. That that timing doesn't include the final a.join(). So how long would that take?

a.join(a):
0.43739795684814453

Oups. Turns out even in this case, append/join is slower.

So where does this recommendation come from? Python 2?

a += b:
0.165287017822
a.append(b):
0.0132720470428
a.join(a):
0.114929914474

Well, append/join is marginally faster there if you are using extremely long strings (which you usually aren't, what would you have a string that's 100MB in memory?)

But the real clincher is Python 2.3. Where I won't even show you the timings, because it's so slow that it hasn't finished yet. These tests suddenly take minutes. Except for the append/join, which is just as fast as under later Pythons.

Yup. String concatenation was very slow in Python back in the stone age. But on 2.4 it isn't anymore (or at least Python 2.4.7), so the recommendation to use append/join became outdated in 2008, when Python 2.3 stopped being updated, and you should have stopped using it. :-)

(Update: Turns out when I did the testing more carefully that using + and += is faster for two strings on Python 2.3 as well. The recommendation to use ''.join() must be a misunderstanding)

However, this is CPython. Other implementations may have other concerns. And this is just yet another reason why premature optimization is the root of all evil. Don't use a technique that's supposed "faster" unless you first measure it.

Therefore the "best" version to do string concatenation is to use + or +=. And if that turns out to be slow for you, which is pretty unlikely, then do something else.

So why do I use a lot of append/join in my code? Because sometimes it's actually clearer. Especially when whatever you should concatenate together should be separated by spaces or commas or newlines.

How to store values from foreach loop into an array?

Try

$items = array_values ( $group_membership );

How to get scrollbar position with Javascript?

it's like this :)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

How do I wait until Task is finished in C#?

When working with continuations I find it useful to think of the place where I write .ContinueWith as the place from which execution immediately continues to the statements following it, not the statements 'inside' it. In that case it becomes clear that you would get an empty string returned in Send. If your only processing of the response is writing it to the console, you don't need any Wait in Ito's solution - the console printout will happen without waits but both Send and Print should return void in that case. Run this in console app and you will get printout of the page.

IMO, waits and Task.Result calls (which block) are necessary sometimes, depending on your desired flow of control, but more often they are a sign that you don't really use asynchronous functionality correctly.

namespace TaskTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Send();
            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }

        private static void Send()
        {
            HttpClient client = new HttpClient();
            Task<HttpResponseMessage> responseTask = client.GetAsync("http://google.com");
            responseTask.ContinueWith(x => Print(x));
        }

        private static void Print(Task<HttpResponseMessage> httpTask)
        {
            Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
            Task continuation = task.ContinueWith(t =>
            {
                Console.WriteLine("Result: " + t.Result);
            });
        }
    }
}

CSS - Expand float child DIV height to parent's height

I learned of this neat trick in an internship interview. The original question is how do you ensure the height of each top component in three columns have the same height that shows all the content available. Basically create a child component that is invisible that renders the maximum possible height.

<div class="parent">
    <div class="assert-height invisible">
        <!-- content -->
    </div>
    <div class="shown">
        <!-- content -->
    </div>
</div>

How do I count the number of occurrences of a char in a String?

public class OccurencesInString { public static void main(String[] args) { String str = "NARENDRA AMILINENI"; HashMap occur = new HashMap(); int count =0; String key = null; for(int i=0;i<str.length()-1;i++){ key = String.valueOf(str.charAt(i)); if(occur.containsKey(key)){ count = (Integer)occur.get(key); occur.put(key,++count); }else{ occur.put(key,1); } } System.out.println(occur); } }

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I ran into a similar problem with the same error message using following code:

@Html.DisplayFor(model => model.EndDate.Value.ToShortDateString())

I found a good answer here

Turns out you can decorate the property in your model with a displayformat then apply a dataformatstring.

Be sure to import the following lib into your model:

using System.ComponentModel.DataAnnotations;

How to get the last character of a string in a shell?

Per @perreal, quoting variables is important, but because I read this post like 5 times before finding a simpler approach to the question at hand in the comments...

str='abcd/'
echo "${str: -1}"

Output: /

str='abcd*'
echo "${str: -1}"

Output: *

Thanks to everyone who participated in this above; I've appropriately added +1's throughout the thread!

Runnable with a parameter?

theView.post(new Runnable() {
    String str;
    @Override                            
    public void run() {
        par.Log(str);                              
    }
    public Runnable init(String pstr) {
        this.str=pstr;
        return(this);
    }
}.init(str));

Create init function that returns object itself and initialize parameters with it.

Java Compare Two List's object values?

This can be done easily through Java8 using forEach and removeIf method.

Take two lists. Iterate from listA and compare elements inside listB

Write any condition inside removeIf method.

Hope this will help

listToCompareFrom.forEach(entity -> listToRemoveFrom.removeIf(x -> x.contains(entity)));

Declaring variables inside or outside of a loop

According to Google Android Development guide, the variable scope should be limited. Please check this link:

Limit Variable Scope

jQuery won't parse my JSON from AJAX query

If jQuery's error handler is being called and the XHR object contains "parser error", that's probably a parser error coming back from the server.

Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record?

What backend are you returning this from?

On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its "data" parameter, it will serialize that into standard & delimited k,v pairs instead of sending it as JSON.

Show space, tab, CRLF characters in editor of Visual Studio

The correct shortcut is CTRL-R-W like you don't have to release CTRL button while pressing W. This worked for me in VS 2015

Check if date is in the past Javascript

_x000D_
_x000D_
$('#datepicker').datepicker().change(evt => {_x000D_
  var selectedDate = $('#datepicker').datepicker('getDate');_x000D_
  var now = new Date();_x000D_
  now.setHours(0,0,0,0);_x000D_
  if (selectedDate < now) {_x000D_
    console.log("Selected date is in the past");_x000D_
  } else {_x000D_
    console.log("Selected date is NOT in the past");_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<input type="text" id="datepicker" name="event_date" class="datepicker">
_x000D_
_x000D_
_x000D_

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

How to comment lines in rails html.erb files?

ruby on rails notes has a very nice blogpost about commenting in erb-files

the short version is

to comment a single line use

<%# commented line %>

to comment a whole block use a if false to surrond your code like this

<% if false %>
code to comment
<% end %>

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

Converting string to number in javascript/jQuery

It sounds like this is referring to something else than you think. In what context are you using it?

The this keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.

If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info class, you could do something like:

parseInt($(".btn-info").data('votevalue'), 10);

You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

A little bit late to the party... but I found this as a solution for me when having "blocked"-Error in chrome:

Blocking resources whose URLs contain both \n and < characters.

More info here: https://www.chromestatus.com/feature/5735596811091968

How to Add a Dotted Underline Beneath HTML Text

Without CSS, you basically are stuck with using an image tag. Basically make an image of the text and add the underline. That basically means your page is useless to a screen reader.

With CSS, it is simple.

HTML:

<u class="dotted">I like cheese</u>

CSS:

u.dotted{
  border-bottom: 1px dashed #999;
  text-decoration: none; 
}

Running Example

Example page

<!DOCTYPE HTML>
<html>
<head>
    <style>
        u.dotted{
          border-bottom: 1px dashed #999;
          text-decoration: none; 
        }
    </style>
</head>
<body>
    <u class="dotted">I like cheese</u>
</body>
</html>

How to serve an image using nodejs

Vanilla node version as requested:

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

http.createServer(function(req, res) {
  // parse url
  var request = url.parse(req.url, true);
  var action = request.pathname;
  // disallow non get requests
  if (req.method !== 'GET') {
    res.writeHead(405, {'Content-Type': 'text/plain' });
    res.end('405 Method Not Allowed');
    return;
  }
  // routes
  if (action === '/') {
    res.writeHead(200, {'Content-Type': 'text/plain' });
    res.end('Hello World \n');
    return;
  }
  // static (note not safe, use a module for anything serious)
  var filePath = path.join(__dirname, action).split('%20').join(' ');
  fs.exists(filePath, function (exists) {
    if (!exists) {
       // 404 missing files
       res.writeHead(404, {'Content-Type': 'text/plain' });
       res.end('404 Not Found');
       return;
    }
    // set the content type
    var ext = path.extname(action);
    var contentType = 'text/plain';
    if (ext === '.gif') {
       contentType = 'image/gif'
    }
    res.writeHead(200, {'Content-Type': contentType });
    // stream the file
    fs.createReadStream(filePath, 'utf-8').pipe(res);
  });
}).listen(8080, '127.0.0.1');

Data binding to SelectedItem in a WPF Treeview

I came across this page looking for the same answer as the original author, and proving there's always more than one way to do it, the solution for me was even easier than the answers provided here so far, so I figured I might as well add to the pile.

The motivation for the binding is to keep it nice & MVVM. The probable usage of the ViewModel is to have a property w/ a name such as "CurrentThingy", and somewhere else, the DataContext on some other thing is bound to "CurrentThingy".

Rather than going through additional steps required (eg: custom behavior, 3rd party control) to support a nice binding from the TreeView to my Model, and then from something else to my Model, my solution was to use simple Element binding the other thing to TreeView.SelectedItem, rather than binding the other thing to my ViewModel, thereby skipping the extra work required.

XAML:

<TreeView x:Name="myTreeView" ItemsSource="{Binding MyThingyCollection}">
.... stuff
</TreeView>

<!-- then.. somewhere else where I want to see the currently selected TreeView item: -->

<local:MyThingyDetailsView 
       DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}" />

Of course, this is great for reading the currently selected item, but not setting it, which is all I needed.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity

Capturing Groups From a Grep RegEx

If you're using Bash, you don't even have to use grep:

files="*.jpg"
regex="[0-9]+_([a-z]+)_[0-9a-z]*"
for f in $files    # unquoted in order to allow the glob to expand
do
    if [[ $f =~ $regex ]]
    then
        name="${BASH_REMATCH[1]}"
        echo "${name}.jpg"    # concatenate strings
        name="${name}.jpg"    # same thing stored in a variable
    else
        echo "$f doesn't match" >&2 # this could get noisy if there are a lot of non-matching files
    fi
done

It's better to put the regex in a variable. Some patterns won't work if included literally.

This uses =~ which is Bash's regex match operator. The results of the match are saved to an array called $BASH_REMATCH. The first capture group is stored in index 1, the second (if any) in index 2, etc. Index zero is the full match.

You should be aware that without anchors, this regex (and the one using grep) will match any of the following examples and more, which may not be what you're looking for:

123_abc_d4e5
xyz123_abc_d4e5
123_abc_d4e5.xyz
xyz123_abc_d4e5.xyz

To eliminate the second and fourth examples, make your regex like this:

^[0-9]+_([a-z]+)_[0-9a-z]*

which says the string must start with one or more digits. The carat represents the beginning of the string. If you add a dollar sign at the end of the regex, like this:

^[0-9]+_([a-z]+)_[0-9a-z]*$

then the third example will also be eliminated since the dot is not among the characters in the regex and the dollar sign represents the end of the string. Note that the fourth example fails this match as well.

If you have GNU grep (around 2.5 or later, I think, when the \K operator was added):

name=$(echo "$f" | grep -Po '(?i)[0-9]+_\K[a-z]+(?=_[0-9a-z]*)').jpg

The \K operator (variable-length look-behind) causes the preceding pattern to match, but doesn't include the match in the result. The fixed-length equivalent is (?<=) - the pattern would be included before the closing parenthesis. You must use \K if quantifiers may match strings of different lengths (e.g. +, *, {2,4}).

The (?=) operator matches fixed or variable-length patterns and is called "look-ahead". It also does not include the matched string in the result.

In order to make the match case-insensitive, the (?i) operator is used. It affects the patterns that follow it so its position is significant.

The regex might need to be adjusted depending on whether there are other characters in the filename. You'll note that in this case, I show an example of concatenating a string at the same time that the substring is captured.

Mockito: Inject real objects into private @Autowired fields

Use @Spy annotation

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Spy
    private SomeService service = new RealServiceImpl();

    @InjectMocks
    private Demo demo;

    /* ... */
}

Mockito will consider all fields having @Mock or @Spy annotation as potential candidates to be injected into the instance annotated with @InjectMocks annotation. In the above case 'RealServiceImpl' instance will get injected into the 'demo'

For more details refer

Mockito-home

@Spy

@Mock

Using Python 3 in virtualenv

virtualenv --python=/usr/local/bin/python3 <VIRTUAL ENV NAME> this will add python3 path for your virtual enviroment.

adb shell command to make Android package uninstall dialog appear

I assume that you enable developer mode on your android device and you are connected to your device and you have shell access (adb shell).

Once this is done you can uninstall application with this command pm uninstall --user 0 <package.name>. 0 is root id -this way you don't need too root your device.

Here is an example how I did on my Huawei P110 lite

# gain shell access
$ adb shell

# check who you are
$ whoami
shell

# obtain user id
$ id
uid=2000(shell) gid=2000(shell)

# list packages
$ pm list packages | grep google                                                                                                                                                         
package:com.google.android.youtube
package:com.google.android.ext.services
package:com.google.android.googlequicksearchbox
package:com.google.android.onetimeinitializer
package:com.google.android.ext.shared
package:com.google.android.apps.docs.editors.sheets
package:com.google.android.configupdater
package:com.google.android.marvin.talkback
package:com.google.android.apps.tachyon
package:com.google.android.instantapps.supervisor
package:com.google.android.setupwizard
package:com.google.android.music
package:com.google.android.apps.docs
package:com.google.android.apps.maps
package:com.google.android.webview
package:com.google.android.syncadapters.contacts
package:com.google.android.packageinstaller
package:com.google.android.gm
package:com.google.android.gms
package:com.google.android.gsf
package:com.google.android.tts
package:com.google.android.partnersetup
package:com.google.android.videos
package:com.google.android.feedback
package:com.google.android.printservice.recommendation
package:com.google.android.apps.photos
package:com.google.android.syncadapters.calendar
package:com.google.android.gsf.login
package:com.google.android.backuptransport
package:com.google.android.inputmethod.latin

# uninstall gmail app
pm uninstall --user 0 com.google.android.gms

Is there a difference between "==" and "is"?

https://docs.python.org/library/stdtypes.html#comparisons

is tests for identity == tests for equality

Each (small) integer value is mapped to a single value, so every 3 is identical and equal. This is an implementation detail, not part of the language spec though

Alter a SQL server function to accept new optional parameter

The way to keep SELECT dbo.fCalculateEstimateDate(647) call working is:

ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100)  AS
   Declare @Result varchar(100)
   SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
   Return @Result
Begin
End

CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100)  AS
Begin
  <Function Body>
End

Where to find extensions installed folder for Google Chrome on Mac?

You can find all Chrome extensions in below location.

/Users/{mac_user}/Library/Application Support/Google/Chrome/Default/Extensions

Injection of autowired dependencies failed;

Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object

 @Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.

for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below

System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();

How can I use a search engine to search for special characters?

duckduckgo.com doesn't ignore special characters, at least if the whole string is between ""

https://duckduckgo.com/?q=%22*222%23%22

How to pass multiple arguments in processStartInfo?

Remember to include System.Diagnostics

ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe");        // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder

//here you add your arguments
startInfo.ArgumentList.Add("arg0");       // First argument          
startInfo.ArgumentList.Add("arg2");       // second argument
startInfo.ArgumentList.Add("arg3");       // third argument
Process.Start(startInfo);                 

#1071 - Specified key was too long; max key length is 1000 bytes

As @Devart says, the total length of your index is too long.

The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.

The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.

You can declare a prefix length per column as you define the index. For example:

...
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
...

But what's the best prefix length for a given column? Here's a method to find out:

SELECT
 ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
 ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
 ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
 ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;

It tells you the proportion of rows that have no more than a given string length in the menu_link column. You might see output like this:

+---------------+---------------+---------------+----------------+
| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
+---------------+---------------+---------------+----------------+
|         21.78 |         80.20 |        100.00 |         100.00 |
+---------------+---------------+---------------+----------------+

This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.

PS: The INT(1) and INT(32) data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL option.

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

How can I submit a form using JavaScript?

HTML

<!-- change id attribute to name  -->

<form method="post" action="yourUrl" name="theForm">
    <button onclick="placeOrder()">Place Order</button>
</form>

JavaScript

function placeOrder () {
    document.theForm.submit()
}

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

Bro, I had the same problem. Thing is I built a query builder, quite an complex one that build his predicates dynamically pending on what parameters had been set and cached the queries. Anyways, before I built my query builder, I had a non object oriented procedural code build the same thing (except of course he didn't cache queries and use parameters) that worked flawless. Now when my builder tried to do the very same thing, my PostgreSQL threw this fucked up error that you received too. I examined my generated SQL code and found no errors. Strange indeed.

My search soon proved that it was one particular predicate in the WHERE clause that caused this error. Yet this predicate was built by code that looked like, well almost, exactly as how the procedural code looked like before this exception started to appear out of nowhere.

But I saw one thing I had done differently in my builder as opposed to what the procedural code did previously. It was the order of the predicates he put in the WHERE clause! So I started to move this predicate around and soon discovered that indeed the order of predicates had much to say. If I had this predicate all alone, my query worked (but returned an erroneous result-match of course), if I put him with just one or the other predicate it worked sometimes, didn't work other times. Moreover, mimicking the previous order of the procedural code didn't work either. What finally worked was to put this demonic predicate at the start of my WHERE clause, as the first predicate added! So again if I haven't made myself clear, the order my predicates where added to the WHERE method/clause was creating this exception.

Double precision floating values in Python?

Python's built-in float type has double precision (it's a C double in CPython, a Java double in Jython). If you need more precision, get NumPy and use its numpy.float128.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

The easiest answer is to just use the cors package.

const cors = require('cors');

const app = require('express')();
app.use(cors());

That will enable CORS across the board. If you want to learn how to enable CORS without outside modules, all you really need is some Express middleware that sets the 'Access-Control-Allow-Origin' header. That's the minimum you need to allow cross-request domains from a browser to your server.

app.options('*', (req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
  res.send('ok');
});

app.use((req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
});

How to set label size in Bootstrap

You'll have to do 2 things to make a Bootstrap label (or anything really) adjust sizes based on screen size:

  • Use a media query per display size range to adjust the CSS.
  • Override CSS sizing set by Bootstrap. You do this by making your CSS rules more specific than Bootstrap's. By default, Bootstrap sets .label { font-size: 75% }. So any extra selector on your CSS rule will make it more specific.

Here's an example CSS listing to accomplish what you are asking, using the default 4 sizes in Bootstrap:

@media (max-width: 767) {
    /* your custom css class on a parent will increase specificity */
    /* so this rule will override Bootstrap's font size setting */
    .autosized .label { font-size: 14px; }
}

@media (min-width: 768px) and (max-width: 991px) {
    .autosized .label { font-size: 16px; }
}

@media (min-width: 992px) and (max-width: 1199px) {
    .autosized .label { font-size: 18px; }
}

@media (min-width: 1200px) {
    .autosized .label { font-size: 20px; }
}

Here is how it could be used in the HTML:

<!-- any ancestor could be set to autosized -->
<div class="autosized">
    ...
        ...
            <span class="label label-primary">Label 1</span>
</div>

Print "hello world" every X seconds

public class HelloWorld extends TimerTask{

    public void run() {

        System.out.println("Hello World");
    }
}


public class PrintHelloWorld {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new HelloWorld(), 0, 5000);

        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException Exception" + e.getMessage());
            }
        }
    }
}

infinite loop is created ad scheduler task is configured.

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

If you read this POST in 2016, please achieve what you want by using

--only={prod[uction]|dev[elopment]} 

argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV.

from: https://docs.npmjs.com/cli/install

Split string and get first value only

These are the two options I managed to build, not having the luxury of working with var type, nor with additional variables on the line:

string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);

This is what it gets:

enter image description here

Select only rows if its value in a particular column is less than the value in the other column

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

How to catch a specific SqlException error?

For those of you rookies out there who may throw a SQL error when connecting to the DB from another machine(For example, at form load), you will find that when you first setup a datatable in C# which points to a SQL server database that it will setup a connection like this:

this.Table_nameTableAdapter.Fill(this.DatabaseNameDataSet.Table_name);

You may need to remove this line and replace it with something else like a traditional connection string as mentioned on MSDN, etc.

http://www.connectionstrings.com/sql-server-2008

Add floating point value to android resources/values

There is a solution:

<resources>
    <item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>

In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:

Format = enclosing data type:

  • float
  • boolean
  • fraction
  • integer
  • ...

and type stands for:

Type = resource type (referenced with R.XXXXX.name):

  • color
  • dimen
  • string
  • style
  • etc...

To fetch resource from code, you should use this snippet:

TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();  

I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)), but Android dimensions have special treatment and pure "float" number is not valid dimension.


Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.

<resources>
    <dimen name="text_line_spacing">2.025px</dimen>
</resources>

and from code, you can get that float by

float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);

in this case, value of lineSpacing is 2.024993896484375, and not 2.025 as you would expected.

How do I properly escape quotes inside HTML attributes?

If you are using Javascript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.

See here: https://lodash.com/docs/#escape

How does one add keyboard languages and switch between them in Linux Mint 16?

Mint 18.2 (Cinnamon)
Menu > Keyboard Preferences > Layouts > Options > Switching to another layout:

Menu > Keyboard Preferences > Layouts > Options > Switching to another layout

View JSON file in Browser

If there is a Content-Disposition: attachment reponse header, Firefox will ask you to save the file, even if you have JSONView installed to format JSON.

To bypass this problem, I removed the header ("Content-Disposition" : null) with moz-rewrite Firefox addon that allows you to modify request and response headers https://addons.mozilla.org/en-US/firefox/addon/moz-rewrite-js/

An example of JSON file served with this header is the Twitter API (it looks like they added it recently). If you want to try this JSON file, I have a script to access Twitter API in browser: https://gist.github.com/baptx/ffb268758cd4731784e3

How to set a header for a HTTP GET request, and trigger file download?

There are two ways to download a file where the HTTP request requires that a header be set.

The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.

The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.

The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.

Solution:

        var id = 123;

        var req = ic.ajax.raw({
            type: 'GET',
            url: '/api/dowloads/'+id,
            beforeSend: function (request) {
                request.setRequestHeader('token', 'token for '+id);
            },
            processData: false
        });

        var maxSizeForBase64 = 1048576; //1024 * 1024

        req.then(
            function resolve(result) {
                var str = result.response;

                var anchor = $('.vcard-hyperlink');
                var windowUrl = window.URL || window.webkitURL;
                if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
                    var blob = new Blob([result.response], { type: 'text/bin' });
                    var url = windowUrl.createObjectURL(blob);
                    anchor.prop('href', url);
                    anchor.prop('download', id+'.bin');
                    anchor.get(0).click();
                    windowUrl.revokeObjectURL(url);
                }
                else {
                    //use base64 encoding when less than set limit or file API is not available
                    anchor.attr({
                        href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
                        download: id+'.bin',
                    });
                    anchor.get(0).click();
                }

            }.bind(this),
            function reject(err) {
                console.log(err);
            }
        );

Note that I'm not using a raw XMLHttpRequest, and instead using ic-ajax, and should be quite similar to a jQuery.ajax solution.

Note also that you should substitute text/bin and .bin with whatever corresponds to the file type being downloaded.

The implementation of FormatUtils.utf8toBase64 can be found here

Vertically align text within a div

To make Omar's (or Mahendra's) solution even more universal, the block of code relative to Firefox should be replaced by the following:

/* Firefox */
display: flex;
justify-content: center;
align-items: center;

The problem with Omar's code, otherwise operative, arises when you want to center the box in the screen or in its immediate ancestor. This centering is done either by setting its position to

position: relative; or position:static; (not with position:absolute nor fixed).

And then margin: auto; or margin-right: auto; margin-left: auto;

Under this box center aligning environment, Omar's suggestion does not work. It doesn't work either in Internet Explorer 8 (yet 7.7% market share). So for Internet Explorer 8 (and other browsers), a workaround as seen in other above solutions should be considered.

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

When should I create a destructor?

I have used a destructor (for debug purposes only) to see if an object was being purged from memory in the scope of a WPF application. I was unsure if garbage collection was truly purging the object from memory, and this was a good way to verify.

Best ways to teach a beginner to program?

This is a fantastic book which my little brothers used to learn:

http://pine.fm/LearnToProgram/

Of course, the most important thing is to start on a real, useful program of some kind IMMEDIATELY after finishing the book.

Using a Python subprocess call to invoke a Python script

Check out this.

from subprocess import call 
with open('directory_of_logfile/logfile.txt', 'w') as f:
   call(['python', 'directory_of_called_python_file/called_python_file.py'], stdout=f)

How do you get a string from a MemoryStream?

byte[] array = Encoding.ASCII.GetBytes("MyTest1 - MyTest2");
MemoryStream streamItem = new MemoryStream(array);

// convert to string
StreamReader reader = new StreamReader(streamItem);
string text = reader.ReadToEnd();

CodeIgniter activerecord, retrieve last insert id?

List of details which helps in requesting id and queries are

For fetching Last inserted Id :This will fetching the last records from the table

$this->db->insert_id(); 

Fetching SQL query add this after modal request

$this->db->last_query()

View a file in a different Git branch without changing branches

A simple, newbie friendly way for looking into a file: git gui browser <branch> which lets you explore the contents of any file.

It's also there in the File menu of git gui. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.

How to handle windows file upload using Selenium WebDriver?

Below code works for me :

public void test() {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.freepdfconvert.com/pdf-word");
    driver.findElement(By.id("clientUpload")).click();
    driver.switchTo()
            .activeElement()
            .sendKeys(
                    "/home/likewise-open/GLOBAL/123/Documents/filename.txt");
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    driver.findElement(By.id("convertButton"));

How to use Google fonts in React.js?

Another option to all of the good answers here is the npm package react-google-font-loader, found here.

The usage is simple:

import GoogleFontLoader from 'react-google-font-loader';

// Somewhere in your React tree:

<GoogleFontLoader
    fonts={[
        {
            font: 'Bungee Inline',
            weights: [400],
        },
    ]}
/>

Then you can just use the family name in your CSS:

body {
    font-family: 'Bungee Inline', cursive;
}

Disclaimer: I'm the author of the react-google-font-loader package.

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

Get device token for push notification

Swift 4 This works for me:

Step 1 into TARGETS Click on add capability and select Push Notifications

Step 2 in AppDelegate.swift add the following code:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) { (didAllow, error) in
            
        }
        UIApplication.shared.registerForRemoteNotifications()
        
        return true
    }
    
    //Get device token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        
        print("The token: \(tokenString)")
    }

Writing to a TextBox from another thread?

Most simple, without caring about delegates

if(textBox1.InvokeRequired == true)
    textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});

else
    textBox1.Text = "Invoke was NOT needed"; 

How to determine whether a Pandas Column contains a particular value

You can also use pandas.Series.isin although it's a little bit longer than 'a' in s.values:

In [2]: s = pd.Series(list('abc'))

In [3]: s
Out[3]: 
0    a
1    b
2    c
dtype: object

In [3]: s.isin(['a'])
Out[3]: 
0    True
1    False
2    False
dtype: bool

In [4]: s[s.isin(['a'])].empty
Out[4]: False

In [5]: s[s.isin(['z'])].empty
Out[5]: True

But this approach can be more flexible if you need to match multiple values at once for a DataFrame (see DataFrame.isin)

>>> df = DataFrame({'A': [1, 2, 3], 'B': [1, 4, 7]})
>>> df.isin({'A': [1, 3], 'B': [4, 7, 12]})
       A      B
0   True  False  # Note that B didn't match 1 here.
1  False   True
2   True   True

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Multi-Column Join in Hibernate/JPA Annotations

Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:

Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)

So if you are unwilling to make AnEmbeddableObject the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.

Create a button programmatically and set a background image

Try below:

let image = UIImage(named: "ImageName.png") as UIImage
var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button .setBackgroundImage(image, forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents:UIControlEvents.TouchUpInside)
menuView.addSubview(button)

Let me know whether if it works or not?

How to change collation of database, table, column?

I've just written a bash script to find all tables in a given database and covert them (and its columns).

Script is available here: https://github.com/Juddling/mysql-charset

Angularjs - simple form submit

Sending data to some service page.

<form class="form-horizontal" role="form" ng-submit="submit_form()">
    <input type="text" name="user_id" ng-model = "formAdata.user_id">
    <input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>

$scope.submit_form = function()
            {
                $http({
                        url: "http://localhost/services/test.php",
                        method: "POST",
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        data: $.param($scope.formAdata)
                    }).success(function(data, status, headers, config) {
                        $scope.status = status;
                    }).error(function(data, status, headers, config) {
                        $scope.status = status;
                    });
            }