Programs & Examples On #No data

How to show an empty view with a RecyclerView?

RVEmptyObserver

Instead of using a custom RecyclerView, extending an AdapterDataObserver is a simpler solution that allows setting a custom View that is displayed when there are no items in the list:

Example Usage:

RVEmptyObserver observer = new RVEmptyObserver(recyclerView, emptyView)
rvAdapter.registerAdapterDataObserver(observer);

Class:

public class RVEmptyObserver extends RecyclerView.AdapterDataObserver {
    private View emptyView;
    private RecyclerView recyclerView;

    public RVEmptyObserver(RecyclerView rv, View ev) {
        this.recyclerView = rv;
        this.emptyView    = ev;
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (emptyView != null && recyclerView.getAdapter() != null) {
            boolean emptyViewVisible = recyclerView.getAdapter().getItemCount() == 0;
            emptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE);
            recyclerView.setVisibility(emptyViewVisible ? View.GONE : View.VISIBLE);
        }
    }

    public void onChanged() { checkIfEmpty(); }
    public void onItemRangeInserted(int positionStart, int itemCount) { checkIfEmpty(); }
    public void onItemRangeRemoved(int positionStart, int itemCount) { checkIfEmpty(); }
}

Oracle - How to create a materialized view with FAST REFRESH and JOINS

You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Jquery insert new row into table at a certain index

Note:

$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody

$("table#myTable tr").last().after(newRow);  // this will add new row outside tbody 
                                             //i.e. between thead and tbody
                                             //.before() will also work similar

How do I remove accents from characters in a PHP string?

What about the WordPress implementation?

function remove_accents($string) {
    if ( !preg_match('/[\x80-\xff]/', $string) )
        return $string;

    $chars = array(
    // Decompositions for Latin-1 Supplement
    chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
    chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
    chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
    chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
    chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
    chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
    chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
    chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
    chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
    chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
    chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
    chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
    chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
    chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
    chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
    chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
    chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
    chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
    chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
    chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
    chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
    chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
    chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
    chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
    chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
    chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
    chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
    chr(195).chr(191) => 'y',
    // Decompositions for Latin Extended-A
    chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
    chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
    chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
    chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
    chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
    chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
    chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
    chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
    chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
    chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
    chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
    chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
    chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
    chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
    chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
    chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
    chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
    chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
    chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
    chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
    chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
    chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
    chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
    chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
    chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
    chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
    chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
    chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
    chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
    chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
    chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
    chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
    chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
    chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
    chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
    chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
    chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
    chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
    chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
    chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
    chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
    chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
    chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
    chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
    chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
    chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
    chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
    chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
    chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
    chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
    chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
    chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
    chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
    chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
    chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
    chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
    chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
    chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
    chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
    chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
    chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
    chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
    chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
    chr(197).chr(190) => 'z', chr(197).chr(191) => 's'
    );

    $string = strtr($string, $chars);

    return $string;
}

To understand what this function does, check the conversion table:

À => A
Á => A
 => A
à => A
Ä => A
Å => A
Ç => C
È => E
É => E
Ê => E
Ë => E
Ì => I
Í => I
Î => I
Ï => I
Ñ => N
Ò => O
Ó => O
Ô => O
Õ => O
Ö => O
Ù => U
Ú => U
Û => U
Ü => U
Ý => Y
ß => s
à => a
á => a
â => a
ã => a
ä => a
å => a
ç => c
è => e
é => e
ê => e
ë => e
ì => i
í => i
î => i
ï => i
ñ => n
ò => o
ó => o
ô => o
õ => o
ö => o
ù => u
ú => u
û => u
ü => u
ý => y
ÿ => y
A => A
a => a
A => A
a => a
A => A
a => a
C => C
c => c
C => C
c => c
C => C
c => c
C => C
c => c
D => D
d => d
Ð => D
d => d
E => E
e => e
E => E
e => e
E => E
e => e
E => E
e => e
E => E
e => e
G => G
g => g
G => G
g => g
G => G
g => g
G => G
g => g
H => H
h => h
H => H
h => h
I => I
i => i
I => I
i => i
I => I
i => i
I => I
i => i
I => I
i => i
? => IJ
? => ij
J => J
j => j
K => K
k => k
? => k
L => L
l => l
L => L
l => l
L => L
l => l
? => L
? => l
L => L
l => l
N => N
n => n
N => N
n => n
N => N
n => n
? => N
? => n
? => N
O => O
o => o
O => O
o => o
O => O
o => o
Π=> OE
œ => oe
R => R
r => r
R => R
r => r
R => R
r => r
S => S
s => s
S => S
s => s
S => S
s => s
Š => S
š => s
T => T
t => t
T => T
t => t
T => T
t => t
U => U
u => u
U => U
u => u
U => U
u => u
U => U
u => u
U => U
u => u
U => U
u => u
W => W
w => w
Y => Y
y => y
Ÿ => Y
Z => Z
z => z
Z => Z
z => z
Ž => Z
ž => z
? => s

You can generate the conversion table yourself by simply iterating over the $chars array of the function:

foreach($chars as $k=>$v) {
   printf("%s -> %s", $k, $v);
}

Connect to network drive with user name and password

var fileName = "Mylogs.log";
var local = Path.Combine(@"C:\TempLogs", fileName);
var remote = Path.Combine(@"\\servername\c$\Windows\Temp\", fileName);

WebClient request = new WebClient();
request.Credentials = new NetworkCredential(@"username", "password");

if (File.Exists(local))
{
    File.Delete(local);

    File.Copy(remote, local, true);
}
else
{
    File.Copy(remote, local, true);
}

WHERE clause on SQL Server "Text" data type

This works in MSSQL and MySQL:

SELECT *
FROM   Village
WHERE  CastleType LIKE '%foo%'; 

How to connect to Oracle 11g database remotely

I install the Oracle server and it allows to connect from the local machine with no problem. But from another Maclaptop on my home network, it can't connect using either Sql Developer or Sql Plus. After doing some research, I figured out there is this additional step you have to do:

Use the Oracle net manager. Select the Listener. Add the IP address (in my case it is 192.168.1.12) besides of the 127.0.0.1 or localhost.

This will end up add an entry to the [OracleHome]\product\11.2.0\dbhome_1\network\admin\listener.ora

  • restart the listener service. (note: for me I reboot machine once to make it work)

  • Use lsnrctl status to verify
    Notice the additional HOST=192.168.1.12 shows up and this is what to make remote connection to work.

    C:\Windows\System32>lsnrctl status
    LSNRCTL for 64-bit Windows: Version 11.2.0.1.0 - Production on 05-SEP-2015 13:51:43
    Copyright (c) 1991, 2010, Oracle. All rights reserved.
    Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
    STATUS of the LISTENER


    Alias LISTENER
    Version TNSLSNR for 64-bit Windows: Version 11.2.0.1.0 - Production
    Start Date 05-SEP-2015 13:45:18
    Uptime 0 days 0 hr. 6 min. 24 sec
    Trace Level off
    Security ON: Local OS Authentication
    SNMP OFF
    Listener Parameter File
    D:\oracle11gr2\product\11.2.0\dbhome_1\network\admin\listener.ora
    Listener Log File d:\oracle11gr2\diag\tnslsnr\eagleii\listener\alert\log.xml
    Listening Endpoints Summary...
    (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\.\pipe\EXTPROC1521ipc)))
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521)))
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.12)(PORT=1521)))
    Services Summary...
    Service "CLRExtProc" has 1 instance(s).
    Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
    Service "xe" has 1 instance(s).
    Instance "xe", status READY, has 1 handler(s) for this service... Service "xeXDB" has 1 instance(s).
    Instance "xe", status READY, has 1 handler(s) for this service... The command completed successfully

  • use tnsping to test the connection
    ping the IPv4 address, not the localhost or the 127.0.0.1

C:\Windows\System32>tnsping 192.168.1.12
TNS Ping Utility for 64-bit Windows: Version 11.2.0.1.0 - Production on 05-SEP-2015 14:09:11
Copyright (c) 1997, 2010, Oracle. All rights reserved.
Used parameter files:
D:\oracle11gr2\product\11.2.0\dbhome_1\network\admin\sqlnet.ora

Used EZCONNECT adapter to resolve the alias
Attempting to contact (DESCRIPTION=(CONNECT_DATA=(SERVICE_NAME=))(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.12)(PORT=1521)))
OK (0 msec)

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

jQuery form validation on button click

You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button

Are HTTPS headers encrypted?

