Programs & Examples On #Mysql connect

The `mysql_connect` function opens a connection to a MySQL server.

Undefined function mysql_connect()

If you are getting the error as

Fatal error: Call to undefined function mysql_connect()

Kindly login to the cPanel >> Click on Select Php version >> select the extension MYSQL

Connecting to remote MySQL server using PHP

I just solved this kind of a problem. What I've learned is:

  1. you'll have to edit the my.cnf and set the bind-address = your.mysql.server.address under [mysqld]
  2. comment out skip-networking field
  3. restart mysqld
  4. check if it's running

    mysql -u root -h your.mysql.server.address –p 
    
  5. create a user (usr or anything) with % as domain and grant her access to the database in question.

    mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
    
  6. open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)

  7. restart firewall/iptables

you should be able to now connect mysql server form your client server php script.

Eclipse error: indirectly referenced from required .class files?

I got the error when I just changing some svn settings and not anything in the code. Just cleaning the projects fixed the error.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Yes, it's possible, the syntax is curl [protocol://]<host>[:port], for example:

curl example.com:1234

If you're using Bash, you can also use pseudo-device /dev files to open a TCP connection, e.g.:

exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.

See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).

What should I do if the current ASP.NET session is null?

The following statement is not entirely accurate:

"So if you are calling other functionality, including static classes, from your page, you should be fine"

I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.

As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:

There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:

[WebMethod(EnableSession = true)]

By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.

Thanks to Matthew Cosier for the solution.

Just thought I'd add my two cents.

Ed

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

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

Vue.js : How to set a unique ID for each component instance?

Update

I published the vue-unique-id Vue plugin for this on npm.

Answer

None of the other solutions address the requirement of having more than one form element in your component. Here's my take on a plugin that builds on previously given answers:

Vue.use((Vue) => {
  // Assign a unique id to each component
  let uuid = 0;
  Vue.mixin({
    beforeCreate: function() {
      this.uuid = uuid.toString();
      uuid += 1;
    },
  });

  // Generate a component-scoped id
  Vue.prototype.$id = function(id) {
    return "uid-" + this.uuid + "-" + id;
  };
});

This doesn't rely on the internal _uid property which is reserved for internal use.

Use it like this in your component:

<label :for="$id('field1')">Field 1</label>
<input :id="$id('field1')" type="text" />

<label :for="$id('field2')">Field 2</label>
<input :id="$id('field2')" type="text" />

To produce something like this:

<label for="uid-42-field1">Field 1</label>
<input id="uid-42-field1" type="text" />

<label for="uid-42-field2">Field 2</label>
<input id="uid-42-field2" type="text" />

Check whether a cell contains a substring

For those who would like to do this using a single function inside the IF statement, I use

=IF(COUNTIF(A1,"*TEXT*"),TrueValue,FalseValue)

to see if the substring TEXT is in cell A1

[NOTE: TEXT needs to have asterisks around it]

How to replace part of string by position?

The easiest way to add and remove ranges in a string is to use the StringBuilder.

var theString = "ABCDEFGHIJ";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2);
aStringBuilder.Insert(3, "ZX");
theString = aStringBuilder.ToString();

An alternative is to use String.Substring, but I think the StringBuilder code gets more readable.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

Passing data to a jQuery UI Dialog

Ok the first issue with the div tag was easy enough: I just added a style="display:none;" to it and then before showing the dialog I added this in my dialog script:

$("#dialog").css("display", "inherit");

But for the post version I'm still out of luck.

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

If you have a wamp setup that won't send emails, there is only a couple of things to do. 1. find out what the smtp server name is for your isp. The gmail thing is most likely unnecessary complication 2. create a phpsetup.php file in your 'www' folder and edit like this:

<?php
   phpinfo();
?>

this will give you a handle on what wamp is using. 3. search for the php.ini file. there may be serveral. The one you want is the one that effects the output of the file above. 4. find the smtp address in the most likely php.ini. 5. Type in your browser localhost/phpsetup.php and scroll down to smtp setting. it should say 'localhost' 6. edit the php.ini file smtp setting to the name of your ISPs smtp server. check if it changes for you phpsetup.php. if it works your done, if not you are working the wrong file.

this issue should be on the Wordpress site but they are way too up-them-selves or trying to get clients.;)

Is it possible to simulate key press events programmatically?

Here's a library that really helps: https://cdn.rawgit.com/ccampbell/mousetrap/2e5c2a8adbe80a89050aaf4e02c45f02f1cc12d4/tests/libs/key-event.js

I don't know from where did it came from, but it is helpful. It adds a .simulate() method to window.KeyEvent, so you use it simply with KeyEvent.simulate(0, 13) for simulating an enter or KeyEvent.simulate(81, 81) for a 'Q'.

I got it at https://github.com/ccampbell/mousetrap/tree/master/tests.

Define static method in source-file with declaration in header-file in C++

Static member functions must refer to static variables of that class. So in your case,

static void CP_StringToPString( std::string& inString, unsigned char *outString);

Since your member function CP_StringToPstring is static, the parameters in that function, inString and outString should be declared as static too.

The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.

You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.

Column standard deviation R

The package fBasics has a function colStdevs

 require('fBasics')
 set.seed(123)
 colStdevs(matrix(rnorm(1000, mean=10, sd=1), ncol=5))
[1] 0.9431599 0.9959210 0.9648052 1.0246366 1.0351268

Ball to Ball Collision - Detection and Handling

Improving the solution to detect circle with circle collision detection given within the question:

float dx = circle1.x - circle2.x,
      dy = circle1.y - circle2.y,
       r = circle1.r + circle2.r;
return (dx * dx + dy * dy <= r * r);

It avoids the unnecessary "if with two returns" and the use of more variables than necessary.

<!--[if !IE]> not working

The Microsoft-recommended syntax for downlevel-revealed conditional “comments” is this:

<![if !IE]>
<link type="text/css" rel="stylesheet" href="/stylesheets/no-ie.css" />
<![endif]>

These aren’t comments, but they work properly.

How to identify numpy types in python?

Note that the type(numpy.ndarray) is a type itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.

See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy

>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True

Fun with booleans:

>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool  # python equivalent
True

More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in

>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True  # generic integer
>>> isinstance(x[0], int)
False  # but not a python int in this case

# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind                                                                                           
'b'
>>> np.dtype('int64').kind                                                                                          
'i'
>>> np.dtype('float').kind                                                                                          
'f'
>>> np.dtype('half').kind                                                                                           
'f'

# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False

# Down these paths there be dragons:

# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False  
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False  # again, confusing the .dtype with a specific dtype


# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:

>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False  # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False  # oh boy
>>> x[0].dtype == np.int
False  # ya, no luck here either
>>> x[0].dtype == np.int_
False  # or here
>>> x[0].dtype == np.uint64
True  # have to end on a good note!

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Subtle point here...

There is an implicit typecast for i+j when j is a double and i is an int. Java ALWAYS converts an integer into a double when there is an operation between them.

To clarify i+=j where i is an integer and j is a double can be described as

i = <int>(<double>i + j)

See: this description of implicit casting

You might want to typecast j to (int) in this case for clarity.

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

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

I had a similar problem. But I was working with Episerver locally with ssl enabled. When I wasn't getting a

Server Error in '/' Application.

I was getting a Insecure connection error. In the end, for me, this post on PluralSight together with configuring the website urls, accordingly with the ssl link set up on the project's config, on Admin's Manage Website's screen solved the problem.

Format decimal for percentage values?

If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.

For example, to get a decimal value with a trailing "%" and no space between the value and the "%":

myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });

More complete example:

using System.Globalization; 

...

decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)

Python function attributes - uses and abuses

I've used them as static variables for a function. For example, given the following C code:

int fn(int i)
{
    static f = 1;
    f += i;
    return f;
}

I can implement the function similarly in Python:

def fn(i):
    fn.f += i
    return fn.f
fn.f = 1

This would definitely fall into the "abuses" end of the spectrum.

How do you store Java objects in HttpSession?

The request object is not the session.

You want to use the session object to store. The session is added to the request and is were you want to persist data across requests. The session can be obtained from

HttpSession session = request.getSession(true);

Then you can use setAttribute or getAttribute on the session.

A more up to date tutorial on jsp sessions is: http://courses.coreservlets.com/Course-Materials/pdf/csajsp2/08-Session-Tracking.pdf

What is an Endpoint?

The endpoint of the term is the URL that is focused on creating a request. Take a look at the following examples from different points:

/api/groups/6/workings/1
/api/v2/groups/5/workings/2
/api/workings/3

They can clearly access the same source in a given API.

How to change the sender's name or e-mail address in mutt?

before you send the email you can press <ESC> f (Escape followed by f) to change the From: Address.

Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!

Replace all whitespace with a line break/paragraph mark to make a word list

The portable way to do this is:

sed -e 's/[ \t][ \t]*/\
/g'

That's an actual newline between the backslash and the slash-g. Many sed implementations don't know about \n, so you need a literal newline. The backslash before the newline prevents sed from getting upset about the newline. (in sed scripts the commands are normally terminated by newlines)

With GNU sed you can use \n in the substitution, and \s in the regex:

sed -e 's/\s\s*/\n/g'