With SSL the encryption is at the transport level, so it takes place before a request is sent.

So everything in the request is encrypted.

How to do a redirect to another route with react-router?

With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.

import { Router } from 'react-router';

export default class Foo extends Component {

  static get contextTypes() {
    return {
      router: React.PropTypes.object.isRequired,
    };
  }

  handleClick() {
    this.context.router.push('/some-path');
  }
}

How do I add space between two variables after a print in Python

Alternatively you can use ljust/rjust to make the formatting nicer.

print "%s%s" % (str(count).rjust(10), conv)

or

print str(count).ljust(10), conv

Java to Jackson JSON serialization: Money fields

Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:

SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);

In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).

Declaring a custom android UI element using XML

It seems that Google has updated its developer page and added various trainings there.

One of them deals with the creation of custom views and can be found here

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

As of mid 2020, none of the answers here provides any explanation, just hacking or guessing.

As @Coderer points out before me, secure context (https) is required today, so on more and more devices geolocation doesn't work at all with plain http:

Secure context This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The third parameter of getCurrentPosition() (and watchPosition() which is more suitable here) is PositionOptions object consisting of these properties:

  • enableHighAccurancy (default false): if set to true, response is slower and more accurate. If you got timeout errors, keep this to false. If the accurancy is low, set it to true. In my tests 1s delay with 1-2 meters precision and there was no difference between true and false on UMAX tablet. I tested also on older iPhone with 5 meters oscilation if set to false. You can also measure accurancy in GeolocationCoordinates.accurancy property and decide dynamically.
  • timeout (default infinity): milliseconds before the API gives up and calls the error handler (the second parameter). Today, 5s (5000) is reasonable and in some cases 10s can make sense. Useful if you want to have plan B when geolocation sensor data is not available.
  • maximumAge (default 0): milliseconds when cached value is valid, the device may decide to use valid cached data instead of sensor measure. Set this to Infinity on static locations, keep at 0 otherwise.

As @YoLoCo points out before me, getCurrentPosition() and watchPosition() interferes and I confirm his results in 2020. Generally, use watchPosition instead of getCurrentPosition periodical calls.

npm ERR! Error: EPERM: operation not permitted, rename

I'm using iTerm. After restarting iTerm, the error was gone.

How to get screen width and height

Try via context.getResources().getDisplayMetrics() if you have a context available.

What is the difference between supervised learning and unsupervised learning?

Supervised Learning is basically a technique in which the training data from which the machine learns is already labelled that is suppose a simple even odd number classifier where you have already classified the data during training . Therefore it uses "LABELLED" data.

Unsupervised learning on the contrary is a technique in which the machine by itself labels the data . Or you can say its the case when the machine learns by itself from scratch.

Why am I getting InputMismatchException?

I encountered the same problem. Strange, but the reason was that the object Scanner interprets fractions depending on localization of system. If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String. Hence the error ...

Generate random numbers with a given (numerical) distribution

(OK, I know you are asking for shrink-wrap, but maybe those home-grown solutions just weren't succinct enough for your liking. :-)

pdf = [(1, 0.1), (2, 0.05), (3, 0.05), (4, 0.2), (5, 0.4), (6, 0.2)]
cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]
R = max(i for r in [random.random()] for i,c in cdf if c <= r)

I pseudo-confirmed that this works by eyeballing the output of this expression:

sorted(max(i for r in [random.random()] for i,c in cdf if c <= r)
       for _ in range(1000))

How to get attribute of element from Selenium?

You are probably looking for get_attribute(). An example is shown here as well

def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?
    val = org.get_attribute("attribute name")

Disable/enable an input with jQuery?

Use like this,

 $( "#id" ).prop( "disabled", true );

 $( "#id" ).prop( "disabled", false );

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

For me the problem was solved by deleting a .pid file named after my computer:

sudo rm /var/mysql/computername.pid

Tomcat in Intellij Idea Community Edition

Well the question is already answered, however what I am writing here is just my observation so other fellows in the community can save some of their time. I tried running a spring-mvc project using the embedded tom-cat in Intellij communit edition.

First try I did was using the Gradle tom-cat plugin, however the problem that I faced there is the tomcat server just starts once, after that from the second start the build complains saying that a container is already running. There are so many open thread on the web about this, for some it works and for most of the people (almost 90% of the web threads that I broke my head with, faced the same problem of container not getting started the second time. The resolution is not there.

After wasting a lot lot of my time, I finally decided to switch to maven tom-cat plugin and do the same spring-mvc setup with maven that I did with gradle and VOILA! it worked in the first short.

So long story short, if you are setting up spring-mvc project in intellij community edition, please consider maven tomcat plugin.

Hope this helps somebody's hours of exploration across various web forums.

C# Passing Function as Argument

There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.

For functions with return types, there is Func<> and for functions without return types there is Action<>.

Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).

So you can declare your Diff function to take a Func:

public double Diff(double x, Func<double, double> f) {
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:

double result = Diff(myValue, Function);

You can even write the function in-line with lambda syntax:

double result = Diff(myValue, d => Math.Sqrt(d * 3.14));

Fully change package name including company domain

I also faced same problem & here is how I solved :-

I want to change package name np.com.shivakrstha.userlog to np.edu.khec.userlog

I selected shivakrstha and I pressed Shift + F6 for Rename Refract and renamed to khec.

Finally, use the same package name in AndroidManifest.xml, applicationId in build.gradle and don't forget to Rebuild Your Project.

Note:- I tried to change np to jp, so I selected np and I pressed Shift + F6 for Rename Refract and renamed to jp, it's ok to change others too.

Meaning of "n:m" and "1:n" in database design

In a relational database all types of relationships are represented in the same way: as relations. The candidate key(s) of each relation (and possibly other constraints as well) determine what kind of relationship is being represented. 1:n and m:n are two kinds of binary relationship:

C {Employee*,Company}
B {Book*,Author*}

In each case * designates the key attribute(s). {Book,Author} is a compound key.

C is a relation where each employee works for only one company but each company may have many employees (1:n): B is a relation where a book can have many authors and an author may write many books (m:n):

Notice that the key constraints ensure that each employee can only be associated with one company whereas any combination of books and authors is permitted.

Other kinds of relationship are possible as well: n-ary (having more than two components); fixed cardinality (m:n where m and n are fixed constants or ranges); directional; and so on. William Kent in his book "Data and Reality" identifies at least 432 kinds - and that's just for binary relationships. In practice, the binary relationships 1:n and m:n are very common and are usually singled out as specially important in designing and understanding data models.

convert '1' to '0001' in JavaScript

This is a clever little trick (that I think I've seen on SO before):

var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str

JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):

That is, with the above:

  • 1 -> "0001"
  • 12345 -> "12345"

Supporting negative numbers is left as an exercise ;-)

Happy coding.

Passing data between different controller action methods

If you need to pass data from one controller to another you must pass data by route values.Because both are different request.if you send data from one page to another then you have to user query string(same as route values).

But you can do one trick :

In your calling action call the called action as a simple method :

public class ServerController : Controller
{
 [HttpPost]
 public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
 {
      XDocument updatedResultsDocument = myService.UpdateApplicationPools();
      ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.

      return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
      // Redirect to ApplicationPool controller and pass
      // updatedResultsDocument to be used in UpdateConfirmation action method
 }
}

gulp command not found - error after installing gulp

This is most commonly because it is not found on environment variables as others have pointed out. This is what worked for me.

echo %PATH%

This will show you what's one your PATH environment variable. If node_modules is not there there do the following to add it from your APPDATA path.

PATH = %PATH%; %APPDATA%\npm

Wireshark localhost traffic capture

Please try Npcap: https://github.com/nmap/npcap, it is based on WinPcap and supports loopback traffic capturing on Windows. Npcap is a subproject of Nmap (http://nmap.org/), so please report any issues on Nmap's development list (http://seclists.org/nmap-dev/).

How to check if dropdown is disabled?

There are two options:

First

You can also use like is()

$('#dropDownId').is(':disabled');

Second

Using == true by checking if the attributes value is disabled. attr()

$('#dropDownId').attr('disabled');

whatever you feel fits better , you can use :)

Cheers!

What is the proper way to test if a parameter is empty in a batch file?

You can use

if defined (variable) echo That's defined!
if not defined (variable) echo Nope. Undefined.

Launch a shell command with in a python script, wait for the termination and return to the script

You can use subprocess.Popen. There's a few ways to do it:

import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
    print line
p.wait()
print p.returncode

Or, if you don't care what the external program actually does:

cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()

How can I declare and define multiple variables in one line using C++?

int column(0), row(0), index(0);

Note that this form will work with custom types too, especially when their constructors take more than one argument.