GNU sed also supports "extended" regular expressions (that's egrep style, not perl-style) if you give it the -r flag, so then you can use +:

sed -r -e 's/\s+/\n/g'

If this is for Linux only, you can probably go with the GNU command, but if you want this to work on systems with a non-GNU sed (eg: BSD, Mac OS-X), you might want to go with the more portable option.

How does one generate a random number in Apple's Swift language?

 let MAX : UInt32 = 9
 let MIN : UInt32 = 1

    func randomNumber()
{
    var random_number = Int(arc4random_uniform(MAX) + MIN)
    print ("random = ", random_number);
}

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

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

Demo 1

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

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

Demo 2

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

Demo 3

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

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

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

CentOS: Copy directory to another directory

For copy directory use following command

cp -r source    Destination

For example

cp -r  /home/hasan   /opt 

For copy file use command without -r

cp   /home/file    /home/hasan/

Which version of Python do I have installed?

Although the question is "which version am I using?", this may not actually be everything you need to know. You may have other versions installed and this can cause problems, particularly when installing additional modules. This is my rough-and-ready approach to finding out what versions are installed:

updatedb                  # Be in root for this
locate site.py            # All installations I've ever seen have this

The output for a single Python installation should look something like this:

/usr/lib64/python2.7/site.py
/usr/lib64/python2.7/site.pyc
/usr/lib64/python2.7/site.pyo

Multiple installations will have output something like this:

/root/Python-2.7.6/Lib/site.py
/root/Python-2.7.6/Lib/site.pyc
/root/Python-2.7.6/Lib/site.pyo
/root/Python-2.7.6/Lib/test/test_site.py
/usr/lib/python2.6/site-packages/site.py
/usr/lib/python2.6/site-packages/site.pyc
/usr/lib/python2.6/site-packages/site.pyo
/usr/lib64/python2.6/site.py
/usr/lib64/python2.6/site.pyc
/usr/lib64/python2.6/site.pyo
/usr/local/lib/python2.7/site.py
/usr/local/lib/python2.7/site.pyc
/usr/local/lib/python2.7/site.pyo
/usr/local/lib/python2.7/test/test_site.py
/usr/local/lib/python2.7/test/test_site.pyc
/usr/local/lib/python2.7/test/test_site.pyo

How do I convert an interval into a number of hours with postgres?

select floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600)), count(*)
from od_a_week
group by floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600));

The ::int conversion follows the principle of rounding. If you want a different result such as rounding down, you can use the corresponding math function such as floor.

Call async/await functions in parallel

I create a helper function waitAll, may be it can make it sweeter. It only works in nodejs for now, not in browser chrome.

    //const parallel = async (...items) => {
    const waitAll = async (...items) => {
        //this function does start execution the functions
        //the execution has been started before running this code here
        //instead it collects of the result of execution of the functions

        const temp = [];
        for (const item of items) {
            //this is not
            //temp.push(await item())
            //it does wait for the result in series (not in parallel), but
            //it doesn't affect the parallel execution of those functions
            //because they haven started earlier
            temp.push(await item);
        }
        return temp;
    };

    //the async functions are executed in parallel before passed
    //in the waitAll function

    //const finalResult = await waitAll(someResult(), anotherResult());
    //const finalResult = await parallel(someResult(), anotherResult());
    //or
    const [result1, result2] = await waitAll(someResult(), anotherResult());
    //const [result1, result2] = await parallel(someResult(), anotherResult());

How to print the contents of RDD?

Instead of typing each time, you can;

[1] Create a generic print method inside Spark Shell.

def p(rdd: org.apache.spark.rdd.RDD[_]) = rdd.foreach(println)

[2] Or even better, using implicits, you can add the function to RDD class to print its contents.

implicit class Printer(rdd: org.apache.spark.rdd.RDD[_]) {
    def print = rdd.foreach(println)
}

Example usage:

val rdd = sc.parallelize(List(1,2,3,4)).map(_*2)

p(rdd) // 1
rdd.print // 2

Output:

2
6
4
8

Important

This only makes sense if you are working in local mode and with a small amount of data set. Otherwise, you either will not be able to see the results on the client or run out of memory because of the big dataset result.

Where can I get Google developer key

You should be able to generate a Youtube API key there.

The recommended way to authorize your API call is to use OAuth 2.0 (without API key), as pointed by the documentation an API key is only necessary when using OAuth 1.0 credentials.

The API key for your application can be found in the Google APIs Console in API Access > Simple API.

Why does Node.js' fs.readFile() return a buffer instead of string?

The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

data.toString('ascii', 0, data.length)

Asynchronously:

fs.readFile('test.txt', 'utf8', function (error, data) {
    if (error) throw error;
    console.log(data.toString());
});

Pass array to where in Codeigniter Active Record

From the Active Record docs:

$this->db->where_in();

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

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

  1. The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.

  2. The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)


<div>
    <canvas id="chartDiv" height="400" width="600"></canvas>
    <div id="legendDiv"></div>
</div>

<script>
   var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "The Flash's Speed",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Superman's Speed",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
    document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>

How can I convert an image into a Base64 string?

byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);

Have a reloadData for a UITableView animate when changing

Native UITableView animations in Swift

Insert and delete rows all at once with tableView.performBatchUpdates so they occur simultaneously. Building on the answer from @iKenndac use methods such as:

  • tableView.insertSections
  • tableView.insertRows
  • tableView.deleteSections
  • tableView.deleteRows

Ex:

 tableView.performBatchUpdates({
   tableView.insertSections([0], with: .top)
 })

This inserts a section at the zero position with an animation that loads from the top. This will re-run the cellForRowAt method and check for a new cell at that position. You could reload the entire table view this way with specific animations.

Re: the OP question, a conditional flag would have been needed to show the cells for the alternate table view state.

Android "elevation" not showing a shadow

one other thing that you should be aware of, shadows will not show if you have this line in the manifest:

android:hardwareAccelerated="false"

I tried all of the suggested stuff but it only worked for me when i removed the line, the reason i had the line was because my app works with a number of bitmap images and they were causing the app to crash.

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

The fetchSize parameter is a hint to the JDBC driver as to many rows to fetch in one go from the database. But the driver is free to ignore this and do what it sees fit. Some drivers, like the Oracle one, fetch rows in chunks, so you can read very large result sets without needing lots of memory. Other drivers just read in the whole result set in one go, and I'm guessing that's what your driver is doing.

You can try upgrading your driver to the SQL Server 2008 version (which might be better), or the open-source jTDS driver.

Include another HTML file in a HTML file

Shameless plug of a library that I wrote the solve this.

https://github.com/LexmarkWeb/csi.js

<div data-include="/path/to/include.html"></div>

The above will take the contents of /path/to/include.html and replace the div with it.

What is the current directory in a batch file?

From within your batch file:

  • %cd% refers to the current working directory (variable)
  • %~dp0 refers to the full path to the batch file's directory (static)
  • %~dpnx0 and %~f0 both refer to the full path to the batch directory and file name (static).

See also: What does %~dp0 mean, and how does it work?

How can I find the OWNER of an object in Oracle?

I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.

To find the owner of a specific table in an Oracle DB, use the following query:

select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';

Group dataframe and get sum AND count?

Just in case you were wondering how to rename columns during aggregation, here's how for

pandas >= 0.25: Named Aggregation

df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')

Or,

df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))

                       MySum  MyCount
Company Name                       
Vifor Pharma UK Ltd  4207.93        5

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

All error codes are on "CFNetwork Errors Codes References" on the documentation (link)

A small extraction for CFURL and CFURLConnection Errors:

  kCFURLErrorUnknown   = -998,
  kCFURLErrorCancelled = -999,
  kCFURLErrorBadURL    = -1000,
  kCFURLErrorTimedOut  = -1001,
  kCFURLErrorUnsupportedURL = -1002,
  kCFURLErrorCannotFindHost = -1003,
  kCFURLErrorCannotConnectToHost    = -1004,
  kCFURLErrorNetworkConnectionLost  = -1005,
  kCFURLErrorDNSLookupFailed        = -1006,
  kCFURLErrorHTTPTooManyRedirects   = -1007,
  kCFURLErrorResourceUnavailable    = -1008,
  kCFURLErrorNotConnectedToInternet = -1009,
  kCFURLErrorRedirectToNonExistentLocation = -1010,
  kCFURLErrorBadServerResponse             = -1011,
  kCFURLErrorUserCancelledAuthentication   = -1012,
  kCFURLErrorUserAuthenticationRequired    = -1013,
  kCFURLErrorZeroByteResource        = -1014,
  kCFURLErrorCannotDecodeRawData     = -1015,
  kCFURLErrorCannotDecodeContentData = -1016,
  kCFURLErrorCannotParseResponse     = -1017,
  kCFURLErrorInternationalRoamingOff = -1018,
  kCFURLErrorCallIsActive               = -1019,
  kCFURLErrorDataNotAllowed             = -1020,
  kCFURLErrorRequestBodyStreamExhausted = -1021,
  kCFURLErrorFileDoesNotExist           = -1100,
  kCFURLErrorFileIsDirectory            = -1101,
  kCFURLErrorNoPermissionsToReadFile    = -1102,
  kCFURLErrorDataLengthExceedsMaximum   = -1103,

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

We found a different solution to a problem with the same symptom:

We saw this error when we updated the project from .net 4.7.1 to 4.7.2.

The problem was that even though we were not referencing System.Net.Http any more in the project, it was listed in the dependentAssembily section of our web.config. Removing this and any other unused assembly references from the web.config solved the problem.

Removing duplicate rows in Notepad++

You may need a plugin to do this. You can try the command line cc.ddl(delete duplicate lines) of ConyEdit. It is a cross-editor plugin for the text editors, including Notepad++.

With ConyEdit running in background, follow the steps below:

  1. enter the command line cc.ddl at the end of the text.
  2. copy the text and the command line.
  3. paste, then you will see what you want.

Example
enter image description here

Which loop is faster, while or for?

That will depend on the language implementation of said loop, compiler and what not.

Most compiler will compile to the exact same executable code for example in CIL (.NET) they definitely do.

Source: vcsjones @ http://forums.asp.net/t/1041090.aspx

Either way, the body of the loop is where the processing time will be spent not the way you iterate.

How to make a vertical SeekBar in Android?

I used Selva's solution but had two kinds of issues:

  • OnSeekbarChangeListener did not work properly
  • Setting progress programmatically did not work properly.

I fixed these two issues. You can find the solution (within my own project package) at

https://github.com/jeisfeld/Augendiagnose/blob/master/AugendiagnoseIdea/augendiagnoseLib/src/main/java/de/jeisfeld/augendiagnoselib/components/VerticalSeekBar.java

100% width background image with an 'auto' height

It's 2017, and now you can use object-fit which has decent support. It works in the same way as a div's background-size but on the element itself, and on any element including images.

.your-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

Jquery to get SelectedText from dropdown

I had the same problem yesterday :-)

$("#SelectedCountryId option:selected").text()

I also read that this is slow, if you want to use it often you should probably use something else.

I don't know why yours is not working, this one is for me, maybe someone else can help...

Get week of year in JavaScript like in PHP

Accordily http://javascript.about.com/library/blweekyear.htm

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    var millisecsInDay = 86400000;
    return Math.ceil((((this - onejan) /millisecsInDay) + onejan.getDay()+1)/7);
};

How to use radio buttons in ReactJS?

To build upon ChinKang said for his answer, I have a more dry'er approach and in es6 for those interested:

class RadioExample extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedRadio: 'public'
    };
  }

  handleRadioChange = (event) => {
    this.setState({
      selectedRadio: event.currentTarget.value
    })
  };

  render() {
    return (
      <div className="radio-row">
        <div className="input-row">
          <input
            type="radio"
            name="public"
            value="public"
            checked={this.state.selectedRadio === 'public'}
            onChange={this.handleRadioChange}
          />
          <label htmlFor="public">Public</label>
        </div>
        <div className="input-row">
          <input
            type="radio"
            name="private"
            value="private"
            checked={this.state.selectedRadio === 'private'}
            onChange={this.handleRadioChange}
          />
          <label htmlFor="private">Private</label>
        </div>
      </div>
    )
  }
}

except this one would have a default checked value.

Retrofit 2.0 how to get deserialised error response.body

Create a model of the Error response & user Gson to convert the response to it. This will just work fine.

APIError.java

public class APIError {
    private String message;

    public String getMessage() {
        return message;
    }
}

MainActivity.java (inside request onResponse)

if (response.isSuccessful()) {
    // Do your success stuff...

} else {
    APIError message = new Gson().fromJson(response.errorBody().charStream(), APIError.class);
    Toast.makeText(MainActivity.this, "" + message.getMessage(), Toast.LENGTH_SHORT).show();
}

How do I use cx_freeze?

I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:

from cx_Freeze import setup, Executable
import sys

productName = "ProductName"
if 'bdist_msi' in sys.argv:
    sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
    sys.argv += ['--install-script', 'install.py']

exe = Executable(
      script="main.py",
      base="Win32GUI",
      targetName="Product.exe"
     )
setup(
      name="Product.exe",
      version="1.0",
      author="Me",
      description="Copyright 2012",
      executables=[exe],
      scripts=[
               'install.py'
               ]
      ) 

Observable.of is not a function

If anybody is having this problem while using Angular 6/rxjs 6 see the answers here: Could not use Observable.of in RxJs 6 and Angular 6

In short, you need to import it like this:

import { of } from 'rxjs';

And then instead of calling

Observable.of(res);

just use

of(res);

How to stop line breaking in vim

I personnally went for:

  • set wrap,
  • set linebreak
  • set breakindent
  • set showbreak=?.

Some explanation:

  • wrap option visually wraps line instead of having to scroll horizontally
  • linebreak is for wrapping long lines at a specific character instead of just anywhere when the line happens to be too long, like in the middle of a word. By default, it breaks on whitespace (word separator), but you can configure it with breakat. It also does NOT insert EOL in the file as the OP wanted.
  • breakat is the character where it will visually break the line. No need to modify it if you want to break at whitespace between two words.
  • breakindent enables to visually indent the line when it breaks.
  • showbreak enables to set the character which indicates this break.

See :h <keyword> within vim for more info.

Note that you don't need to modify textwidth nor wrapmargin if you go this route.

Could not load file or assembly 'System.Data.SQLite'

I have a 64 bit dev machine and 32 bit build server. I used this code prior to NHibernate initialisation. Works a charm on any architecture (well the 2 I have tested)

Hope this helps someone.

Guido

        private static void LoadSQLLiteAssembly()
        {
            Uri dir = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            FileInfo fi = new FileInfo(dir.AbsolutePath);           
            string binFile = fi.Directory.FullName + "\\System.Data.SQLite.DLL";
            if (!File.Exists(binFile)) File.Copy(GetAppropriateSQLLiteAssembly(), binFile, false);
        }

        private static string GetAppropriateSQLLiteAssembly()
        {
            string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
            string arch = ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? "32" : "64");
            return GetLibsDir() + "\\NUnit\\System.Data.SQLite.x" + arch + ".DLL";
        }

Make a number a percentage

((portion/total) * 100).toFixed(2) + '%'

How to step through Python code to help debug issues?

If you come from Java/C# background I guess your best bet would be to use Eclipse with Pydev. This gives you a fully functional IDE with debugger built in. I use it with django as well.

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

List<String> listA = new ArrayList<String>();

    listA.add("A");
    listA.add("B");

List<String> listB = new ArrayList<String>();

    listB.add("B");
    listB.add("C");

Set<String> newSet = new HashSet<String>(listA);

    newSet.addAll(listB);
List<String> newList = new ArrayList<String>(newSet);

System.out.println("New List :"+newList);

is giving you New List :[A, B, C]

Get the Last Inserted Id Using Laravel Eloquent

Use insertGetId to insert and get inserted id at the same time

From doc

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

By Model

$id = Model::insertGetId(["name"=>"Niklesh","email"=>"[email protected]"]);

By DB

$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"[email protected]"]);

For more details : https://laravel.com/docs/5.5/queries#inserts

Display Images Inline via CSS

Place this css in your page:

<style>
   #client_logos {
    display: inline-block;
    width:100%;
    }
  </style>

Replace

<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>

To

<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>

How to export table as CSV with headings on Postgresql?

instead of just table name, you can also write a query for getting only selected column data.

COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;

with admin privilege

\COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;

Cannot find the '@angular/common/http' module

You should import http from @angular/http in your service:

import {Http} from '@angular/http';

constructor(private http: http) {} // <--Then Inject it here


// now you can use it in any function eg:
getUsers() {
    return this.http.get('whateverURL');
}

java.lang.ClassNotFoundException: HttpServletRequest

I had the same problem, and the cause was the missing of commons-logging-1.2.jar

I add it to the lib folder, then my Apache Tomcat 7 server executed without problems.

Delete a database in phpMyAdmin

  1. Connect to your localhost.
  2. Open your favorite browser.
  3. Make sure your localhost is working.
  4. Type in url= localhost.
  5. Scroll down click on phpadmin once phpadmin is open.
  6. Click on database.
  7. Mark check the database you want remove.
  8. Click on drop.

If this don't work

  1. Click on database go to operation
  2. Click drop database

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Try to use mousemove event lisentner

var audio = document.createElement("AUDIO")
document.body.appendChild(audio);
audio.src = "./audio/rain.m4a"

document.body.addEventListener("mousemove", function () {
    audio.play()
})

Autowiring fails: Not an managed Type

In spring boot I get same exception by using CrudRepository because I forgot to set generic types. I want to write it here in case it helps someone.

errorneous definition:

public interface OctopusPropertiesRepository extends CrudRepository

error:

Caused by: java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object

successfull definition:

public interface OctopusPropertiesRepository extends CrudRepository<OctopusProperties,Long>{

Side-by-side plots with ggplot2

Using the patchwork package, you can simply use + operator:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


p1 + p2

patchwork

Other operators include / to stack plots to place plots side by side, and () to group elements. For example you can configure a top row of 3 plots and a bottom row of one plot with (p1 | p2 | p3) /p. For more examples, see the package documentation.

Submit form using <a> tag

Submit your form like this ...

Your HTML code

    <form name="myform" action="handle-data.php"> Search: <input type='text' name='query' />
     <a href="javascript: submitform()">Search</a> 
   </form> 

JavaScript Code