How to import Maven dependency in Android Studio/IntelliJ?

  1. Uncheck "Offline work" in File>Settings>Gradle>Global Gradle Settings
  2. Resync the project, for example by restarting the Android Studio
  3. Once synced, you can check the option again to work offline.

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

The other answers here clearly explained what does it mean.I like to explain its use.

You can select an element in the elements tab and switch to console tab in chrome. Just type $0 or $1 or whatever number and press enter and the element will be displayed in the console for your use.

screenshot of chrome dev tools

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

How to disable the parent form when a child form is active?

You can do that with the following:

Form3 formshow = new Form3();

formshow.ShowDialog();

Move layouts up when soft keyboard is shown?

I just added the following line to the top level layout and everything worked:

android:fitsSystemWindows="true"

How to get an object's property's value by property name?

Here is an alternative way to get an object's property value:

write-host $(get-something).SomeProp

How to index characters in a Golang string?

Can be done via slicing too

package main

import "fmt"

func main() {
    fmt.Print("HELLO"[1:2])
}

NOTE: This solution only works for ASCII characters.

How to strip HTML tags with jQuery?

If you want to keep the innerHTML of the element and only strip the outermost tag, you can do this:

$(".contentToStrip").each(function(){
  $(this).replaceWith($(this).html());
});

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

How I do it with Django 1.11 :

class ItemForm(ModelForm):
    disabled_fields = ('added_by',)

    class Meta:
        model = Item
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        for field in self.disabled_fields:
            self.fields[field].disabled = True

Open file by its full path in C++

Normally one uses the backslash character as the path separator in Windows. So:

ifstream file;
file.open("C:\\Demo.txt", ios::in);

Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.

Relationship between hashCode and equals method in Java

A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.

Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.

How to make an introduction page with Doxygen

I tried all the above with v 1.8.13 to no avail. What worked for me (on macOS) was to use the doxywizard->Expert tag to fill the USE_MD_FILE_AS_MAINPAGE setting.

It made the following changes to my Doxyfile:

USE_MDFILE_AS_MAINPAGE = ../README.md
...
INPUT                  = ../README.md \
                         ../sdk/include \
                         ../sdk/src

Note the line termination for INPUT, I had just been using space as a separator as specified in the documentation. AFAICT this is the only change between the not-working and working version of the Doxyfile.

How to install toolbox for MATLAB

Use ver it will list all the installed toolboxes and versions of the toolbox.

Show popup after page load

You can also do this much easier with a plugin called jQuery-confirm. All you have to do is add the script tag and the style sheet they provide in your page

<link rel="stylesheet" 
href="https://cdnjs.cloudflare.com/ajax/libs/jquery-
confirm/3.3.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-
confirm/3.3.0/jquery-confirm.min.js"></script>

And then an example of calling the alert box is:

   <script>
        $.alert({
    title: 'Alert!',
    content: 'Simple alert!',
     });

What are my options for storing data when using React Native? (iOS and Android)

you can use sync storage that is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.

import SyncStorage from 'sync-storage';

SyncStorage.set('foo', 'bar');
const result = SyncStorage.get('foo');
console.log(result); // 'bar'

How to change background color of cell in table using java script

<table border="1" cellspacing="0" cellpadding= "20">
    <tr>
    <td id="id1" ></td>
    </tr>
</table>
<script>
    document.getElementById('id1').style.backgroundColor='#003F87';
</script>

Put id for cell and then change background of the cell.

recursively use scp but excluding some folders

You can specify GLOBIGNORE and use the pattern *

GLOBIGNORE='ignore1:ignore2' scp -r source/* remoteurl:remoteDir

You may wish to have general rules which you combine or override by using export GLOBIGNORE, but for ad-hoc usage simply the above will do. The : character is used as delimiter for multiple values.

XML Serialize generic list of serializable objects

You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer (the extraTypes parameter) :

List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());

XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xs.Serialize(streamWriter, list);
}

If all the objects of your list inherit from the same class, you can also use the XmlInclude attribute to specify the expected types :

[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}

Add to Array jQuery

You are right. This has nothing to do with jQuery though.

var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.

How can I zoom an HTML element in Firefox and Opera?

I've been swearing at this for a while. Zoom is definitely not the solutions, it works in chrome, it works partially in IE but moves the entire html div, firefox doesnt do a thing.

My solution that worked for me was using both a scaling and a translation, and also adding the original height and weight and then setting the height and weight of the div itself:

#miniPreview {
transform: translate(-710px, -1000px) rotate(0rad) skewX(0rad) scale(0.3, 0.3);
transform-origin: 1010px 1429px 0px;
width: 337px;
height: 476px;

Obviously change these to your own needs. It gave me the same result in all browsers.

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

Bash: If/Else statement in one line

There is no need to explicitly check $?. Just do:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0 

Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

jQuery Scroll to bottom of page/iframe

$('.block').scrollTop($('.block')[0].scrollHeight);

I use this code to scroll the chat when new messages arrive.

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

How do I remove a file from the FileList

If you are targeting evergreen browsers (Chrome, Firefox, Edge, but also works in Safari 9+) or you can afford a polyfill, you can turn the FileList into an array by using Array.from() like this:

let fileArray = Array.from(fileList);

Then it's easy to handle the array of Files like any other array.

How do I encode a JavaScript object as JSON?

All major browsers now include native JSON encoding/decoding.

// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject); 

// To decode (This produces an object)
var obj = JSON.parse(json_str);

Note that only valid JSON data will be encoded. For example:

var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"

Valid JSON types are: objects, strings, numbers, arrays, true, false, and null.

Some JSON resources:

Remove all stylings (border, glow) from textarea

The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.

textarea {
    border: none;
    overflow: auto;
    outline: none;

    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;

    resize: none; /*remove the resize handle on the bottom right*/
}

You may also try adding !important to prioritize this CSS.

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

you can disable security check. go to

Project -> Properties -> Configuration properties -> C/C++ -> Code Generation -> Security Check

and select Disable Security Check (/GS-)

Inserting records into a MySQL table using Java

this can also be done like this if you don't want to use prepared statements.

String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"

Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.

How can I refresh a page with jQuery?

It is shortest in JavaScript.

window.location = '';

Why do I need to explicitly push a new branch?

I couldn't find a rationale by the original developers this quickly, but I can give you an educated guess based on a few years of Git experience.

No, not every branch is something you want to push to the outside world. It might represent a private experiment.

Moreover, where should git push send all the branches? Git can work with multiple remotes and you may want to have different sets of branches on each. E.g. a central project GitHub repo may have release branches; a GitHub fork may have topic branches for review; and a local Git server may have branches containing local configuration. If git push would push all branches to the remote that the current branch tracks, this kind of scheme would be easy to screw up.

Delete the first five characters on any line of a text file in Linux with sed

sed 's/^.\{,5\}//' file.dat worked like a charm for me

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.

Remove the last line from a file in Bash

OK processing a good amount of data and the output was OK, but had one junk line.

If I piped the output of the script to:

| sed -i '$ d' I would get the following error and finally no output at all sed: no input files

But | head -n -1 worked!

JQuery / JavaScript - trigger button click from another button click event

If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

GoogleMaps API KEY for testing

Updated Answer

As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.

This answer is no longer valid

As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.

Declaring a boolean in JavaScript using just var

As this very useful tutorial says:

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

How do I make curl ignore the proxy?

Long shot but try setting the proxy to "" (empty string) that should override any proxy settings according to the man page.

How do I write a "tab" in Python?

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

Anaconda Installed but Cannot Launch Navigator

On windows 10, I faced the same error - only Anaconda Prompt was showing in the startup menu. What I did is i re-installed Anaconda and selected install for all users of the pc (in my initial installation I have installed only for current user).

Translating touch events from Javascript to jQuery

jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

Difference between Method and Function?

Programmers from structural programming language background know it as a function while in OOPS it's called a method.

But there's not any difference between the two.

In the old days, methods did not return values and functions did. Now they both are used interchangeably.

Psql list all tables

Connect to the database, then list the tables:

\c liferay
\dt

That's how I do it anyway.

You can combine those two commands onto a single line, if you prefer:

\c liferay \dt

Magento: get a static block as html in a phtml file

Following code will work when you Call CMS-Static Block in Magento.

<?php echo 

$this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml();

?>

stale element reference: element is not attached to the page document

This errors have two common causes: The element has been deleted entirely, or the element is no longer attached to the DOM.

If you already checked if it is not your case, you could be facing the same problem as me.

The element in the DOM is not found because your page is not entirely loaded when Selenium is searching for the element. To solve that, you can put an explicit wait condition that tells Selenium to wait until the element is available to be clicked on.

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

See: https://selenium-python.readthedocs.io/waits.html