  <script type="text/javascript"> 
        function submitform() {   document.myform.submit(); } 
   </script> 

How to use If Statement in Where Clause in SQL?

You have to use CASE Statement/Expression

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
AND    
    (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
AND 
     CASE @Value
         WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL) 
         WHEN 3 THEN (CASE WHEN I.RecurringCharge like 
                               '%'+cast(@Total as varchar(50))+'%' 
                     or @Total is NULL )
     END

Where does PHP's error log reside in XAMPP?

\xampp\apache\logs\error.log, where xampp is your installation folder. If you haven't changed the error_log setting in PHP (check with phpinfo()), it will be logged to the Apache log.

Is it possible to apply CSS to half of a character?

It may be irrelevant, maybe not, but sometime ago, I created a jQuery function that does the same thing, but horizontally.

I called it "Strippex" For 'stripe'+'text', demo : http://cdpn.io/FcIBg

I'm not saying this is the solution of any problems, but I already tried to apply css to half of a character, but horizontally, So the idea is the same, the realisation may be horrible, but it works.

Ah, and the most important, I had fun creating it !

enter image description here

How to specify preference of library path?

This is an old question, but no one seems to have mentioned this.

You were getting lucky that the thing was linking at all.

You needed to change

g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp

to this:

g++ -g -Wall -o my_binary -L/my/dir bar.cpp -lfoo

Your linker keeps track of symbols it needs to resolve. If it reads the library first, it doesn't have any needed symbols, so it ignores the symbols in it. Specify the libraries after the things that need to link to them so that your linker has symbols to find in them.

Also, -lfoo makes it search specifically for a file named libfoo.a or libfoo.so as needed. Not libfoo.so.0. So either ln the name or rename the library as appopriate.

To quote the gcc man page:

-l library
   ...
   It makes a difference where in the command you 
   write this option; the linker searches and processes 
   libraries and object files in the order they are 
   specified.  Thus, foo.o -lz bar.o searches library z 
   after file foo.o but before bar.o.  If bar.o refers 
   to functions in z, those functions may not be loaded.

Adding the file directly to g++'s command line should have worked, unless of course, you put it prior to bar.cpp, causing the linker to ignore it for lacking any needed symbols, because no symbols were needed yet.

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Getting current unixtimestamp using Moment.js

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

How do I set default values for functions parameters in Matlab?

I like to do this in a somewhat more object oriented way. Before calling wave() save some of your arguments within a struct, eg. one called parameters:

parameters.flag =42;
parameters.fTrue =1;
wave(a,b,n,k,T,f,parameters);

Within the wave function then check, whether the struct parameters contains a field called 'flag' and if so, if its value is non empty. Then assign it eighter a default value you define before, or the value given as an argument in the parameters struct:

function output = wave(a,b,n,k,T,f,parameters)
  flagDefault=18;
  fTrueDefault=0;
  if (isfield(parameters,'flag') == 0 || isempty(parameters.flag)),flag=flagDefault;else flag=parameters.flag; end
  if (isfield(parameter,'fTrue') == 0 || isempty(parameters.fTrue)),fTrue=fTrueDefault;else fTrue=parameters.fTrue; end
  ...
end

This makes it easier to handle large numbers of arguments, because it does not depend on the order of the given arguments. That said, it is also helpful if you have to add more arguments later, because you don't have to change the functions signature to do so.

How do I get the current date in Cocoa

CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%2.0f", currentDate.hour, currentDate.minute, currentDate.second];

Mark was right this code is MUCH more efficient to manage dates hours min and secs. But he forgot the @ at the beginning of format string declaration.

Is it possible to convert char[] to char* in C?

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:

int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
    buf[i] = (int*) malloc(N * sizeof(int));

and then you can reference buf[3][5] or whatever.

HTML form submit to PHP script

Assuming you've fixed the syntax errors (you've closed the select box before the name attribute), you're using the same name for the select box as the submit button. Give the select box a different name.

How to search for a string in cell array in MATLAB?

The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))

Change a web.config programmatically with C# (.NET)

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();

How to find if an array contains a specific string in JavaScript/jQuery?

jQuery offers $.inArray:

Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Edit 3.5 years later

$.inArray is effectively a wrapper for Array.prototype.indexOf in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_


Edit another 3 years later

Gosh, 6.5 years?!

The best option for this in modern Javascript is Array.prototype.includes:

var found = categories.includes('specialword');

No comparisons and no confusing -1 results. It does what we want: it returns true or false. For older browsers it's polyfillable using the code at MDN.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_

How to change the timeout on a .NET WebClient object

According to kisp solution this is my edited version working async:

Class WebConnection.cs

internal class WebConnection : WebClient
{
    internal int Timeout { get; set; }

    protected override WebRequest GetWebRequest(Uri Address)
    {
        WebRequest WebReq = base.GetWebRequest(Address);
        WebReq.Timeout = Timeout * 1000 // Seconds
        return WebReq;
    }
}

The async Task

private async Task GetDataAsyncWithTimeout()
{
    await Task.Run(() =>
    {
        using (WebConnection webClient = new WebConnection())
        {
            webClient.Timeout = 5; // Five seconds
            webClient.DownloadData("https://www.yourwebsite.com");
        }
    });
} // await GetDataAsyncWithTimeout()

Else, if you don't want to use async:

private void GetDataSyncWithTimeout()
{
    using (WebConnection webClient = new WebConnection())
    {
        webClient.Timeout = 5; // Five seconds
        webClient.DownloadData("https://www.yourwebsite.com");
    }
} // GetDataSyncWithTimeout()

Double border with different color

Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:

_x000D_
_x000D_
body {_x000D_
  background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
  background-repeat: no-repeat;_x000D_
  height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
  background-color: #ccc;_x000D_
  border: 4px solid #fff;_x000D_
  padding: 2em;_x000D_
  width: 16em;_x000D_
  height: 16em;_x000D_
  position: relative;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
.double-border:before {_x000D_
  background: none;_x000D_
  border: 4px solid #fff;_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 4px;_x000D_
  left: 4px;_x000D_
  right: 4px;_x000D_
  bottom: 4px;_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div class="double-border">_x000D_
  <!-- Content -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you want borders that are consecutive to each other (no space between them), you can use multiple box-shadow declarations (separated by commas) to do so:

_x000D_
_x000D_
body {_x000D_
  background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
  background-repeat: no-repeat;_x000D_
  height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
  background-color: #ccc;_x000D_
  border: 4px solid #fff;_x000D_
  box-shadow:_x000D_
    inset 0 0 0 4px #eee,_x000D_
    inset 0 0 0 8px #ddd,_x000D_
    inset 0 0 0 12px #ccc,_x000D_
    inset 0 0 0 16px #bbb,_x000D_
    inset 0 0 0 20px #aaa,_x000D_
    inset 0 0 0 20px #999,_x000D_
    inset 0 0 0 20px #888;_x000D_
  /* And so on and so forth, if you want border-ception */_x000D_
  margin: 0 auto;_x000D_
  padding: 3em;_x000D_
  width: 16em;_x000D_
  height: 16em;_x000D_
  position: relative;_x000D_
}
_x000D_
<div class="double-border">_x000D_
  <!-- Content -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Select rows of a matrix that meet a condition

If your matrix is called m, just use :

R> m[m$three == 11, ]

'adb' is not recognized as an internal or external command, operable program or batch file

In my case it was:

C:\Program Files (x86)\Android\android-sdk\platform-tools

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

How can I generate Unix timestamps?

In Haskell...

To get it back as a POSIXTime type:

import Data.Time.Clock.POSIX
getPOSIXTime

As an integer:

import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime

Easiest way to loop through a filtered list with VBA?

Suppose I have numbers 1 to 10 in cells A2:A11 with my autofilter in A1. I now filter to only show numbers greater then 5 (i.e. 6, 7, 8, 9, 10).

This code will only print visible cells:

Sub SpecialLoop()
    Dim cl As Range, rng As Range

    Set rng = Range("A2:A11")

    For Each cl In rng
        If cl.EntireRow.Hidden = False Then //Use Hidden property to check if filtered or not
            Debug.Print cl
        End If
    Next

End Sub

Perhaps there is a better way with SpecialCells but the above worked for me in Excel 2003.

EDIT

Just found a better way with SpecialCells:

Sub SpecialLoop()
    Dim cl As Range, rng As Range

    Set rng = Range("A2:A11")

    For Each cl In rng.SpecialCells(xlCellTypeVisible)
        Debug.Print cl
    Next cl

End Sub

Add days Oracle SQL

In a more general way you can use "INTERVAL". Here some examples:

1) add a day

select sysdate + INTERVAL '1' DAY from dual;

2) add 20 days

select sysdate + INTERVAL '20' DAY from dual;

2) add some minutes

select sysdate + INTERVAL '15' MINUTE from dual;

Soft hyphen in HTML (<wbr> vs. &shy;)

I use &shy;, inserted manually where necessary.

I always find it a pity that people don’t use techniques because there is some—maybe old or strange—browser around which doesn’t handle them the way they were specified. I found that &shy; is working properly in both recent Internet Explorer and Firefox browsers, that should be enough. You may include a browser check telling people to use something mature or continue at their own risk if they come around with some strange browser.

Syllabification isn’t that easy and I cannot recommend leaving it to some Javascript. It’s a language specific topic and may need to be carefully revised by the deskman if you don’t want it to turn your text irritating. Some languages, such as German, form compound words and are likely to lead to decomposition problems. E.g. Spargelder (germ. saved money, pl.) may, by syllabification rules, be wrapped in two places (Spar-gel-der). However, wrapping it in the second position, turns the first part to show up as Spargel- (germ. asparagus), activating a completely misleading concept in the head of the reader and therefore shoud be avoided.

And what about the string Wachstube? It could either mean ‘guardroom’ (Wach-stu-be) or ‘tube of wax’ (Wachs-tu-be). You may probably find other examples in other languages as well. You should aim to provide an environment in which the deskman can be supported in creating a well-syllabified text, proof-reading every critical word.

Why is there no Char.Empty like String.Empty?

There's no such thing as an empty char. The closest you can get is '\0', the Unicode "null" character. Given that you can embed that within string literals or express it on its own very easily, why would you want a separate field for it? Equally, the "it's easy to confuse "" and " "" arguments don't apply for '\0'.

If you could give an example of where you'd want to use it and why you think it would be better, that might help...

Update statement with inner join on Oracle

Just as a matter of completeness, and because we're talking Oracle, this could do it as well:

declare
begin
  for sel in (
    select table2.code, table2.desc
    from table1
    join table2 on table1.value = table2.desc
    where table1.updatetype = 'blah'
  ) loop
    update table1 
    set table1.value = sel.code
    where table1.updatetype = 'blah' and table1.value = sel.desc;    
  end loop;
end;
/

Bad Request - Invalid Hostname IIS7

Double check the exact URL you're providing. I saw this error when I missed off the route prefix defined in ASP.NET so it didn't know where to route the request.

Should I use Java's String.format() if performance is important?

Java's String.format works like so:

  1. it parses the format string, exploding into a list of format chunks
  2. it iterates the format chunks, rendering into a StringBuilder, which is basically an array that resizes itself as necessary, by copying into a new array. this is necessary because we don't yet know how large to allocate the final String
  3. StringBuilder.toString() copies his internal buffer into a new String

if the final destination for this data is a stream (e.g. rendering a webpage or writing to a file), you can assemble the format chunks directly into your stream:

new PrintStream(outputStream, autoFlush, encoding).format("hello {0}", "world");

I speculate that the optimizer will optimize away the format string processing. If so, you're left with equivalent amortized performance to manually unrolling your String.format into a StringBuilder.

jQuery/JavaScript: accessing contents of an iframe

If the iframe src is from another domain you can still do it. You need to read the external page into PHP and echo it from your domain. Like this:

iframe_page.php

<?php
    $URL = "http://external.com";

    $domain = file_get_contents($URL);

    echo $domain;
?>

Then something like this:

display_page.html

<html>
<head>
  <title>Test</title>
 </head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script>

$(document).ready(function(){   
    cleanit = setInterval ( "cleaning()", 500 );
});

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        clearInterval(cleanit);
        $('#selector').contents().find('.Link').html('ideate tech');
    }
}

</script>

<body>
<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>
</body>
</html>

The above is an example of how to edit an external page through an iframe without the access denied etc...

Installing NumPy and SciPy on 64-bit Windows (with Pip)

You can now pip install numpy on Windows!

"Note: this page has only historical relevance, you can now pip-install for windows" Source: https://github.com/numpy/numpy/wiki/Whats-with-Windows-builds

Error when deploying an artifact in Nexus

In the rare event that you need to redeploy the SAME STABLE artifact to Nexus, it will fail by default. If you then delete the artifact from Nexus (via the web interface) for the purpose of deploying it again, the deploy will still fail, since just removing the e.g. jar or pom does not clear other files still laying around in the directory. You need to log onto the box and delete the directory in its entirety.

c++ string array initialization

In C++11 and above, you can also initialize std::vector with an initializer list. For example:

using namespace std; // for example only

for (auto s : vector<string>{"one","two","three"} ) 
    cout << s << endl;

So, your example would become:

void foo(vector<string> strArray){
  // some code
}

vector<string> s {"hi", "there"}; // Works
foo(s); // Works

foo(vector<string> {"hi", "there"}); // also works

ZIP Code (US Postal Code) validation

Here's a JavaScript function which validates a ZIP/postal code based on a country code. It allows somewhat liberal formatting. You could add cases for other countries as well. Note that the default case allows empty postal codes since not all countries use them.

function isValidPostalCode(postalCode, countryCode) {
    switch (countryCode) {
        case "US":
            postalCodeRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
            break;
        case "CA":
            postalCodeRegex = /^([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])$/;
            break;
        default:
            postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;
    }
    return postalCodeRegex.test(postalCode);
}

FYI The second link referring to vanity ZIP codes appears to have been an April Fool's joke.

What is exactly the base pointer and stack pointer? To what do they point?

ESP is the current stack pointer, which will change any time a word or address is pushed or popped onto/off off the stack. EBP is a more convenient way for the compiler to keep track of a function's parameters and local variables than using the ESP directly.

Generally (and this may vary from compiler to compiler), all of the arguments to a function being called are pushed onto the stack by the calling function (usually in the reverse order that they're declared in the function prototype, but this varies). Then the function is called, which pushes the return address (EIP) onto the stack.

Upon entry to the function, the old EBP value is pushed onto the stack and EBP is set to the value of ESP. Then the ESP is decremented (because the stack grows downward in memory) to allocate space for the function's local variables and temporaries. From that point on, during the execution of the function, the arguments to the function are located on the stack at positive offsets from EBP (because they were pushed prior to the function call), and the local variables are located at negative offsets from EBP (because they were allocated on the stack after the function entry). That's why the EBP is called the Frame Pointer, because it points to the center of the function call frame.

Upon exit, all the function has to do is set ESP to the value of EBP (which deallocates the local variables from the stack, and exposes the entry EBP on the top of the stack), then pop the old EBP value from the stack, and then the function returns (popping the return address into EIP).

Upon returning back to the calling function, it can then increment ESP in order to remove the function arguments it pushed onto the stack just prior to calling the other function. At this point, the stack is back in the same state it was in prior to invoking the called function.

How to execute a raw update sql with dynamic binding in rails

It doesn't look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it's methods, e.g. for MySQL:

st = ActiveRecord::Base.connection.raw_connection.prepare("update table set f1=? where f2=? and f3=?")
st.execute(f1, f2, f3)
st.close

I'm not sure if there are other ramifications to doing this (connections left open, etc). I would trace the Rails code for a normal update to see what it's doing aside from the actual query.

Using prepared queries can save you a small amount of time in the database, but unless you're doing this a million times in a row, you'd probably be better off just building the update with normal Ruby substitution, e.g.

ActiveRecord::Base.connection.execute("update table set f1=#{ActiveRecord::Base.sanitize(f1)}")

or using ActiveRecord like the commenters said.

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

Remove duplicate rows in MySQL

If the IGNORE statement won't work like in my case, you can use the below statement:

CREATE TABLE your_table_deduped LIKE your_table;


INSERT your_table_deduped
SELECT *
FROM your_table
GROUP BY index1_id,
         index2_id;

RENAME TABLE your_table TO your_table_with_dupes;

RENAME TABLE your_table_deduped TO your_table;

#OPTIONAL
ALTER TABLE `your_table` ADD UNIQUE `unique_index` (`index1_id`, `index2_id`);

#OPTIONAL
DROP TABLE your_table_with_dupes;

Is there such a thing as min-font-size and max-font-size?

Rucksack is brilliant, but you don't necessarily have to resort to build tools like Gulp or Grunt etc.

I made a demo using CSS Custom Properties (CSS Variables) to easily control the min and max font sizes.

Like so:

* {
  /* Calculation */
  --diff: calc(var(--max-size) - var(--min-size));
  --responsive: calc((var(--min-size) * 1px) + var(--diff) * ((100vw - 420px) / (1200 - 420))); /* Ranges from 421px to 1199px */
}

h1 {
  --max-size: 50;
  --min-size: 25;
  font-size: var(--responsive);
}

h2 {
  --max-size: 40;
  --min-size: 20;
  font-size: var(--responsive);
}

How to create a function in a cshtml template?

If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    Func<int,int,int> Sum = (a, b) => a + b;
}

<h2>Index</h2>

@Sum(3,4)