What are the main differences between JWT and OAuth authentication?

OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.

OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.

But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.

So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).

how to change the default positioning of modal in bootstrap?

Add the following css to your html and try changing the top, right, bottom, left values.

.modal {
   position: absolute;
   top: 10px;
   right: 100px;
   bottom: 0;
   left: 0;
   z-index: 10040;
   overflow: auto;
   overflow-y: auto;
}

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

How do I rename both a Git local and remote branch name?

I use these git alias and it pretty much does the job automatic:

git config --global alias.move '!git checkout master; git branch -m $1 $2; git status; git push --delete origin $1; git status; git push -u origin $2; git branch -a; exit;'

Usage: git move FROM_BRANCH TO_BRANCH

It works if you have the default names like master, origin etc. You can modify as you wish but it gives you the idea.

Adding a collaborator to my free GitHub account?

It is pretty easy to add a collaborator to a free plan.

  1. Navigate to the repository on Github you wish to share with your collaborator.
  2. Click on the "Settings" tab on the right side of the menu at the top of the screen.
  3. On the new page, click the "Collaborators" menu item on the left side of the page.
  4. Start typing the new collaborator's GitHub username into the text box.
  5. Select the GitHub user from the list that appears below the text box.
  6. Click the "Add" button.

The added user should now be able to push to your repository on GitHub.

how to display a javascript var in html body

You cannot add JavaScript variable to HTML code.

For this you need to do in following way.

<html>
<head>
<script type="text/javscript">
var number = 123;

document.addEventListener('DOMContentLoaded', function() {
   document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>

MySQL Install: ERROR: Failed to build gem native extension

I had a similar experience, so here are the things that I tried

Firstly, I tried to install mysql's required packages by running the command below in my terminal

sudo apt-get install build-essential libmysqlclient-dev

Secondly, I tried updating rubygems on my system by running the command below in my terminal

sudo gem update --system

But I was still experiencing the same issue. After much research I realized that I was using an almost out-of-date version of the mysql gem. I simply needed to use the mysql2 gem (mysql2 gem)and not the mysql gem, so I fixed it by running the command below in my terminal

gem install mysql2

This worked fine for me. Before running the last command, ensure that you've ran the first and second commands to be sure that everything is fine on your system.

That's all.

I hope this helps

How do I clear my local working directory in Git?

To reset a specific file as git status suggests:

git checkout <filename>

To reset a folder

git checkout <foldername>/*

What is the !! (not not) operator in JavaScript?

!!foo applies the unary not operator twice and is used to cast to boolean type similar to the use of unary plus +foo to cast to number and concatenating an empty string ''+foo to cast to string.

Instead of these hacks, you can also use the constructor functions corresponding to the primitive types (without using new) to explicitly cast values, ie

Boolean(foo) === !!foo
Number(foo)  === +foo
String(foo)  === ''+foo

Android Viewpager as Image Slide Gallery

In Jake's ViewPageIndicator he has implemented View pager to display a String array (i.e. ["this","is","a","text"]) which you pass from YourAdapter.java (that extends FragmentPagerAdapter) to the YourFragment.java which returns a View to the viewpager.

In order to display something different, you simply have to change the context type your passing. In this case you want to pass images instead of text, as shown in the sample below:

This is how you setup your Viewpager:

public class PlaceDetailsFragment extends SherlockFragment {
    PlaceSlidesFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;

    public static final String TAG = "detailsFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_place_details,
                container, false);

        mAdapter = new PlaceSlidesFragmentAdapter(getActivity()
                .getSupportFragmentManager());

        mPager = (ViewPager) view.findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
        ((CirclePageIndicator) mIndicator).setSnap(true);

        mIndicator
                .setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        Toast.makeText(PlaceDetailsFragment.this.getActivity(),
                                "Changed to page " + position,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onPageScrolled(int position,
                            float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                });
        return view;
    }

}

your_layout.xml

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



    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.viewpagerindicator.CirclePageIndicator
        android:id="@+id/indicator"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip" />

</LinearLayout>

YourAdapter.java

public class PlaceSlidesFragmentAdapter extends FragmentPagerAdapter implements
        IconPagerAdapter {

    private int[] Images = new int[] { R.drawable.photo1, R.drawable.photo2,
            R.drawable.photo3, R.drawable.photo4

    };

    protected static final int[] ICONS = new int[] { R.drawable.marker,
            R.drawable.marker, R.drawable.marker, R.drawable.marker };

    private int mCount = Images.length;

    public PlaceSlidesFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return new PlaceSlideFragment(Images[position]);
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public int getIconResId(int index) {
        return ICONS[index % ICONS.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }
}

YourFragment.java

// you need to return image instaed of text from here.//

public final class PlaceSlideFragment extends Fragment {
    int imageResourceId;

    public PlaceSlideFragment(int i) {
        imageResourceId = i;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        ImageView image = new ImageView(getActivity());
        image.setImageResource(imageResourceId);

        LinearLayout layout = new LinearLayout(getActivity());
        layout.setLayoutParams(new LayoutParams());

        layout.setGravity(Gravity.CENTER);
        layout.addView(image);

        return layout;
    }
}

You should get a View pager like this from the above code. enter image description here

How to set placeholder value using CSS?

Another way this can be accomplished, and have not really seen any others give it as an option, is to instead use an anchor as a container around your input and label, and handle the removal of the label via some color trickory, the #hashtag, and the css a:visited. (jsfiddle at the bottom)

Your HTML would look like this:

<a id="Trickory" href="#OnlyHappensOnce">
    <input type="text" value="" id="email1" class="inputfield_ui" />
    <label>Email address 1</label>
</a>

And your CSS, something like this:

html, body {margin:0px}
a#Trickory {color: #CCC;} /* Actual Label Color */
a#Trickory:visited {color: #FFF;} /* Fake "Turn Off" Label */

a#Trickory:visited input {border-color: rgb(238, 238, 238);} /* Make Sure We Dont Mess With The Border Of Our Input */

a#Trickory input:focus + label {display: none;} /* "Turn Off" Label On Focus */

a#Trickory input {
    width:95%;
    z-index:3;
    position:relative;
    background-color:transparent;
}
a#Trickory label {
    position:absolute;
    pointer-events: none;
    display:block;
    top:3px;
    left:4px;
    z-index:1;
}

You can see this working over at jsfiddle, note that this solution only allows the user to select the field once, before it removes the label for good. Maybe not the solution you want, but definitely an available solution out there that I have not seen others mention. If you want to experiment multiple times, just change your #hashtag to a new 'non-visited' tag.

http://jsfiddle.net/childerskc/M6R7K/

SQL 'LIKE' query using '%' where the search criteria contains '%'

May be this one help :)

DECLARE @SearchCriteria VARCHAR(25)
SET  @SearchCriteria = 'employee'
IF CHARINDEX('%', @SearchCriteria) = 0
BEGIN
SET @SearchCriteria = '%' + @SearchCriteria + '%'
END
SELECT * 
FROM Employee
WHERE Name LIKE @SearchCriteria

Can one do a for each loop in java in reverse order?

The Collections.reverse method actually returns a new list with the elements of the original list copied into it in reverse order, so this has O(n) performance with regards to the size of the original list.

As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.

For example:

public class Reversed<T> implements Iterable<T> {
    private final List<T> original;

    public Reversed(List<T> original) {
        this.original = original;
    }

    public Iterator<T> iterator() {
        final ListIterator<T> i = original.listIterator(original.size());

        return new Iterator<T>() {
            public boolean hasNext() { return i.hasPrevious(); }
            public T next() { return i.previous(); }
            public void remove() { i.remove(); }
        };
    }

    public static <T> Reversed<T> reversed(List<T> original) {
        return new Reversed<T>(original);
    }
}

And you would use it like:

import static Reversed.reversed;

...

List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
    doSomethingWith(s);
}

How to retry image pull in a kubernetes Pods?

Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:

kubectl replace --force -f <yml_file_describing_pod>

Declare a constant array

An array isn't immutable by nature; you can't make it constant.

The nearest you can get is:

var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 }

Note the [...] instead of []: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.

Sys is undefined

I had similar problems and to my surprise what I found that one of my developer had saved web.config in the same folder/solution as web123.config and by mistake both of these files were uploaded.

As soon as I deleted the web123.config file, this error disappeared and ajax framework was loading correctly. even though I have

<compilation debug="true">

In my case I also have following segment. My project is using framework 3.5

    <httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

Had the same problem, I just coerced the id into a string.

My schema:

const product = new mongooseClient.Schema({
    retailerID: { type: mongoose.SchemaTypes.ObjectId, required: true, index: true }
});

And then, when inserting:

retailerID: `${retailer._id}`

Nexus 5 USB driver

Windows 7 x32 I found that no matter what I did, the driver being used dated back to 2006. It would not update, in fact Windows appears to be preferring the old driver to the new. I eventually found a way to sort it.

The Device Manager contains 'ghost' drivers that need to be deleted (if you have the same problem as I). To see them requires setting a variable in the registry, restarting and then deleting the likely redundant drivers.

Open the Device Manager from the command line use devmgmt.msc There are other ways, but this is easiest to describe. Currently it shows only 'current' drivers.

Open the System Properties box. Via Command line use sysdm.cpl

** Be aware that playing with area of your computer can break it. Back away if you are at all unsure of this. **

  1. Open the Advanced tab, click Environmental Variables.
  2. Under System Variables, click New.
  3. Enter variable name devmgr_show_nonpresent_devices, under value enter 1.
  4. Restart your computer.

Re-open the Device Manager, under view click Show Hidden Devices.

From here delete what you think are the problems then follow the advise you will have read elsewhere. On two seperate computers I have done this and found all I needed to do following this was download and install the standard google drivers as per user3079537's answer above. Good luck.

ref: http://www.petri.co.il/removing-old-drivers-from-vista-and-windows7.htm#

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

Centering in CSS Grid

You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.

From flexbox specs:

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the white-space property) is not rendered (just as if it were display:none).

So just make grid items as flex containers (display: flex), and add align-items: center and justify-content: center to center both vertically and horizontally.