When to use Spring Security`s antMatcher()?

Basically http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

Getting the minimum of two values in SQL

Use a CASE statement.

Example B in this page should be close to what you're trying to do:
http://msdn.microsoft.com/en-us/library/ms181765.aspx

Here's the code from the page:

USE AdventureWorks;
GO
SELECT   ProductNumber, Name, 'Price Range' = 
      CASE 
         WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
         WHEN ListPrice < 50 THEN 'Under $50'
         WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
         WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
         ELSE 'Over $1000'
      END
FROM Production.Product
ORDER BY ProductNumber ;
GO

Changing Node.js listening port

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);
});

This will log Ready on port 8080 to your console.

How can I get the MAC and the IP address of a connected client in PHP?

I don't think you can get MAC address in PHP, but you can get IP from $_SERVER['REMOTE_ADDR'] variable.

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

How to generate a random string of 20 characters

public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
    buf.append(chars.charAt(rand.nextInt(chars.length())));
  }
  return buf.toString();
}

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

Remove Project from Android Studio

Or if you don't want to build it just remove it from settings.gradle file

Excel VBA - select a dynamic cell range

sub selectVar ()
    dim x,y as integer
    let srange = "A" & x & ":" & "m" & y
    range(srange).select
end sub

I think this is the simplest way.

how to replace an entire column on Pandas.DataFrame

If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:

df = df.assign(B=df1['E'])

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.

However, you can convert strings to numbers like this:

pd.Series(['123', '42']).astype(float)

instead of float(series)

How to check whether a select box is empty using JQuery/Javascript

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

Console.log(); How to & Debugging javascript

console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.

It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.

To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Maven error: Not authorized, ReasonPhrase:Unauthorized

I have recently encountered this problem. Here are the steps to resolve

  1. Check the servers section in the settings.xml file.Is username and password correct?

_x000D_
_x000D_
<servers>_x000D_
  <server>_x000D_
    <id>serverId</id>_x000D_
    <username>username</username>_x000D_
    <password>password</password>_x000D_
  </server>_x000D_
</servers>
_x000D_
_x000D_
_x000D_

  1. Check the repository section in the pom.xml file.The id of the server tag should be the same as the id of the repository tag.

_x000D_
_x000D_
<repositories>_x000D_
 <repository>_x000D_
   <id>serverId</id>  _x000D_
   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
 </repository>_x000D_
</repositories>
_x000D_
_x000D_
_x000D_

  1. If the repository tag is not configured in the pom.xml file, look in the settings.xml file.

_x000D_
_x000D_
<profiles>_x000D_
 <profile>_x000D_
   <repositories>_x000D_
     <repository>_x000D_
      <id>serverId</id>_x000D_
      <name>aliyun</name>_x000D_
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
     </repository>_x000D_
   </repositories>_x000D_
 </profile>_x000D_
</profiles>
_x000D_
_x000D_
_x000D_

Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.

Pure CSS collapse/expand div

Using <summary> and <details>

Using <summary> and <details> elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.

_x000D_
_x000D_
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
  color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
  outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
  <summary>Summary, caption, or legend for the content</summary>_x000D_
  Content goes here._x000D_
</details>
_x000D_
_x000D_
_x000D_

See also how to style the <details> element (HTML5 Doctor) (little bit tricky).

Pure CSS3

The :target selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.

_x000D_
_x000D_
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
  display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
  display: block;_x000D_
}
_x000D_
<div>_x000D_
  <a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
  <a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
  <a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
  <a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Add a common Legend for combined ggplots

You may also use ggarrange from ggpubr package and set "common.legend = TRUE":

library(ggpubr)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data = dsamp, colour = clarity)
p2 <- qplot(cut, price, data = dsamp, colour = clarity)
p3 <- qplot(color, price, data = dsamp, colour = clarity)
p4 <- qplot(depth, price, data = dsamp, colour = clarity) 

ggarrange(p1, p2, p3, p4, ncol=2, nrow=2, common.legend = TRUE, legend="bottom")

enter image description here

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

If you are using a fragment and using an AlertDialog / Toast message, use getActivity() in the context parameter.

Worked for me.

Cheers!

How to set session timeout dynamically in Java web applications?

As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.

getRequest().getSession().setMaxInactiveInterval(123);

How to extract numbers from string in c?

A possible solution using sscanf() and scan sets:

const char* s = "ab234cid*(s349*(20kd";
int i1, i2, i3;
if (3 == sscanf(s,
                "%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
                &i1,
                &i2,
                &i3))
{
    printf("%d %d %d\n", i1, i2, i3);
}

where %*[^0123456789] means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW .

Or, if the number of numbers is unknown you can use %n specifier to record the last position read in the buffer:

const char* s = "ab234cid*(s349*(20kd";
int total_n = 0;
int n;
int i;
while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
{
    total_n += n;
    printf("%d\n", i);
}

Electron: jQuery is not defined

you may try the following code:

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration:false,
        }
});

Add ... if string is too long PHP

Use wordwrap() to truncate the string without breaking words if the string is longer than 50 characters, and just add ... at the end:

$str = $input;
if( strlen( $input) > 50) {
    $str = explode( "\n", wordwrap( $input, 50));
    $str = $str[0] . '...';
}

echo $str;

Otherwise, using solutions that do substr( $input, 0, 50); will break words.

CSS: fixed position on x-axis but not y?

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

Thanks

How SQL query result insert in temp table?

In MySQL:

create table temp as select * from original_table

How to upgrade all Python packages with pip

See all outdated packages

 pip list --outdated --format=columns

Install

 sudo pip install pipdate

then type

 sudo -H pipdate

Python loop to run for certain amount of seconds

For those using asyncio, an easy way is to use asyncio.wait_for():

async def my_loop():
    res = False
    while not res:
        res = await do_something()

await asyncio.wait_for(my_loop(), 10)

Increase distance between text and title on the y-axis

Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU

Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.

ggplot(mpg, aes(cty, hwy)) + 
    geom_point() + 
    xlab("\nYour_x_Label") + ylab("Your_y_Label\n")

Hope that helps!

How to concatenate text from multiple rows into a single text string in SQL server?

DECLARE @Names VARCHAR(8000)
SELECT @name = ''
SELECT @Names = @Names + ',' + Names FROM People
SELECT SUBSTRING(2, @Names, 7998)

This puts the stray comma at the beginning.

However, if you need other columns, or to CSV a child table you need to wrap this in a scalar user defined field (UDF).

You can use XML path as a correlated subquery in the SELECT clause too (but I'd have to wait until I go back to work because Google doesn't do work stuff at home :-)

define() vs. const

I know this is already answered, but none of the current answers make any mention of namespacing and how it affects constants and defines.

As of PHP 5.3, consts and defines are similar in most respects. There are still, however, some important differences:

  • Consts cannot be defined from an expression. const FOO = 4 * 3; doesn't work, but define('CONST', 4 * 3); does.
  • The name passed to define must include the namespace to be defined within that namespace.

The code below should illustrate the differences.

namespace foo 
{
    const BAR = 1;
    define('BAZ', 2);
    define(__NAMESPACE__ . '\\BAZ', 3);
}

namespace {
    var_dump(get_defined_constants(true));
}

The content of the user sub-array will be ['foo\\BAR' => 1, 'BAZ' => 2, 'foo\\BAZ' => 3].

=== UPDATE ===

The upcoming PHP 5.6 will allow a bit more flexibility with const. You will now be able to define consts in terms of expressions, provided that those expressions are made up of other consts or of literals. This means the following should be valid as of 5.6:

const FOOBAR = 'foo ' . 'bar';
const FORTY_TWO = 6 * 9; // For future editors: THIS IS DELIBERATE! Read the answer comments below for more details
const ULTIMATE_ANSWER = 'The ultimate answer to life, the universe and everything is ' . FORTY_TWO;

You still won't be able to define consts in terms of variables or function returns though, so

const RND = mt_rand();
const CONSTVAR = $var;

will still be out.

Switch to selected tab by name in Jquery-UI Tabs

Use this function:

function uiTabs(i){
    $("#tabs").tabs("option", "selected", i);
}

And use following code to switch between tabs:

<a onclick="uiTabs(0)">Tab 1</a>
<a onclick="uiTabs(1)">Tab 2</a>
<a onclick="uiTabs(2)">Tab 3</a>

Multiple commands in an alias for bash

Add this function to your ~/.bashrc and restart your terminal or run source ~/.bashrc

function lock() {
    gnome-screensaver
    gnome-screensaver-command --lock
}

This way these two commands will run whenever you enter lock in your terminal.

In your specific case creating an alias may work, but I don't recommend it. Intuitively we would think the value of an alias would run the same as if you entered the value in the terminal. However that's not the case:

The rules concerning the definition and use of aliases are somewhat confusing.

and

For almost every purpose, shell functions are preferred over aliases.

So don't use an alias unless you have to. https://ss64.com/bash/alias.html

MongoDB SELECT COUNT GROUP BY

Additionally if you need to restrict the grouping you can use:

db.events.aggregate( 
    {$match: {province: "ON"}},
    {$group: {_id: "$date", number: {$sum: 1}}}  
)

How to clear text area with a button in html using javascript?

Change in your html with adding the function on the button click

 <input type="button" value="Clear" onclick="javascript:eraseText();"> 
    <textarea id='output' rows=20 cols=90></textarea>

Try this in your js file:

function eraseText() {
    document.getElementById("output").value = "";
}

How to use MySQL dump from a remote machine

Try it with Mysqldump

#mysqldump --host=the.remotedatabase.com -u yourusername -p yourdatabasename > /User/backups/adump.sql

Conda command not found

Maybe you should type add this to your .bashrc or .zshrc

export PATH="/anaconda3/bin":$PATH

It worked for me.

Is an anchor tag without the href attribute safe?

Short answer: No.

Long answer:

First, without an href attribute, it will not be a link. If it isn't a link then it wont be keyboard (or breath switch, or various other not pointer based input device) accessible (unless you use HTML 5 features of tabindex which are not universally supported). It is very rare that it is appropriate for a control to not have keyboard access.

Second. You should have an alternative for when the JavaScript does not run (because it was slow to load from the server, an Internet connection was dropped (e.g. mobile signal on a moving train), JS is turned off, etc, etc).

Make use of progressive enhancement by unobtrusive JS.

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

just in case someone finds this searching for errors concerning ActiveStorage:

if you have a controller-action where you want to generate upload-urls etc with the local disc-service (most likely in test environment), you need to include ActiveStorage::SetCurrent in the controller in order to allow blob.service_url_for_direct_upload to work correctly.

How to convert java.sql.timestamp to LocalDate (java8) java.time?

I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.

You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:

public static void main(String... args) {
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    TimeZone.setDefault(utcTimeZone);
    ...
    timestamp.toLocalDateTime().toLocalDate();
}

Or you can use toInstant.atZone chain:

timestamp.toInstant()
        .atZone(ZoneId.of("UTC"))
        .toLocalDate();

Change the mouse cursor on mouse over to anchor-like style

I think :hover was missing in above answers. So following would do the needful.(if css was required)

#myDiv:hover
{
    cursor: pointer;
}

How to align an input tag to the center without specifying the width?

You need to put the text-align:center on the containing div, not on the input itself.

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

Test class with a new() call in it with Mockito

I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.

Here is how:

class TestedClass extends AARRGGHH {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

Now, PowerMockRunner failed to initialize TestedClass because it extends AARRGGHH, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.

I found a nice hack with minimal refactoring of TestedClass: I created a small method

LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
    new lc = new LoginContext(login, callbackHandler);
}

The scope of this method is necessarily package.

Then your test stub will look like:

LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
    .when(testClass)
    .initLoginContext("login", callbackHandler)

and the trick is done...

How to get the device's IMEI/ESN programmatically in android?

I use the following code to get the IMEI or use Secure.ANDROID_ID as an alternative, when the device doesn't have phone capabilities:

/**
 * Returns the unique identifier for the device
 *
 * @return unique identifier for the device
 */
public String getDeviceIMEI() {
    String deviceUniqueIdentifier = null;
    TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    if (null != tm) {
        deviceUniqueIdentifier = tm.getDeviceId();
    }
    if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
        deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
    return deviceUniqueIdentifier;
}

When would you use the different git merge strategies?

"Resolve" vs "Recursive" merge strategy

Recursive is the current default two-head strategy, but after some searching I finally found some info about the "resolve" merge strategy.

Taken from O'Reilly book Version Control with Git (Amazon) (paraphrased):

Originally, "resolve" was the default strategy for Git merges.

In criss-cross merge situations, where there is more than one possible merge basis, the resolve strategy works like this: pick one of the possible merge bases, and hope for the best. This is actually not as bad as it sounds. It often turns out that the users have been working on different parts of the code. In that case, Git detects that it's remerging some changes that are already in place and skips the duplicate changes, avoiding the conflict. Or, if these are slight changes that do cause conflict, at least the conflict should be easy for the developer to handle..

I have successfully merged trees using "resolve" that failed with the default recursive strategy. I was getting fatal: git write-tree failed to write a tree errors, and thanks to this blog post (mirror) I tried "-s resolve", which worked. I'm still not exactly sure why... but I think it was because I had duplicate changes in both trees, and resolve "skipped" them properly.

How can I obtain the element-wise logical NOT of a pandas Series?

I just give it a shot:

In [9]: s = Series([True, True, True, False])

In [10]: s
Out[10]: 
0     True
1     True
2     True
3    False

In [11]: -s
Out[11]: 
0    False
1    False
2    False
3     True

How to prevent Browser cache for php site

I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).

I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/

The solution:

Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)

For development:

<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">

For production (where caching is mostly a good thing):

<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)

Or combination of these two:

<?php
    define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">

EDIT:

Or prettier combination of those two:

<?php
    // Init
    define( "DEBUGGING", true ); // or false in production enviroment
    // Functions
    function get_cache_prevent_string( $always = false ) {
        return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
    }
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">

Turning off hibernate logging console output

Executing:

java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);

before hibernate's initialization worked for me.


Note: the line above will turn every logging off (Level.OFF). If you want to be less strict, you can use

java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.SEVERE);

that is silent enough. (Or check the java.util.logging.Level class for more levels).

regex.test V.S. string.match to know if a string matches a regular expression

Basic Usage

First, let's see what each function does:

regexObject.test( String )

Executes the search for a match between a regular expression and a specified string. Returns true or false.

string.match( RegExp )

Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or null if there are none.

Since null evaluates to false,

if ( string.match(regex) ) {
  // There was a match.
} else {
  // No match.
} 

Performance

Is there any difference regarding performance?

Yes. I found this short note in the MDN site:

If you need to know if a string matches a regular expression regexp, use regexp.test(string).

Is the difference significant?

The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:

test vs match | Performance Test

Conclusion

Use .test if you want a faster boolean check. Use .match to retrieve all matches when using the g global flag.

How to get parameters from the URL with JSP

About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:

Implicit Objects

The JSP expression language defines a set of implicit objects:

  • pageContext: The context for the JSP page. Provides access to various objects including:
    • servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
    • session: The session object for the client. See Maintaining Client State.
    • request: The request triggering the execution of the JSP page. See Getting Information from Requests.
    • response: The response returned by the JSP page. See Constructing Responses.
  • In addition, several implicit objects are available that allow easy access to the following objects:
    • param: Maps a request parameter name to a single value
    • paramValues: Maps a request parameter name to an array of values
    • header: Maps a request header name to a single value
    • headerValues: Maps a request header name to an array of values
    • cookie: Maps a cookie name to a single cookie
    • initParam: Maps a context initialization parameter name to a single value
  • Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
    • pageScope: Maps page-scoped variable names to their values
    • requestScope: Maps request-scoped variable names to their values
    • sessionScope: Maps session-scoped variable names to their values
    • applicationScope: Maps application-scoped variable names to their values

The interesting parts are in bold :)

So, to answer your question, you should be able to access it like this (using EL):

${param.accountID}

Or, using JSP Scriptlets (not recommended):

<%
    String accountId = request.getParameter("accountID");
%>

Allow only pdf, doc, docx format for file upload?

var file = form.getForm().findField("file").getValue();
var fileLen = file.length;
var lastValue = file.substring(fileLen - 3, fileLen);
if (lastValue == 'doc') {//check same for other file format}

What's the difference between identifying and non-identifying relationships?

Let's say we have those tables:

user
--------
id
name


comments
------------
comment_id
user_id
text

relationship between those two tables will identifiying relationship. Because, comments only can be belong to its owner, not other users. for example. Each user has own comment, and when user is deleted, this user's comments also should be deleted.

How do I close a single buffer (out of many) in Vim?

Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville

I use:

"" Buffer Navigation                                                                                                                                                                                        
" Toggle left sidebar: NERDTree and BufferGator                                                                                                                                                             
fu! UiToggle()                                                                                                                                                                                              
  let b = bufnr("%")                                                                                                                                                                                        
  execute "NERDTreeToggle | BuffergatorToggle"                                                                                                                                                              
  execute ( bufwinnr(b) . "wincmd w" )                                                                                                                                                                      
  execute ":set number!"                                                                                                                                                                                    
endf                                                                                                                                                                                                        
map  <silent> <Leader>w  <esc>:call UiToggle()<cr>   

Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

JavaScript Chart Library

There is a growing number of Open Source and commercial solutions for pure JavaScript charting that do not require Flash. In this response I will only present Open Source options.

There are 2 main classes of JavaScript solutions for graphics that do not require Flash:

  • Canvas-based, rendered in IE using ExplorerCanvas that in turns relies on VML
  • SVG on standard-based browsers, rendered as VML in IE

There are pros and cons of both approaches but for a charting library I would recommend the later because it is well integrated with DOM, allowing to manipulate charts elements with the DOM, and most importantly setting DOM events. By contrast Canvas charting libraries must reinvent the DOM wheel to manage events. So unless you intend to build static graphs with no event handling, SVG/VML solutions should be better.

For SVG/VML solutions there are many options, including:

Raphael is a very active, well maintained, and mature, open-source graphic library with very good cross-browser support including IE 6 to 8, Firefox, Opera, Safari, Chrome, and Konqueror. Raphael does not depend on any JavaScript framework and therefore can be used with Prototype, jQuery, Dojo, Mootools, etc...

There are a number of charting libraries based on Raphael, including (but not limited to):

  • gRaphael, an extension of the Raphael graphic library
  • Ico, with an intuitive API based on a single function call to create complex charts

Disclosure: I am the developer of one of the Ico forks on github.

SQL JOIN and different types of JOINs

Definition:


JOINS are way to query the data that combined together from multiple tables simultaneously.

Types of JOINS:


Concern to RDBMS there are 5-types of joins:

  • Equi-Join: Combines common records from two tables based on equality condition. Technically, Join made by using equality-operator (=) to compare values of Primary Key of one table and Foreign Key values of another table, hence result set includes common(matched) records from both tables. For implementation see INNER-JOIN.

  • Natural-Join: It is enhanced version of Equi-Join, in which SELECT operation omits duplicate column. For implementation see INNER-JOIN

  • Non-Equi-Join: It is reverse of Equi-join where joining condition is uses other than equal operator(=) e.g, !=, <=, >=, >, < or BETWEEN etc. For implementation see INNER-JOIN.

  • Self-Join:: A customized behavior of join where a table combined with itself; This is typically needed for querying self-referencing tables (or Unary relationship entity). For implementation see INNER-JOINs.

  • Cartesian Product: It cross combines all records of both tables without any condition. Technically, it returns the result set of a query without WHERE-Clause.

As per SQL concern and advancement, there are 3-types of joins and all RDBMS joins can be achieved using these types of joins.

  1. INNER-JOIN: It merges(or combines) matched rows from two tables. The matching is done based on common columns of tables and their comparing operation. If equality based condition then: EQUI-JOIN performed, otherwise Non-EQUI-Join.

  2. OUTER-JOIN: It merges(or combines) matched rows from two tables and unmatched rows with NULL values. However, can customized selection of un-matched rows e.g, selecting unmatched row from first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.

    2.1. LEFT Outer JOIN (a.k.a, LEFT-JOIN): Returns matched rows from two tables and unmatched from the LEFT table(i.e, first table) only.

    2.2. RIGHT Outer JOIN (a.k.a, RIGHT-JOIN): Returns matched rows from two tables and unmatched from the RIGHT table only.

    2.3. FULL OUTER JOIN (a.k.a OUTER JOIN): Returns matched and unmatched from both tables.

  3. CROSS-JOIN: This join does not merges/combines instead it performs Cartesian product.

enter image description here Note: Self-JOIN can be achieved by either INNER-JOIN, OUTER-JOIN and CROSS-JOIN based on requirement but the table must join with itself.

For more information:

Examples:

1.1: INNER-JOIN: Equi-join implementation

SELECT  *
FROM Table1 A 
 INNER JOIN Table2 B ON A.<Primary-Key> =B.<Foreign-Key>;

1.2: INNER-JOIN: Natural-JOIN implementation

Select A.*, B.Col1, B.Col2          --But no B.ForeignKeyColumn in Select
 FROM Table1 A
 INNER JOIN Table2 B On A.Pk = B.Fk;

1.3: INNER-JOIN with NON-Equi-join implementation

Select *
 FROM Table1 A INNER JOIN Table2 B On A.Pk <= B.Fk;

1.4: INNER-JOIN with SELF-JOIN

Select *
 FROM Table1 A1 INNER JOIN Table1 A2 On A1.Pk = A2.Fk;

2.1: OUTER JOIN (full outer join)

Select *
 FROM Table1 A FULL OUTER JOIN Table2 B On A.Pk = B.Fk;

2.2: LEFT JOIN

Select *
 FROM Table1 A LEFT OUTER JOIN Table2 B On A.Pk = B.Fk;

2.3: RIGHT JOIN

Select *
 FROM Table1 A RIGHT OUTER JOIN Table2 B On A.Pk = B.Fk;

3.1: CROSS JOIN

Select *
 FROM TableA CROSS JOIN TableB;

3.2: CROSS JOIN-Self JOIN

Select *
 FROM Table1 A1 CROSS JOIN Table1 A2;

//OR//

Select *
 FROM Table1 A1,Table1 A2;

Set the value of a variable with the result of a command in a Windows batch file

The only way I've seen it done is if you do this:

for /f "delims=" %a in ('ver') do @set foobar=%a

ver is the version command for Windows and on my system it produces:

Microsoft Windows [Version 6.0.6001]

Source

Does 'position: absolute' conflict with Flexbox?

No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.

That means that

  • If you add absolute positioning to an element with display: inline-flex, it will become block-level (like display: flex), but will still generate a flex formatting context.

  • If you add absolute positioning to an element with display: flex, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.

That said, absolutely positioning conflicts with flex children.

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

Simulate user input in bash script

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"

Git: which is the default configured remote for branch?

For the sake of completeness: the previous answers tell how to set the upstream branch, but not how to see it.

There are a few ways to do this:

git branch -vv shows that info for all branches. (formatted in blue in most terminals)

cat .git/config shows this also.

For reference:

How to create a inner border for a box in html?

IE doesn't support outline-offset so another solution would be to create 2 div tags, one nested into the other one. The inner one would have a border and be slightly smaller than the container.

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 400px;_x000D_
  height: 100px;_x000D_
  background: #000000;_x000D_
  padding: 10px;_x000D_
}_x000D_
.inner {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: #000000;_x000D_
  border: 1px dashed #ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="inner"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Origin null is not allowed by Access-Control-Allow-Origin

You can load a local Javascript file (in the tree below your file:/ source page) using the source tag:

<script src="my_data.js"></script>

If you encode your input into Javascript, like in this case:

mydata.js:

$xsl_text = "<xsl:stylesheet version="1.0" + ....

(this is easier for json) then you have your 'data' in a Javascript global variable to use as you wish.

error TS2339: Property 'x' does not exist on type 'Y'

Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.

See Dotted property for types with string index signatures in TypeScript 2.2 release note.

How can I make a "color map" plot in matlab?

I also suggest using contourf(Z). For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.

So in my case, I prefer to use jucestain's answer. The default shading faceted of pcolor() is more suitable. However, pcolor() does not use the last row and column of the plotted matrix. For this, I used the padarray() function:

pcolor(padarray(Z,[1 1],0,'post'))

Sorry if that is not really related to the original post

How to post JSON to PHP with curl

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

LOAD DATA INFILE 'file.csv'
  INTO TABLE t1
  (column1, @dummy, column2, @dummy, column3, ...)
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';

Just replace the column1, column2, etc.. with your column names, and put @dummy anwhere there's a column in the CSV you want to ignore.

Full details here.

Remove all values within one list from another list?

I was looking for fast way to do the subject, so I made some experiments with suggested ways. And I was surprised by results, so I want to share it with you.

Experiments were done using pythonbenchmark tool and with

a = range(1,50000) # Source list
b = range(1,15000) # Items to remove

Results:

 def comprehension(a, b):
     return [x for x in a if x not in b]

5 tries, average time 12.8 sec

def filter_function(a, b):
    return filter(lambda x: x not in b, a)

5 tries, average time 12.6 sec

def modification(a,b):
    for x in b:
        try:
            a.remove(x)
        except ValueError:
            pass
    return a

5 tries, average time 0.27 sec

def set_approach(a,b):
    return list(set(a)-set(b))

5 tries, average time 0.0057 sec

Also I made another measurement with bigger inputs size for the last two functions

a = range(1,500000)
b = range(1,100000)

And the results:

For modification (remove method) - average time is 252 seconds For set approach - average time is 0.75 seconds

So you can see that approach with sets is significantly faster than others. Yes, it doesn't keep similar items, but if you don't need it - it's for you. And there is almost no difference between list comprehension and using filter function. Using 'remove' is ~50 times faster, but it modifies source list. And the best choice is using sets - it's more than 1000 times faster than list comprehension!

How to use java.Set

The first thing you need to study is the java.util.Set API.

Here's a small example of how to use its methods:

    Set<Integer> numbers = new TreeSet<Integer>();

    numbers.add(2);
    numbers.add(5);

    System.out.println(numbers); // "[2, 5]"
    System.out.println(numbers.contains(7)); // "false"

    System.out.println(numbers.add(5)); // "false"
    System.out.println(numbers.size()); // "2"

    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    System.out.println("Sum = " + sum); // "Sum = 7"

    numbers.addAll(Arrays.asList(1,2,3,4,5));
    System.out.println(numbers); // "[1, 2, 3, 4, 5]"

    numbers.removeAll(Arrays.asList(4,5,6,7));
    System.out.println(numbers); // "[1, 2, 3]"

    numbers.retainAll(Arrays.asList(2,3,4,5));
    System.out.println(numbers); // "[2, 3]"

Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals and hashCode contract, already, now is a good time to start.

In a nutshell:

  • @Override both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
    • Be careful with writing boolean equals(Thing other) instead; this is not a proper @Override.
  • For non-null references x, y, z, equals must be:
    • reflexive: x.equals(x).
    • symmetric: x.equals(y) if and only if y.equals(x)
    • transitive: if x.equals(y) && y.equals(z), then x.equals(z)
    • consistent: x.equals(y) must not change unless the objects have mutated
    • x.equals(null) == false
  • The general contract for hashCode is:
    • consistent: return the same number unless mutation happened
    • consistent with equals: if x.equals(y), then x.hashCode() == y.hashCode()
      • strictly speaking, object inequality does not require hash code inequality
      • but hash code inequality necessarily requires object inequality
  • What counts as mutation should be consistent between equals and hashCode.

Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable, or by providing a separate Comparator.

Having either makes it easy to sort your objects (Arrays.sort, Collections.sort(List)). It also allows you to use SortedSet, such as TreeSet.


Further readings on stackoverflow:

How do I print out the value of this boolean? (Java)

There are several problems.

One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.

Secondly, the line

System.out.println(boolean isLeapYear);

is a syntax error. Delete it.

Thirdly.

You never call the function from your main routine. That is why you never see any reply to the input.

Catch a thread's exception in the caller thread in Python

One method I am fond of is based on the observer pattern. I define a signal class which my thread uses to emit exceptions to listeners. It can also be used to return values from threads. Example:

import threading

class Signal:
    def __init__(self):
        self._subscribers = list()

    def emit(self, *args, **kwargs):
        for func in self._subscribers:
            func(*args, **kwargs)

    def connect(self, func):
        self._subscribers.append(func)

    def disconnect(self, func):
        try:
            self._subscribers.remove(func)
        except ValueError:
            raise ValueError('Function {0} not removed from {1}'.format(func, self))


class WorkerThread(threading.Thread):

    def __init__(self, *args, **kwargs):
        super(WorkerThread, self).__init__(*args, **kwargs)
        self.Exception = Signal()
        self.Result = Signal()

    def run(self):
        if self._Thread__target is not None:
            try:
                self._return_value = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
            except Exception as e:
                self.Exception.emit(e)
            else:
                self.Result.emit(self._return_value)

if __name__ == '__main__':
    import time

    def handle_exception(exc):
        print exc.message

    def handle_result(res):
        print res

    def a():
        time.sleep(1)
        raise IOError('a failed')

    def b():
        time.sleep(2)
        return 'b returns'

    t = WorkerThread(target=a)
    t2 = WorkerThread(target=b)
    t.Exception.connect(handle_exception)
    t2.Result.connect(handle_result)
    t.start()
    t2.start()

    print 'Threads started'

    t.join()
    t2.join()
    print 'Done'

I do not have enough experience of working with threads to claim that this is a completely safe method. But it has worked for me and I like the flexibility.

Return list from async/await method

you can use the following

private async Task<List<string>> GetItems()
{
    return await Task.FromResult(new List<string> 
    { 
      "item1", "item2", "item3" 
    });
}

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

It only appeared in my Chrome browser a few days ago too. I checked a few websites I developed in the past that haven't been changed and they also show the same error. So I'd suggest it's not down to your coding, rather a bug in the latest Chrome release.

How do I calculate tables size in Oracle

I found this to be a little more accurate:

SELECT
   owner, table_name, TRUNC(sum(bytes)/1024/1024/1024) GB
FROM
(SELECT segment_name table_name, owner, bytes
FROM dba_segments
WHERE segment_type in  ('TABLE','TABLE PARTITION')
UNION ALL
SELECT i.table_name, i.owner, s.bytes
FROM dba_indexes i, dba_segments s
WHERE s.segment_name = i.index_name
AND   s.owner = i.owner
AND   s.segment_type in ('INDEX','INDEX PARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.segment_name
AND   s.owner = l.owner
AND   s.segment_type IN ('LOBSEGMENT','LOB PARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.index_name
AND   s.owner = l.owner
AND   s.segment_type = 'LOBINDEX')
---WHERE owner in UPPER('&owner')
GROUP BY table_name, owner
HAVING SUM(bytes)/1024/1024 > 10  /* Ignore really small tables */
ORDER BY SUM(bytes) desc

How to simulate key presses or a click with JavaScript?

For simulating keyboard events in Chrome:

There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for it is posted in this SO answer.

gradient descent using python and numpy

I know this question already have been answer but I have made some update to the GD function :

  ### COST FUNCTION

def cost(theta,X,y):
     ### Evaluate half MSE (Mean square error)
     m = len(y)
     error = np.dot(X,theta) - y
     J = np.sum(error ** 2)/(2*m)
     return J

 cost(theta,X,y)



def GD(X,y,theta,alpha):

    cost_histo = [0]
    theta_histo = [0]

    # an arbitrary gradient, to pass the initial while() check
    delta = [np.repeat(1,len(X))]
    # Initial theta
    old_cost = cost(theta,X,y)

    while (np.max(np.abs(delta)) > 1e-6):
        error = np.dot(X,theta) - y
        delta = np.dot(np.transpose(X),error)/len(y)
        trial_theta = theta - alpha * delta
        trial_cost = cost(trial_theta,X,y)
        while (trial_cost >= old_cost):
            trial_theta = (theta +trial_theta)/2
            trial_cost = cost(trial_theta,X,y)
            cost_histo = cost_histo + trial_cost
            theta_histo = theta_histo +  trial_theta
        old_cost = trial_cost
        theta = trial_theta
    Intercept = theta[0] 
    Slope = theta[1]  
    return [Intercept,Slope]

res = GD(X,y,theta,alpha)

This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.

grant remote access of MySQL database from any IP address

To remotely access database Mysql server 8:

CREATE USER 'root'@'%' IDENTIFIED BY 'Pswword@123';

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

FLUSH PRIVILEGES;

List of All Folders and Sub-folders

find . -type d > list.txt

Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the . to that other path.

If you want to exclude certain directories, you can filter them out with a negative condition:

find . -type d ! -name "~snapshot" > list.txt

How do I find my host and username on mysql?

You should be able to access the local database by using the name localhost. There is also a way to determine the hostname of the computer you're running on, but it doesn't sound like you need that. As for the username, you can either (1) give permissions to the account that PHP runs under to access the database without a password, or (2) store the username and password that you need to connect with (hard-coded or stored in a config file), and pass those as arguments to mysql_connect. See http://php.net/manual/en/function.mysql-connect.php.

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else