Also performed optimization of HTML and CSS:

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-template-rows: 100vh;_x000D_
  _x000D_
  font-family: Raleway;_x000D_
  font-size: large;_x000D_
}_x000D_
_x000D_
.left_bg,_x000D_
.right_bg {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
  background-color: #3498db;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
  background-color: #ecf0f1;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left_bg">Review my stuff</div>_x000D_
  <div class="right_bg">Hire me!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find the duration of difference between two dates in java?

Use Joda-Time library

DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();

Joda Time has a concept of time Interval:

Interval interval = new Interval(oldTime, new Instant());

One more example Date Difference

One more Link

or with Java-8 (which integrated Joda-Time concepts)

Instant start, end;//
Duration dur = Duration.between(start, stop);
long hours = dur.toHours();
long minutes = dur.toMinutes();

When to use 'npm start' and when to use 'ng serve'?

If you want to run angular app ported from another machine without ng command then edit package.json as follows

"scripts": {
    "ng": "ng",
    "start": "node node_modules/.bin/ng serve",
    "build": "node node_modules/.bin/ng build",
    "test": "node node_modules/.bin/ng test",
    "lint": "node node_modules/.bin/ng lint",
    "e2e": "node node_modules/.bin/ng e2e"
  }

Finally run usual npm start command to start build server.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

Oke, I was looking at this issue as well. And in my case the solutions was too easy. I added a new empty project to the solution. The newly added project is automatically set as a console application. But since the project added was a 'empty' project, no Program.cs existed in that new project. (As expected)

All I needed to do was change the output type of the project properties to Class library

Get current AUTO_INCREMENT value for any table

If you just want to know the number, rather than get it in a query then you can use:

SHOW CREATE TABLE tablename;

You should see the auto_increment at the bottom

How to format numbers by prepending 0 to single-digit numbers?

Quick and dirty one liner....

function zpad(n, len) {
  return 0..toFixed(len).slice(2,-n.toString().length)+n.toString();
}

How do I output lists as a table in Jupyter notebook?

I finally re-found the jupyter/IPython documentation that I was looking for.

I needed this:

from IPython.display import HTML, display

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

display(HTML(
   '<table><tr>{}</tr></table>'.format(
       '</tr><tr>'.join(
           '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in data)
       )
))

(I may have slightly mucked up the comprehensions, but display(HTML('some html here')) is what we needed)

How can I add an item to a IEnumerable<T> collection?

Easyest way to do that is simply

IEnumerable<T> items = new T[]{new T("msg")};
List<string> itemsList = new List<string>();
itemsList.AddRange(items.Select(y => y.ToString()));
itemsList.Add("msg2");

Then you can return list as IEnumerable also because it implements IEnumerable interface

Stopping Excel Macro executution when pressing Esc won't work

CTRL + SCR LK (Scroll Lock) worked for me.

test attribute in JSTL <c:if> tag

Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.

If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

You may need to do AndroidStudio - Build - Clean

If you updated manifest through the filesystem or Git it won't pick up the changes.

All shards failed

If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:

curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
    "index" : {
        "number_of_replicas" : 0
    }
}'

Doing this you'll force to use es without replicas

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

How to properly add include directories with CMake

Two things must be done.

First add the directory to be included:

target_include_directories(test PRIVATE ${YOUR_DIRECTORY})

In case you are stuck with a very old CMake version (2.8.10 or older) without support for target_include_directories, you can also use the legacy include_directories instead:

include_directories(${YOUR_DIRECTORY})

Then you also must add the header files to the list of your source files for the current target, for instance:

set(SOURCES file.cpp file2.cpp ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)
add_executable(test ${SOURCES})

This way, the header files will appear as dependencies in the Makefile, and also for example in the generated Visual Studio project, if you generate one.

How to use those header files for several targets:

set(HEADER_FILES ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)

add_library(mylib libsrc.cpp ${HEADER_FILES})
target_include_directories(mylib PRIVATE ${YOUR_DIRECTORY})
add_executable(myexec execfile.cpp ${HEADER_FILES})
target_include_directories(myexec PRIVATE ${YOUR_DIRECTORY})

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

BTW, Yandex Metrica also uses IDFA.

./Pods/YandexMobileMetrica/libYandexMobileMetrica.a

They say on their GitHub page that

"Starting from version 1.6.0 Yandex AppMetrica became also a tracking instrument and uses Apple idfa to attribute installs. Because of that during submitting your application to the AppStore you will be prompted with three checkboxes to state your intentions for idfa usage. As Yandex AppMetrica uses idfa for attributing app installations you need to select Attribute this app installation to a previously served advertisement."

So, I will try to select this checkbox and send my app without actually no any ads in it.

CSS Progress Circle

What about that?

HTML

<div class="chart" id="graph" data-percent="88"></div>

Javascript

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

and CSS

div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

http://jsfiddle.net/Aapn8/3410/

Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/

How can I convert an integer to a hexadecimal string in C?

I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :

char* dechex (int dec);

This will use calloc() to to return a pointer to an hexadecimal string, this way the quantity of memory used is optimized, so don't forget to use free()

Here the link on github : https://github.com/kevmuret/libhex/

Using async/await with a forEach loop

In addition to @Bergi’s answer, I’d like to offer a third alternative. It's very similar to @Bergi’s 2nd example, but instead of awaiting each readFile individually, you create an array of promises, each which you await at the end.

import fs from 'fs-promise';
async function printFiles () {
  const files = await getFilePaths();

  const promises = files.map((file) => fs.readFile(file, 'utf8'))

  const contents = await Promise.all(promises)

  contents.forEach(console.log);
}

Note that the function passed to .map() does not need to be async, since fs.readFile returns a Promise object anyway. Therefore promises is an array of Promise objects, which can be sent to Promise.all().

In @Bergi’s answer, the console may log file contents in the order they’re read. For example if a really small file finishes reading before a really large file, it will be logged first, even if the small file comes after the large file in the files array. However, in my method above, you are guaranteed the console will log the files in the same order as the provided array.

Questions every good Java/Java EE Developer should be able to answer?

Usage of final keyword in method calls. For example why does the method test in below code does not give any compile error despite using final qualifier for the method parameter.

class Name {
    private String name;

    public Name (String s) {
        this.name = s;
    }

    public void setName(String s) {
        this.name = s;
    }
}

private void test (final Name n) {
    n.setName("test");
}

Find unique lines

Use as follows:

sort < filea | uniq > fileb

React - uncaught TypeError: Cannot read property 'setState' of undefined

This error can be resolved by various methods-

  • If you are using ES5 syntax, then as per React js Documentation you have to use bind method.

    Something like this for the above example:

    this.delta = this.delta.bind(this)

  • If you are using ES6 syntax,then you need not use bind method,you can do it with something like this:

    delta=()=>{ this.setState({ count : this.state.count++ }); }

Java: how to add image to Jlabel?

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

I was having this same issue and it was because I was trying to manipulate elements using javascript in a div that was overflow: scroll, all I did was change overflow to auto and everything worked.

Hope this helps

Using the rJava package on Win7 64 bit with R

The last question has an easy answer:

> .Machine$sizeof.pointer
[1] 8

Meaning I am running R64. If I were running 32 bit R it would return 4. Just because you are running a 64 bit OS does not mean you will be running 64 bit R, and from the error message it appears you are not.

EDIT: If the package has binaries, then they are in separate directories. The specifics will depend on the OS. Notice that your LoadLibrary error occurred when it attempted to find the dll in ...rJava/libs/x64/... On my MacOS system the ...rJava/libs/...` folder has 3 subdirectories: i386, ppc, and x86_64. (The ppc files are obviously useless baggage.)

How to create timer events using C++ 11?

This is the code I have so far:

I am using VC++ 2012 (no variadic templates)

//header
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
#include <memory>
#include <algorithm>

template<class T>
class TimerThread
{
  typedef std::chrono::high_resolution_clock clock_t;

  struct TimerInfo
  {
    clock_t::time_point m_TimePoint;
    T m_User;

    template <class TArg1>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1))
    {
    }

    template <class TArg1, class TArg2>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1, TArg2 && arg2)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2))
    {
    }
  };

  std::unique_ptr<std::thread> m_Thread;
  std::vector<TimerInfo>       m_Timers;
  std::mutex                   m_Mutex;
  std::condition_variable      m_Condition;
  bool                         m_Sort;
  bool                         m_Stop;

  void TimerLoop()
  {
    for (;;)
    {
      std::unique_lock<std::mutex>  lock(m_Mutex);

      while (!m_Stop && m_Timers.empty())
      {
        m_Condition.wait(lock);
      }

      if (m_Stop)
      {
        return;
      }

      if (m_Sort)
      {
        //Sort could be done at insert
        //but probabily this thread has time to do
        std::sort(m_Timers.begin(),
                  m_Timers.end(),
                  [](const TimerInfo & ti1, const TimerInfo & ti2)
        {
          return ti1.m_TimePoint > ti2.m_TimePoint;
        });
        m_Sort = false;
      }

      auto now = clock_t::now();
      auto expire = m_Timers.back().m_TimePoint;

      if (expire > now) //can I take a nap?
      {
        auto napTime = expire - now;
        m_Condition.wait_for(lock, napTime);

        //check again
        auto expire = m_Timers.back().m_TimePoint;
        auto now = clock_t::now();

        if (expire <= now)
        {
          TimerCall(m_Timers.back().m_User);
          m_Timers.pop_back();
        }
      }
      else
      {
        TimerCall(m_Timers.back().m_User);
        m_Timers.pop_back();
      }
    }
  }

  template<class T, class TArg1>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1);

  template<class T, class TArg1, class TArg2>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2);

public:
  TimerThread() : m_Stop(false), m_Sort(false)
  {
    m_Thread.reset(new std::thread(std::bind(&TimerThread::TimerLoop, this)));
  }

  ~TimerThread()
  {
    m_Stop = true;
    m_Condition.notify_all();
    m_Thread->join();
  }
};

template<class T, class TArg1>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

template<class T, class TArg1, class TArg2>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1),
                                      std::forward<TArg2>(arg2)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

//sample
#include <iostream>
#include <string>

void TimerCall(int i)
{
  std::cout << i << std::endl;
}

int main()
{
  std::cout << "start" << std::endl;
  TimerThread<int> timers;

  CreateTimer(timers, 2000, 1);
  CreateTimer(timers, 5000, 2);
  CreateTimer(timers, 100, 3);

  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "end" << std::endl;
}

Does not contain a definition for and no extension method accepting a first argument of type could be found

placeBets(betList, stakeAmt) is an instance method not a static method. You need to create an instance of CBetfairAPI first:

MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

This answer seems quite outdated and not adapt for nowadays single page applications. In my case I found the solution thank to this aricle where a simple but effective solution is proposed:

_x000D_
_x000D_
html,
body {
  position: fixed;
  overflow: hidden;
}
_x000D_
_x000D_
_x000D_

This solution it's not applicable if your body is your scroll container.

Where does MAMP keep its php.ini?

To be clearer (as i read this thread but didn't SEE the solution, also if it was here!), I have the same problem and found the cause: I were modifying the wrong php.ini!

Yes, there are 2 php.ini files in MAMP:

  1. Applications/MAMP/conf/php5.5.10/php.ini
  2. Applications/MAMP/bin/php/php5.5.10/conf/php.ini

The right php.ini file is the second: Applications/MAMP/bin/php/php5.5.10/conf/php.ini

To prove this, create a .php file (call it as you like, for example "info.php") and put into it a simple phpinfo()

<?php
echo phpinfo();

Open it in your browser and search for "Loaded Configuration File": mine is "/Applications/MAMP/bin/php/php5.5.10/conf/php.ini"

The error was here; i edited Applications/MAMP/conf/php5.5.10/php.ini but this is the wrong file to modify! Infact, the right php.ini file is the one in the bin directory.

Take care of this so small difference that caused me literally 1 and a half hours of headaches!

How can I create and style a div using JavaScript?

Here's one solution that I'd use:

var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';

If you wanted the attribute and/or attribute values to be based on variables:

var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';

Then, to append to the body:

document.getElementsByTagName("body").innerHTML = div;

Easy as pie.

Getting a list of all subdirectories in the current directory

This is how I do it.

    import os
    for x in os.listdir(os.getcwd()):
        if os.path.isdir(x):
            print(x)

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

This solution is (only) for SQL Server 2005

You guys are lifesavers, but as @Dan Mork said, you need to add EXEC to the mix. What was tripping me up was:

  • 'EXEC ' before the Proc Name
  • Commas in between Params
  • Chopping off '@' on the Param Definitions (not sure that bit is required though).

:

context.Database.SqlQuery<EntityType>(
    "EXEC ProcName @param1, @param2", 
    new SqlParameter("param1", param1), 
    new SqlParameter("param2", param2)
);

Unioning two tables with different number of columns

Add extra columns as null for the table having less columns like

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

How to use the command update-alternatives --config java

There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all and choosing the right alternatives for everything else besides java and javac.

Read .csv file in C

Hopefully this would get you started

See it live on http://ideone.com/l23He (using stdin)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* getfield(char* line, int num)
{
    const char* tok;
    for (tok = strtok(line, ";");
            tok && *tok;
            tok = strtok(NULL, ";\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}

int main()
{
    FILE* stream = fopen("input", "r");

    char line[1024];
    while (fgets(line, 1024, stream))
    {
        char* tmp = strdup(line);
        printf("Field 3 would be %s\n", getfield(tmp, 3));
        // NOTE strtok clobbers tmp
        free(tmp);
    }
}

Output:

Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak

Adding days to a date in Java

Simple, without any other API:

To add 8 days:

Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);

equivalent of vbCrLf in c#

I typically abbreviate so that I can use several places in my code. Near the top, do something like this:

 string nl = System.Environment.NewLine;

Then I can just use "nl" instead of the full qualification everywhere when constructing strings.

How do I create ColorStateList programmatically?

Here's an example of how to create a ColorList programmatically in Kotlin:

val colorList = ColorStateList(
        arrayOf(
                intArrayOf(-android.R.attr.state_enabled),  // Disabled
                intArrayOf(android.R.attr.state_enabled)    // Enabled
        ),
        intArrayOf(
                Color.BLACK,     // The color for the Disabled state
                Color.RED        // The color for the Enabled state
        )
)

Using BufferedReader.readLine() in a while loop properly

You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.

how to display excel sheet in html page

Upload your file to Skydrive and then right click and select "Embed". They will provide iframe snippet which you can paste in your html. This works flawlessly.

Source: Office.com

Conditional WHERE clause in SQL Server

To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!

Here:

WHERE 
    DateDropped = 0
    AND CASE
            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'
            WHEN DateAppr != 0 THEN 'True'
            ELSE 'False'
        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.

Using parameters in batch files at Windows command line

Batch Files automatically pass the text after the program so long as their are variables to assign them to. They are passed in order they are sent; e.g. %1 will be the first string sent after the program is called, etc.

If you have Hello.bat and the contents are:

@echo off
echo.Hello, %1 thanks for running this batch file (%2)
pause

and you invoke the batch in command via

hello.bat APerson241 %date%

you should receive this message back:

Hello, APerson241 thanks for running this batch file (01/11/2013)

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.

--opt

This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.

--skip-extended-insert

Turn off extended-insert

Force sidebar height 100% using CSS (with a sticky bottom image)?

I realise this is an old post but I was trying to work something out for my site to have a sidebar. Would this work?

#sidebar-background
{
    position:fixed;
    width:250px;
    top:0;
    bottom:0;
    background-color:orange;
}

#content-background
{
    position:fixed;
    right:0;
    top:0;
    bottom:0;
    left:250px;
    background-color:pink;
}

#sidebar
{
    float:left;
    width:250px;
}

#content
{
    float:left;
    width:600px;
}

<div id="sidebar-background"></div>
<div id="content-background"></div>

<div id="sidebar">Sidebar stuff here</div>
<div id="content">Stuff in here</div>

Extract substring from a string

substring():

str.substring(startIndex, endIndex); 

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

How to split a dos path into its components in Python

I've been bitten loads of times by people writing their own path fiddling functions and getting it wrong. Spaces, slashes, backslashes, colons -- the possibilities for confusion are not endless, but mistakes are easily made anyway. So I'm a stickler for the use of os.path, and recommend it on that basis.

(However, the path to virtue is not the one most easily taken, and many people when finding this are tempted to take a slippery path straight to damnation. They won't realise until one day everything falls to pieces, and they -- or, more likely, somebody else -- has to work out why everything has gone wrong, and it turns out somebody made a filename that mixes slashes and backslashes -- and some person suggests that the answer is "not to do that". Don't be any of these people. Except for the one who mixed up slashes and backslashes -- you could be them if you like.)

You can get the drive and path+file like this:

drive, path_and_file = os.path.splitdrive(path)

Get the path and the file:

path, file = os.path.split(path_and_file)

Getting the individual folder names is not especially convenient, but it is the sort of honest middling discomfort that heightens the pleasure of later finding something that actually works well:

folders = []
while 1:
    path, folder = os.path.split(path)

    if folder != "":
        folders.append(folder)
    elif path != "":
        folders.append(path)

        break

folders.reverse()

(This pops a "\" at the start of folders if the path was originally absolute. You could lose a bit of code if you didn't want that.)

Return the characters after Nth character in a string

Since there is the [vba] tag, split is also easy:

str1 = "001 baseball"
str2 = Split(str1)

Then use str2(1).

MySQL limit from descending order

This way is comparatively more easy

SELECT doc_id,serial_number,status FROM date_time ORDER BY  date_time DESC LIMIT 0,1;

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

How to test if a double is an integer

you could try in this way: get the integer value of the double, subtract this from the original double value, define a rounding range and tests if the absolute number of the new double value(without the integer part) is larger or smaller than your defined range. if it is smaller you can intend it it is an integer value. Example:

public final double testRange = 0.2;

public static boolean doubleIsInteger(double d){
    int i = (int)d;
    double abs = Math.abs(d-i);
    return abs <= testRange;
}

If you assign to d the value 33.15 the method return true. To have better results you can assign lower values to testRange (as 0.0002) at your discretion.

Uncaught ReferenceError: angular is not defined - AngularJS not working

Use the ng-click directive:

<button my-directive ng-click="alertFn()">Click Me!</button>

// In <script>:
app.directive('myDirective' function() {
  return function(scope, element, attrs) {
    scope.alertFn = function() { alert('click'); };
  };
};

Note that you don't need my-directive in this example, you just need something to bind alertFn on the current scope.

Update: You also want the angular libraries loaded before your <script> block.

Assigning a variable NaN in python without numpy

Use float("nan"):

>>> float("nan")
nan

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

I ran into this problem when I simply mistyped my jdbc url in application.properties. Hope this helps someone: before:

spring.datasource.url=jdbc://localhost:3306/test

after:

spring.datasource.url=jdbc:mysql://localhost:3306/test

Cannot access wamp server on local network

1.

first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)

2.

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Order Allow,Deny
      Allow from all

if "Allow from all" line not work for your then use "Require all granted" then it will work for you.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80

3. Dont forget to restart All Services of Wamp or Apache after making this change

Java Embedded Databases Comparison

What criteria will you use to evaluate these ? If you don't know yet, then you don't need to decide right now. Try to make your application as database-implementation-agnostic as you can - providing the appropriate wrappers, data access objects etc., and make this decision when you have all the facts to hand and you have to decide.

If you're using relational databases and SQL then the above shouldn't be too hard (using JDBC etc). Make sure you have plenty of surrounding tests so that when you want to switch between databases, you can determine that your application's functionality remains the same.

I ran into the same issue some time ago. I didn't know which database to go for, so my first solution used Derby (or HSQLDB?), and I was later able to switch to HSQLDB (or Derby ? Can't remember which solution worked) once I'd determined where I had issues (relating to performance) and which solution would really work for me.

Python recursive folder read

Make sure you understand the three return values of os.walk:

for root, subdirs, files in os.walk(rootdir):

has the following meaning:

  • root: Current path which is "walked through"
  • subdirs: Files in root of type directory
  • files: Files in root (not in subdirs) of type other than directory

And please use os.path.join instead of concatenating with a slash! Your problem is filePath = rootdir + '/' + file - you must concatenate the currently "walked" folder instead of the topmost folder. So that must be filePath = os.path.join(root, file). BTW "file" is a builtin, so you don't normally use it as variable name.

Another problem are your loops, which should be like this, for example:

import os
import sys

walk_dir = sys.argv[1]

print('walk_dir = ' + walk_dir)

# If your current working directory may change during script execution, it's recommended to
# immediately convert program arguments to an absolute path. Then the variable root below will
# be an absolute path as well. Example:
# walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))

for root, subdirs, files in os.walk(walk_dir):
    print('--\nroot = ' + root)
    list_file_path = os.path.join(root, 'my-directory-list.txt')
    print('list_file_path = ' + list_file_path)

    with open(list_file_path, 'wb') as list_file:
        for subdir in subdirs:
            print('\t- subdirectory ' + subdir)

        for filename in files:
            file_path = os.path.join(root, filename)

            print('\t- file %s (full path: %s)' % (filename, file_path))

            with open(file_path, 'rb') as f:
                f_content = f.read()
                list_file.write(('The file %s contains:\n' % filename).encode('utf-8'))
                list_file.write(f_content)
                list_file.write(b'\n')

If you didn't know, the with statement for files is a shorthand:

with open('filename', 'rb') as f:
    dosomething()

# is effectively the same as

f = open('filename', 'rb')
try:
    dosomething()
finally:
    f.close()

PHP mail function doesn't complete sending of e-mail

This will only affect a small handful of users, but I'd like it documented for that small handful. This member of that small handful spent 6 hours troubleshooting a working PHP mail script because of this issue.

If you're going to a university that runs XAMPP from www.AceITLab.com, you should know what our professor didn't tell us: The AceITLab firewall (not the Windows firewall) blocks MercuryMail in XAMPP. You'll have to use an alternative mail client, pear is working for us. You'll have to send to a Gmail account with low security settings.

Yes, I know, this is totally useless for real world email. However, from what I've seen, academic settings and the real world often have precious little in common.

Insert data using Entity Framework model

I'm using EF6, and I find something strange,

Suppose Customer has constructor with parameter ,

if I use new Customer(id, "name"), and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name") );
    db.SaveChanges();
 }

It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,

But if I add the curly brackets, use new Customer(id, "name"){} and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name"){} );
    db.SaveChanges();
 }

the data will then actually BE Inserted,

seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Docker official registry (Docker Hub) URL

I came across this post in search for the dockerhub repo URL when creating a dockerhub kubernetes secret.. figured id share the URL is used with success, hope that's ok.

Live Current: https://index.docker.io/v2/

Dead Orginal: https://index.docker.io/v1/

How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Most of the solutions here don't work if you're running Visual Studio 2013 and possibly 2012. Microsoft probably introduced some optimizations to make the IDE snappier, consequently they've reduced the number of cases that trigger the code generator. The following scenarios that used to work no longer do:

  1. Delete the aspx or ascx file -- No longer checks for this case
  2. Cut all the content and repaste into the aspx or ascx file -- No longer works, no change in the references
  3. Convert to Web Application -- Option no longer available
  4. Arbitrarily changing content on the aspx/ascx file -- No longer works (see 2).

The solution is surprisingly simple, but it's slightly cumbersome. In order to trigger the code generator, change something that would require the designer.aspx.cs to be generated. Changing content that doesn't affect code, such as a CSS style or adding text, won't trigger the code generator. You must change a referenced control. Here's how to do it:

In the ascx or aspx change the ID of the control

<asp:HyperLink ID="MyLink" runat="server" NavigateUrl="~/Default.aspx" Text="Home" />

to

<asp:HyperLink ID="theLINK" runat="server" NavigateUrl="~/Default.aspx" CssClass="tab" Text="Home" />

Go to the ascx.cs or aspx.cs and make sure you rename all references to "MyLink" to "theLINK" as well. Save and do build and the you should be good to go.

How to make a char string from a C macro's value?

He who is Shy* gave you the germ of an answer, but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:

#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC

#include <stdio.h>
int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.

In section 6.10.3.2 of the C standard, 'The # operator', it says:

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.

The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.

So, to achieve the effect you are after, you most certainly have to do some extra work.

#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME  FUNCTION_NAME(test_func)

#include <stdio.h>

int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR_VALUE is an idiom that is necessary to get the desired result.

#define STR_VALUE(arg)      #arg
#define FUNCTION_NAME(name) STR_VALUE(name)

#define TEST_FUNC      test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)

#include <stdio.h>

static void TEST_FUNC(void)
{
    printf("In function %s\n", TEST_FUNC_NAME);
}

int main(void)
{
    puts(TEST_FUNC_NAME);
    TEST_FUNC();
    return(0);
}

* At the time when this answer was first written, shoosh's name used 'Shy' as part of the name.

Replace characters from a column of a data frame R

You can use the stringr library:

library('stringr')

a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A_C
# 6  0.55313288 f A_C
# 7  0.31264280 g A_C
# 8  0.33759921 h A_C
# 9  0.72322599 i A_C
# 10 0.25223075 j A_C

data$c <- str_replace_all(data$c, '_', '-')

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A-C
# 6  0.55313288 f A-C
# 7  0.31264280 g A-C
# 8  0.33759921 h A-C
# 9  0.72322599 i A-C
# 10 0.25223075 j A-C

Note that this does change factored variables into character.

Can I use jQuery with Node.js?

WARNING

This solution, as mentioned by Golo Roden is not correct. It is just a quick fix to help people to have their actual jQuery code running using a Node app structure, but it's not Node philosophy because the jQuery is still running on the client side instead of on the server side. I'm sorry for giving a wrong answer.


You can also render Jade with node and put your jQuery code inside. Here is the code of the jade file:

!!! 5
html(lang="en")
  head
    title Holamundo!
    script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
  body
    h1#headTitle Hello, World
    p#content This is an example of Jade.
    script
      $('#headTitle').click(function() {
        $(this).hide();
      });
      $('#content').click(function() {
        $(this).hide();
      });

Force download a pdf link using javascript/ajax/jquery

Using Javascript you can download like this in a simple method

var oReq = new XMLHttpRequest();
// The Endpoint of your server 
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);

// Important to use the blob response type
oReq.responseType = "blob";

// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], { 
    type: 'application/pdf' 
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};

oReq.send();

What are the "standard unambiguous date" formats for string-to-date conversion in R?

In other words, is there a better solution than needing to specify the format?

Yes, there is now (ie in late 2016), thanks to anytime::anydate from the anytime package.

See the following for some examples from above:

R> anydate(c("01 Jan 2000", "01/01/2000", "2015/10/10"))
[1] "2000-01-01" "2000-01-01" "2015-10-10"
R> 

As you said, these are in fact unambiguous and should just work. And via anydate() they do. Without a format.

Post multipart request with Android SDK

Try this:

    public void SendMultipartFile() {
    Log.d(TAG, "UPLOAD: SendMultipartFile");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost( <url> );

    File file = new File("/sdcard/spider.jpg");

    Log.d(TAG, "UPLOAD: setting up multipart entity");

    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Log.d(TAG, "UPLOAD: file length = " + file.length());
    Log.d(TAG, "UPLOAD: file exist = " + file.exists());

    try {
        mpEntity.addPart("datafile", new FileBody(file, "application/octet"));
        mpEntity.addPart("id", new StringBody("1"));
    } catch (UnsupportedEncodingException e1) {
        Log.d(TAG, "UPLOAD: UnsupportedEncodingException");
        e1.printStackTrace();
    }

    httppost.setEntity(mpEntity);
    Log.d(TAG, "UPLOAD: executing request: " + httppost.getRequestLine());
    Log.d(TAG, "UPLOAD: request: " + httppost.getEntity().getContentType().toString());


    HttpResponse response;
    try {
        Log.d(TAG, "UPLOAD: about to execute");
        response = httpclient.execute(httppost);
        Log.d(TAG, "UPLOAD: executed");
        HttpEntity resEntity = response.getEntity();
        Log.d(TAG, "UPLOAD: respose code: " + response.getStatusLine().toString());
        if (resEntity != null) {
            Log.d(TAG, "UPLOAD: " + EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

When to use RDLC over RDL reports?

if you want to use report in asp.net then use .rdl if you want to use /view in report builder / report server then use .rdlc just by converting format manually it works

how to compare two elements in jquery

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

Assuming:

<div id="a" class="a"></div>

this:

$('div.a')[0] == $('div#a')[0]

returns true.

Using R to list all files with a specified extension

Peg the pattern to find "\\.dbf" at the end of the string using the $ character:

list.files(pattern = "\\.dbf$")

invalid_client in google oauth2

probably old credentials are invalid

see the answer below

stackoverflow answer

or short names may work

see the answer below stackoverflow answer

or product name same as project name as answered already

at times one may include extra space in the

check twice this line so that you are redirected to the correct url

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

Any way to break if statement in PHP?

goto:

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break...

Maximum size of an Array in Javascript

It will be very browser dependant. 100 items doesn't sound like a large number - I expect you could go a lot higher than that. Thousands shouldn't be a problem. What may be a problem is the total memory consumption.

Instagram: Share photo from webpage

As of November 17, 2015. This rule has officially changed. Instagram has deprecated the rule against using their API to upload images.

Good luck.

How to customize the back button on ActionBar

The "up" affordance indicator is provided by a drawable specified in the homeAsUpIndicator attribute of the theme. To override it with your own custom version it would be something like this:

<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
    <item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
</style>

If you are supporting pre-3.0 with your application be sure you put this version of the custom theme in values-v11 or similar.

How to change an Android app's name?

To change the name of your Android application in Android Studio or Eclipse, you have to change the value of the property android:label defined inside the <application> node in AndroidManifest.xml

 android:label="My Cool Application!"

by default the name of the application is referenced to a string defined in strings.xml file, for example:

 android:label="@string/app_name"

so, we have to change the value inside the strings.xml file:

  <string name="app_name">My Cool Application!</string>

How to add onload event to a div element

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to get current working directory using vba?

It would seem likely that the ActiveWorkbook has not been saved...

Try CurDir() instead.

http post - how to send Authorization header?

you need RequestOptions

 let headers = new Headers({'Content-Type': 'application/json'});  
 headers.append('Authorization','Bearer ')
 let options = new RequestOptions({headers: headers});
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);

for more check this link

Accessing the web page's HTTP Headers in JavaScript

Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.

Best case is to just do a HEAD request and then examine the headers.

For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html

Just my 2 cents.

How can I run code on a background thread on Android?

I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible?

Most likely mechanizm that you are looking for is AsyncTask. It directly designated for performing background process on background Thread. Also its main benefit is that offers a few methods which run on Main(UI) Thread and make possible to update your UI if you want to annouce user about some progress in task or update UI with data retrieved from background process.

If you don't know how to start here is nice tutorial:

Note: Also there is possibility to use IntentService with ResultReceiver that works as well.

Make child div stretch across width of page

you can pull it out of the flow by setting position:absolute on it, but you'll have different display issues to deal with. Or you can explicitly set the width to > 960.

What is difference between functional and imperative programming languages?

Functional Programming is a form of declarative programming, which describe the logic of computation and the order of execution is completely de-emphasized.

Problem: I want to change this creature from a horse to a giraffe.

  • Lengthen neck
  • Lengthen legs
  • Apply spots
  • Give the creature a black tongue
  • Remove horse tail

Each item can be run in any order to produce the same result.

Imperative Programming is procedural. State and order is important.

Problem: I want to park my car.

  1. Note the initial state of the garage door
  2. Stop car in driveway
  3. If the garage door is closed, open garage door, remember new state; otherwise continue
  4. Pull car into garage
  5. Close garage door

Each step must be done in order to arrive at desired result. Pulling into the garage while the garage door is closed would result in a broken garage door.

Create an enum with string values

TypeScript 2.4

Now has string enums so your code just works:

enum E {
    hello = "hello",
    world = "world"
};

TypeScript 1.8

Since TypeScript 1.8 you can use string literal types to provide a reliable and safe experience for named string values (which is partially what enums are used for).

type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay 
foo = "asdf"; // Error!

More : https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types

Legacy Support

Enums in TypeScript are number based.

You can use a class with static members though:

class E
{
    static hello = "hello";
    static world = "world"; 
}

You could go plain as well:

var E = {
    hello: "hello",
    world: "world"
}

Update: Based on the requirement to be able to do something like var test:E = E.hello; the following satisfies this:

class E
{
    // boilerplate 
    constructor(public value:string){    
    }

    toString(){
        return this.value;
    }

    // values 
    static hello = new E("hello");
    static world = new E("world");
}

// Sample usage: 
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;

console.log("First value is: "+ first);
console.log(first===third); 

How can I find the link URL by link text with XPath?

if you are using html agility pack use getattributeValue:

$doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","")

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.