Programs & Examples On #Portable contacts

ProcessStartInfo hanging on "WaitForExit"? Why?

The documentation for Process.StandardOutput says to read before you wait otherwise you can deadlock, snippet copied below:

 // Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

Convert Date/Time for given Timezone - java

I have try this code

try{
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss Z");
            Date datetime = new Date();

            System.out.println("date "+sdf.format(datetime));

            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

            System.out.println("GMT "+ sdf.format(datetime));

            sdf.setTimeZone(TimeZone.getTimeZone("GMT+13"));

            System.out.println("GMT+13 "+ sdf.format(datetime));

            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

            System.out.println("utc "+sdf.format(datetime));

            Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

            DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");    
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));  

            String newZealandTime = formatter.format(calendar.getTime());

            System.out.println("using calendar "+newZealandTime);

        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

and getting this result

date 06-10-2011 10:40:05 +0530
GMT 06-10-2011 05:10:05 +0000 // here getting 5:10:05
GMT+13 06-10-2011 06:10:05 +1300 // here getting 6:10:05
utc 06-10-2011 05:10:05 +0000
using calendar 06 Oct 2011 18:10:05 GMT+13:00

How can I write a byte array to a file in Java?

To write a byte array to a file use the method

public void write(byte[] b) throws IOException

from BufferedOutputStream class.

java.io.BufferedOutputStream implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

For your example you need something like:

String filename= "C:/SO/SOBufferedOutputStreamAnswer";
BufferedOutputStream bos = null;
try {
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(filename));

//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);

KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
kgen.init(128); 
SecretKey key = kgen.generateKey(); 
byte[] encoded = key.getEncoded();

bos.write(encoded);

} 
// catch and handle exceptions...

Split string to equal length substrings in Java

@Test
public void regexSplit() {
    String source = "Thequickbrownfoxjumps";
    // define matcher, any char, min length 1, max length 4
    Matcher matcher = Pattern.compile(".{1,4}").matcher(source);
    List<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(source.substring(matcher.start(), matcher.end()));
    }
    String[] expected = {"Theq", "uick", "brow", "nfox", "jump", "s"};
    assertArrayEquals(result.toArray(), expected);
}

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

How to Set OnClick attribute with value containing function in ie8?

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>

How to search for file names in Visual Studio?

Just for anyone else landing on this page from Google or elsewhere, this answer is probably the best answer out of all of them.

To summarize, simply hit:

CTRL + ,

And then start typing the file name.

Numpy where function multiple conditions

The best way in your particular case would just be to change your two criteria to one criterion:

dists[abs(dists - r - dr/2.) <= dr/2.]

It only creates one boolean array, and in my opinion is easier to read because it says, is dist within a dr or r? (Though I'd redefine r to be the center of your region of interest instead of the beginning, so r = r + dr/2.) But that doesn't answer your question.


The answer to your question:
You don't actually need where if you're just trying to filter out the elements of dists that don't fit your criteria:

dists[(dists >= r) & (dists <= r+dr)]

Because the & will give you an elementwise and (the parentheses are necessary).

Or, if you do want to use where for some reason, you can do:

 dists[(np.where((dists >= r) & (dists <= r + dr)))]

Why:
The reason it doesn't work is because np.where returns a list of indices, not a boolean array. You're trying to get and between two lists of numbers, which of course doesn't have the True/False values that you expect. If a and b are both True values, then a and b returns b. So saying something like [0,1,2] and [2,3,4] will just give you [2,3,4]. Here it is in action:

In [230]: dists = np.arange(0,10,.5)
In [231]: r = 5
In [232]: dr = 1

In [233]: np.where(dists >= r)
Out[233]: (array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),)

In [234]: np.where(dists <= r+dr)
Out[234]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

In [235]: np.where(dists >= r) and np.where(dists <= r+dr)
Out[235]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

What you were expecting to compare was simply the boolean array, for example

In [236]: dists >= r
Out[236]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True], dtype=bool)

In [237]: dists <= r + dr
Out[237]: 
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

In [238]: (dists >= r) & (dists <= r + dr)
Out[238]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

Now you can call np.where on the combined boolean array:

In [239]: np.where((dists >= r) & (dists <= r + dr))
Out[239]: (array([10, 11, 12]),)

In [240]: dists[np.where((dists >= r) & (dists <= r + dr))]
Out[240]: array([ 5. ,  5.5,  6. ])

Or simply index the original array with the boolean array using fancy indexing

In [241]: dists[(dists >= r) & (dists <= r + dr)]
Out[241]: array([ 5. ,  5.5,  6. ])

C++ Best way to get integer division and remainder

All else being equal, the best solution is one that clearly expresses your intent. So:

int totalSeconds = 453;
int minutes = totalSeconds / 60;
int remainingSeconds = totalSeconds % 60;

is probably the best of the three options you presented. As noted in other answers however, the div method will calculate both values for you at once.

How do I prevent a Gateway Timeout with FastCGI on Nginx

Proxy timeouts are well, for proxies, not for FastCGI...

The directives that affect FastCGI timeouts are client_header_timeout, client_body_timeout and send_timeout.

Edit: Considering what's found on nginx wiki, the send_timeout directive is responsible for setting general timeout of response (which was bit misleading). For FastCGI there's fastcgi_read_timeout which is affecting the fastcgi process response timeout.

HTH.

Get Image Height and Width as integer values?

list($width, $height) = getimagesize($filename)

Or,

$data = getimagesize($filename);
$width = $data[0];
$height = $data[1];

Insert null/empty value in sql datetime column by default

Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()

-Just a side thought. seems you have things working.

time data does not match format

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

How to set root password to null

This worked for me on Ubuntu 16.04 with v5.7.15 MySQL:

First, make sure you have mysql-client installed (sudo apt-get install mysql-client).

Open terminal and login:

mysql -uroot -p

(then type your password)

After that:

use mysql;
update user set authentication_string=password(''), plugin='mysql_native_password' where user='root';

(tnx @Stanislav Karakhanov)

And the very last important thing is to reset mysql service:

sudo service mysql restart

You should now be able to login (without passsword) also by using MySQL Workbench.

Working with select using AngularJS's ng-options

If you need a custom title for each option, ng-options is not applicable. Instead use ng-repeat with options:

<select ng-model="myVariable">
  <option ng-repeat="item in items"
          value="{{item.ID}}"
          title="Custom title: {{item.Title}} [{{item.ID}}]">
       {{item.Title}}
  </option>
</select>

Setting background-image using jQuery CSS property

Don't forget that the jQuery css function allows objects to be passed which allows you to set multiple items at the same time. The answered code would then look like this:

$(this).css({'background-image':'url(' + imageUrl + ')'})

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Modification from @veeresh i

 var data=[

                        { id: 1, color: 'yellow' },
                        { id: 2, color: 'blue' },
                        { id: 3, color: 'red' }
                        ]; //parameter
        var para={};
        para.datav=data;   //datav from View


        $.ajax({
                    traditional: true,
                    url: "/Conroller/MethodTest",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data:para,
                    success: function (data) {
                        $scope.DisplayError(data.requestStatus);
                    }
                });

In MVC



public class Thing
    {
        public int id { get; set; }
        public string color { get; set; }
    }

    public JsonResult MethodTest(IEnumerable<Thing> datav)
        {
       //now  datav is having all your values
      }

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

PHP salt and hash SHA256 for login password

You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

What is the default Precision and Scale for a Number in Oracle?

I believe the default precision is 38, default scale is zero. However the actual size of an instance of this column, is dynamic. It will take as much space as needed to store the value, or max 21 bytes.

Gulp command not found after install

If you're using tcsh (which is my default shell on Mac OS X), you probably just need to type rehash into the shell just after the install completes:

npm install -g gulp

followed immediately by:

rehash

Otherwise, if this is your very first time installing gulp, your shell may not recognize that there's a new executable installed -- so you either need to start a new shell, or type rehash in the current shell.

(This is basically a one-time thing for each command you install globally.)

How to drop a database with Mongoose?

Tried @hellslam's and @silverfighter's answers. I found a race condition holding my tests back. In my case I'm running mocha tests and in the before function of the test I want to erase the entire DB. Here's what works for me.

var con = mongoose.connect('mongodb://localhost/mydatabase');
mongoose.connection.on('open', function(){
    con.connection.db.dropDatabase(function(err, result){
        done();
    });
});

You can read more https://github.com/Automattic/mongoose/issues/1469

CASCADE DELETE just once

If I understand correctly, you should be able to do what you want by dropping the foreign key constraint, adding a new one (which will cascade), doing your stuff, and recreating the restricting foreign key constraint.

For example:

testing=# create table a (id integer primary key);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "a_pkey" for table "a"
CREATE TABLE
testing=# create table b (id integer references a);
CREATE TABLE

-- put some data in the table
testing=# insert into a values(1);
INSERT 0 1
testing=# insert into a values(2);
INSERT 0 1
testing=# insert into b values(2);
INSERT 0 1
testing=# insert into b values(1);
INSERT 0 1

-- restricting works
testing=# delete from a where id=1;
ERROR:  update or delete on table "a" violates foreign key constraint "b_id_fkey" on table "b"
DETAIL:  Key (id)=(1) is still referenced from table "b".

-- find the name of the constraint
testing=# \d b;
       Table "public.b"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 
Foreign-key constraints:
    "b_id_fkey" FOREIGN KEY (id) REFERENCES a(id)

-- drop the constraint
testing=# alter table b drop constraint b_a_id_fkey;
ALTER TABLE

-- create a cascading one
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete cascade; 
ALTER TABLE

testing=# delete from a where id=1;
DELETE 1
testing=# select * from a;
 id 
----
  2
(1 row)

testing=# select * from b;
 id 
----
  2
(1 row)

-- it works, do your stuff.
-- [stuff]

-- recreate the previous state
testing=# \d b;
       Table "public.b"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 
Foreign-key constraints:
    "b_id_fkey" FOREIGN KEY (id) REFERENCES a(id) ON DELETE CASCADE

testing=# alter table b drop constraint b_id_fkey;
ALTER TABLE
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete restrict; 
ALTER TABLE

Of course, you should abstract stuff like that into a procedure, for the sake of your mental health.

How to redirect a URL path in IIS?

If you have loads of re-directs to create, having loads of virtual directories over the places is a nightmare to maintain. You could try using ISAPI redirect an IIS extension. Then all you re-directs are managed in one place.

http://www.isapirewrite.com/docs/

It allows also you to match patterns based on reg ex expressions etc. I've used where I've had to re-direct 100's of pages and its saved a lot of time.

Is there a way to create key-value pairs in Bash script?

In bash version 4 associative arrays were introduced.

declare -A arr

arr["key1"]=val1

arr+=( ["key2"]=val2 ["key3"]=val3 )

The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.

for key in ${!arr[@]}; do
    echo ${key} ${arr[${key}]}
done

Will loop over all key values and echo them out.

Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here

Automatically plot different colored lines

If all vectors have equal size, create a matrix and plot it. Each column is plotted with a different color automatically Then you can use legend to indicate columns:

data = randn(100, 5);

figure;
plot(data);

legend(cellstr(num2str((1:size(data,2))')))

Or, if you have a cell with kernels names, use

legend(names)

jQuery dialog popup

Your problem is on the call for the dialog

If you dont initialize the dialog, you don't have to pass "open" for it to show:

$("#dialog").dialog();

Also, this code needs to be on a $(document).ready(); function or be below the elements for it to work.

Simple GUI Java calculator

Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.

When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.

So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.

Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.

Node.js EACCES error when listening on most ports

this happens if the port you are trying to locally host on is portfowarded

Creating stored procedure and SQLite?

Yet, it is possible to fake it using a dedicated table, named for your fake-sp, with an AFTER INSERT trigger. The dedicated table rows contain the parameters for your fake sp, and if it needs to return results you can have a second (poss. temp) table (with name related to the fake-sp) to contain those results. It would require two queries: first to INSERT data into the fake-sp-trigger-table, and the second to SELECT from the fake-sp-results-table, which could be empty, or have a message-field if something went wrong.

Function for Factorial in Python

def factorial(n):
    if n < 2:
        return 1
    return n * factorial(n - 1)

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

While both reducebykey and groupbykey will produce the same answer, the reduceByKey example works much better on a large dataset. That's because Spark knows it can combine output with a common key on each partition before shuffling the data.

On the other hand, when calling groupByKey - all the key-value pairs are shuffled around. This is a lot of unnessary data to being transferred over the network.

for more detailed check this below link

https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/best_practices/prefer_reducebykey_over_groupbykey.html

WP -- Get posts by category?

add_shortcode( 'seriesposts', 'series_posts' );

function series_posts( $atts )
{ ob_start();

$myseriesoption = get_option( '_myseries', null );

$type = $myseriesoption;
$args=array(  'post_type' => $type,  'post_status' => 'publish',  'posts_per_page' => 5,  'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>'; 
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>'; 
endwhile;
echo '</ul>'; 
}
wp_reset_query();




return ob_get_clean(); }

//this will generate a shortcode function to be used on your site [seriesposts]

Checkout old commit and make it a new commit

eloone did it file by file with

git checkout <commit-hash> <filename>

but you could checkout all files more easily by doing

git checkout <commit-hash> .

How to compare timestamp dates with date-only parameter in MySQL?

Use a conversion function of MYSQL :

SELECT * FROM table WHERE DATE(timestamp) = '2012-05-05' 

This should work

Could not commit JPA transaction: Transaction marked as rollbackOnly

As explained @Yaroslav Stavnichiy if a service is marked as transactional spring tries to handle transaction itself. If any exception occurs then a rollback operation performed. If in your scenario ServiceUser.method() is not performing any transactional operation you can use @Transactional.TxType annotation. 'NEVER' option is used to manage that method outside transactional context.

Transactional.TxType reference doc is here.

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

[contains(text(),'')] only returns true or false. It won't return any element results.

How to get dictionary values as a generic list

Another variant:

    List<MyType> items = new List<MyType>();
    items.AddRange(myDico.values);

Single quotes vs. double quotes in Python

Triple quoted comments are an interesting subtopic of this question. PEP 257 specifies triple quotes for doc strings. I did a quick check using Google Code Search and found that triple double quotes in Python are about 10x as popular as triple single quotes -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How do I resolve "Cannot find module" error using Node.js?

For TypeScript users, if you are importing a built-in Node module (such as http, path or url) and you are getting an error such as "Cannot find module "x" then the error can be fixed by running

npm install @types/node --save-dev

The command will import the NodeJS TypeScript definitions into your project, allowing you to use Node's built-in modules.

Using jQuery Fancybox or Lightbox to display a contact form

Have a look at: Greybox

It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.

You will find many information on how to use Greybox and also some great examples. Cheers Kara

How can I stop a While loop?

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while period<12:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        if numpy.array_equal(tmp,universe_array) is True:
            break 
        period+=1

    return period

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new FileChooserEx().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();
                saveFile.showSaveDialog(null);
            }
        });

        openBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();
                openFile.showOpenDialog(null);
            }
        });

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

How to get the onclick calling object?

I think the best way is to use currentTarget property instead of target property.

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred.


For example:

<a href="#"><span class="icon"></span> blah blah</a>

Javascript:

a.addEventListener('click', e => {
    e.currentTarget; // always returns "a" element
    e.target; // may return "a" or "span"
})

SELECT inside a COUNT

Use SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d.

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch

_x000D_
_x000D_
var data = { "results":[  _x000D_
  [  _x000D_
     {  _x000D_
        "b":"0.110547334",_x000D_
        "cost":"0.000000",_x000D_
        "w":"1.998889"_x000D_
     }_x000D_
  ],_x000D_
  [  _x000D_
     {  _x000D_
        "x":0,_x000D_
        "y":0_x000D_
     },_x000D_
     {  _x000D_
        "x":1,_x000D_
        "y":2_x000D_
     },_x000D_
     {  _x000D_
        "x":2,_x000D_
        "y":4_x000D_
     },_x000D_
     {  _x000D_
        "x":3,_x000D_
        "y":6_x000D_
     },_x000D_
     {  _x000D_
        "x":4,_x000D_
        "y":8_x000D_
     },_x000D_
     {  _x000D_
        "x":5,_x000D_
        "y":10_x000D_
     },_x000D_
     {  _x000D_
        "x":6,_x000D_
        "y":12_x000D_
     },_x000D_
     {  _x000D_
        "x":7,_x000D_
        "y":14_x000D_
     },_x000D_
     {  _x000D_
        "x":8,_x000D_
        "y":16_x000D_
     },_x000D_
     {  _x000D_
        "x":9,_x000D_
        "y":18_x000D_
     },_x000D_
     {  _x000D_
        "x":10,_x000D_
        "y":20_x000D_
     },_x000D_
     {  _x000D_
        "x":11,_x000D_
        "y":22_x000D_
     },_x000D_
     {  _x000D_
        "x":12,_x000D_
        "y":24_x000D_
     },_x000D_
     {  _x000D_
        "x":13,_x000D_
        "y":26_x000D_
     },_x000D_
     {  _x000D_
        "x":14,_x000D_
        "y":28_x000D_
     },_x000D_
     {  _x000D_
        "x":15,_x000D_
        "y":30_x000D_
     },_x000D_
     {  _x000D_
        "x":16,_x000D_
        "y":32_x000D_
     },_x000D_
     {  _x000D_
        "x":17,_x000D_
        "y":34_x000D_
     },_x000D_
     {  _x000D_
        "x":18,_x000D_
        "y":36_x000D_
     },_x000D_
     {  _x000D_
        "x":19,_x000D_
        "y":38_x000D_
     },_x000D_
     {  _x000D_
        "x":20,_x000D_
        "y":40_x000D_
     },_x000D_
     {  _x000D_
        "x":21,_x000D_
        "y":42_x000D_
     },_x000D_
     {  _x000D_
        "x":22,_x000D_
        "y":44_x000D_
     },_x000D_
     {  _x000D_
        "x":23,_x000D_
        "y":46_x000D_
     },_x000D_
     {  _x000D_
        "x":24,_x000D_
        "y":48_x000D_
     },_x000D_
     {  _x000D_
        "x":25,_x000D_
        "y":50_x000D_
     },_x000D_
     {  _x000D_
        "x":26,_x000D_
        "y":52_x000D_
     },_x000D_
     {  _x000D_
        "x":27,_x000D_
        "y":54_x000D_
     },_x000D_
     {  _x000D_
        "x":28,_x000D_
        "y":56_x000D_
     },_x000D_
     {  _x000D_
        "x":29,_x000D_
        "y":58_x000D_
     },_x000D_
     {  _x000D_
        "x":30,_x000D_
        "y":60_x000D_
     },_x000D_
     {  _x000D_
        "x":31,_x000D_
        "y":62_x000D_
     },_x000D_
     {  _x000D_
        "x":32,_x000D_
        "y":64_x000D_
     },_x000D_
     {  _x000D_
        "x":33,_x000D_
        "y":66_x000D_
     },_x000D_
     {  _x000D_
        "x":34,_x000D_
        "y":68_x000D_
     },_x000D_
     {  _x000D_
        "x":35,_x000D_
        "y":70_x000D_
     },_x000D_
     {  _x000D_
        "x":36,_x000D_
        "y":72_x000D_
     },_x000D_
     {  _x000D_
        "x":37,_x000D_
        "y":74_x000D_
     },_x000D_
     {  _x000D_
        "x":38,_x000D_
        "y":76_x000D_
     },_x000D_
     {  _x000D_
        "x":39,_x000D_
        "y":78_x000D_
     },_x000D_
     {  _x000D_
        "x":40,_x000D_
        "y":80_x000D_
     },_x000D_
     {  _x000D_
        "x":41,_x000D_
        "y":82_x000D_
     },_x000D_
     {  _x000D_
        "x":42,_x000D_
        "y":84_x000D_
     },_x000D_
     {  _x000D_
        "x":43,_x000D_
        "y":86_x000D_
     },_x000D_
     {  _x000D_
        "x":44,_x000D_
        "y":88_x000D_
     },_x000D_
     {  _x000D_
        "x":45,_x000D_
        "y":90_x000D_
     },_x000D_
     {  _x000D_
        "x":46,_x000D_
        "y":92_x000D_
     },_x000D_
     {  _x000D_
        "x":47,_x000D_
        "y":94_x000D_
     },_x000D_
     {  _x000D_
        "x":48,_x000D_
        "y":96_x000D_
     },_x000D_
     {  _x000D_
        "x":49,_x000D_
        "y":98_x000D_
     },_x000D_
     {  _x000D_
        "x":50,_x000D_
        "y":100_x000D_
     },_x000D_
     {  _x000D_
        "x":51,_x000D_
        "y":102_x000D_
     },_x000D_
     {  _x000D_
        "x":52,_x000D_
        "y":104_x000D_
     },_x000D_
     {  _x000D_
        "x":53,_x000D_
        "y":106_x000D_
     },_x000D_
     {  _x000D_
        "x":54,_x000D_
        "y":108_x000D_
     },_x000D_
     {  _x000D_
        "x":55,_x000D_
        "y":110_x000D_
     },_x000D_
     {  _x000D_
        "x":56,_x000D_
        "y":112_x000D_
     },_x000D_
     {  _x000D_
        "x":57,_x000D_
        "y":114_x000D_
     },_x000D_
     {  _x000D_
        "x":58,_x000D_
        "y":116_x000D_
     },_x000D_
     {  _x000D_
        "x":59,_x000D_
        "y":118_x000D_
     },_x000D_
     {  _x000D_
        "x":60,_x000D_
        "y":120_x000D_
     },_x000D_
     {  _x000D_
        "x":61,_x000D_
        "y":122_x000D_
     },_x000D_
     {  _x000D_
        "x":62,_x000D_
        "y":124_x000D_
     },_x000D_
     {  _x000D_
        "x":63,_x000D_
        "y":126_x000D_
     },_x000D_
     {  _x000D_
        "x":64,_x000D_
        "y":128_x000D_
     },_x000D_
     {  _x000D_
        "x":65,_x000D_
        "y":130_x000D_
     },_x000D_
     {  _x000D_
        "x":66,_x000D_
        "y":132_x000D_
     },_x000D_
     {  _x000D_
        "x":67,_x000D_
        "y":134_x000D_
     },_x000D_
     {  _x000D_
        "x":68,_x000D_
        "y":136_x000D_
     },_x000D_
     {  _x000D_
        "x":69,_x000D_
        "y":138_x000D_
     },_x000D_
     {  _x000D_
        "x":70,_x000D_
        "y":140_x000D_
     },_x000D_
     {  _x000D_
        "x":71,_x000D_
        "y":142_x000D_
     },_x000D_
     {  _x000D_
        "x":72,_x000D_
        "y":144_x000D_
     },_x000D_
     {  _x000D_
        "x":73,_x000D_
        "y":146_x000D_
     },_x000D_
     {  _x000D_
        "x":74,_x000D_
        "y":148_x000D_
     },_x000D_
     {  _x000D_
        "x":75,_x000D_
        "y":150_x000D_
     },_x000D_
     {  _x000D_
        "x":76,_x000D_
        "y":152_x000D_
     },_x000D_
     {  _x000D_
        "x":77,_x000D_
        "y":154_x000D_
     },_x000D_
     {  _x000D_
        "x":78,_x000D_
        "y":156_x000D_
     },_x000D_
     {  _x000D_
        "x":79,_x000D_
        "y":158_x000D_
     },_x000D_
     {  _x000D_
        "x":80,_x000D_
        "y":160_x000D_
     },_x000D_
     {  _x000D_
        "x":81,_x000D_
        "y":162_x000D_
     },_x000D_
     {  _x000D_
        "x":82,_x000D_
        "y":164_x000D_
     },_x000D_
     {  _x000D_
        "x":83,_x000D_
        "y":166_x000D_
     },_x000D_
     {  _x000D_
        "x":84,_x000D_
        "y":168_x000D_
     },_x000D_
     {  _x000D_
        "x":85,_x000D_
        "y":170_x000D_
     },_x000D_
     {  _x000D_
        "x":86,_x000D_
        "y":172_x000D_
     },_x000D_
     {  _x000D_
        "x":87,_x000D_
        "y":174_x000D_
     },_x000D_
     {  _x000D_
        "x":88,_x000D_
        "y":176_x000D_
     },_x000D_
     {  _x000D_
        "x":89,_x000D_
        "y":178_x000D_
     },_x000D_
     {  _x000D_
        "x":90,_x000D_
        "y":180_x000D_
     },_x000D_
     {  _x000D_
        "x":91,_x000D_
        "y":182_x000D_
     },_x000D_
     {  _x000D_
        "x":92,_x000D_
        "y":184_x000D_
     },_x000D_
     {  _x000D_
        "x":93,_x000D_
        "y":186_x000D_
     },_x000D_
     {  _x000D_
        "x":94,_x000D_
        "y":188_x000D_
     },_x000D_
     {  _x000D_
        "x":95,_x000D_
        "y":190_x000D_
     },_x000D_
     {  _x000D_
        "x":96,_x000D_
        "y":192_x000D_
     },_x000D_
     {  _x000D_
        "x":97,_x000D_
        "y":194_x000D_
     },_x000D_
     {  _x000D_
        "x":98,_x000D_
        "y":196_x000D_
     },_x000D_
     {  _x000D_
        "x":99,_x000D_
        "y":198_x000D_
     }_x000D_
  ]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
               console.info(ch);_x000D_
               _x000D_
               scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
_x000D_
_x000D_

code sample - https://codepen.io/nagasai/pen/GGzZVB

TortoiseGit-git did not exit cleanly (exit code 1)

Right-click folder -> TortiseGit -> Clean up.. -> click OK

None of the above solutions worked for me but this one did.

Create a directory if it doesn't exist

OpenCV Specific

Opencv supports filesystem, probably through its dependency Boost.

#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);

Iterate over model instance field names and values in template

There should really be a built-in way to do this. I wrote this utility build_pretty_data_view that takes a model object and form instance (a form based on your model) and returns a SortedDict.

Benefits to this solution include:

  • It preserves order using Django's built-in SortedDict.
  • When tries to get the label/verbose_name, but falls back to the field name if one is not defined.
  • It will also optionally take an exclude() list of field names to exclude certain fields.
  • If your form class includes a Meta: exclude(), but you still want to return the values, then add those fields to the optional append() list.

To use this solution, first add this file/function somewhere, then import it into your views.py.

utils.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
from django.utils.datastructures import SortedDict


def build_pretty_data_view(form_instance, model_object, exclude=(), append=()):
    i=0
    sd=SortedDict()

    for j in append:
        try:
            sdvalue={'label':j.capitalize(),
                     'fieldvalue':model_object.__getattribute__(j)}
            sd.insert(i, j, sdvalue)
            i+=1
        except(AttributeError):
            pass

    for k,v in form_instance.fields.items():
        sdvalue={'label':"", 'fieldvalue':""}
        if not exclude.__contains__(k):
            if v.label is not None:
                sdvalue = {'label':v.label,
                           'fieldvalue': model_object.__getattribute__(k)}
            else:
                sdvalue = {'label':k,
                           'fieldvalue': model_object.__getattribute__(k)}
            sd.insert(i, k, sdvalue)
            i+=1
    return sd

So now in your views.py you might do something like this

from django.shortcuts import render_to_response
from django.template import RequestContext
from utils import build_pretty_data_view
from models import Blog
from forms import BlogForm
.
.
def my_view(request):
   b=Blog.objects.get(pk=1)
   bf=BlogForm(instance=b)
   data=build_pretty_data_view(form_instance=bf, model_object=b,
                        exclude=('number_of_comments', 'number_of_likes'),
                        append=('user',))

   return render_to_response('my-template.html',
                          RequestContext(request,
                                         {'data':data,}))

Now in your my-template.html template you can iterate over the data like so...

{% for field,value in data.items %}

    <p>{{ field }} : {{value.label}}: {{value.fieldvalue}}</p>

{% endfor %}

Good Luck. Hope this helps someone!

Should Gemfile.lock be included in .gitignore?

My workmates and I have different Gemfile.lock, because we use different platforms, windows and mac, and our server is linux.

We decide to remove Gemfile.lock in repo and create Gemfile.lock.server in git repo, just like database.yml. Then before deploy it on server, we copy Gemfile.lock.server to Gemfile.lock on server using cap deploy hook

Downloading all maven dependencies to a directory NOT in repository?

I finally figured out a how to use Maven. From within Eclipse, create a new Maven project.

Download Maven, extract the archive, add the /bin folder to path.

Validate install from command-line by running mvn -v (will print version and java install path)

Change to the project root folder (where pom.xml is located) and run:

mvn dependency:copy-dependencies

All jar-files are downloaded to /target/dependency.

To set another output directory:

mvn dependency:copy-dependencies -DoutputDirectory="c:\temp"

Now it's possible to re-use this Maven-project for all dependency downloads by altering the pom.xml

Add jars to java project by build path -> configure build path -> libraries -> add JARs..

jQuery event for images loaded

There's a note on the ahpi.imgload.js plugin at the moment saying that it is currently broken, and to try this gist instead: https://gist.github.com/797120/7176db676f1e0e20d7c23933f9fc655c2f120c58

Regex to validate date format dd/mm/yyyy

Here I wrote one for dd/mm/yyyy where separator can be one of -.,/ year range 0000-9999.

It deals with leap years and is designed for regex flavors, that support lookaheads, capturing groups and backreferences. NOT valid for such as d/m/yyyy. If needed add further separators to [-.,/]

^(?=\d{2}([-.,\/])\d{2}\1\d{4}$)(?:0[1-9]|1\d|[2][0-8]|29(?!.02.(?!(?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)\d{2}(?:[02468][048]|[13579][26])))|30(?!.02)|31(?=.(?:0[13578]|10|12))).(?:0[1-9]|1[012]).\d{4}$

Test at regex101; as a Java string:

"^(?=\\d{2}([-.,\\/])\\d{2}\\1\\d{4}$)(?:0[1-9]|1\\d|[2][0-8]|29(?!.02.(?!(?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)\\d{2}(?:[02468][048]|[13579][26])))|30(?!.02)|31(?=.(?:0[13578]|10|12))).(?:0[1-9]|1[012]).\\d{4}$"

explained:

(?x) # modifier x: free spacing mode (for comments)
     # verify date dd/mm/yyyy; possible separators: -.,/
     # valid year range: 0000-9999

^    # start anchor

# precheck xx-xx-xxxx,... add new separators here
(?=\d{2}([-.,\/])\d{2}\1\d{4}$)

(?:  # day-check: non caturing group

  # days 01-28
  0[1-9]|1\d|[2][0-8]| 

  # february 29d check for leap year: all 4y / 00 years: only each 400
  # 0400,0800,1200,1600,2000,...
  29
  (?!.02. # not if feb: if not ...
    (?!
      # 00 years: exclude !0 %400 years
      (?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)

      # 00,04,08,12,... 
      \d{2}(?:[02468][048]|[13579][26])
    )
  )|

  # d30 negative lookahead: february cannot have 30 days
  30(?!.02)|

  # d31 positive lookahead: month up to 31 days
  31(?=.(?:0[13578]|10|12))

) # eof day-check

# month 01-12
.(?:0[1-9]|1[012])

# year 0000-9999
.\d{4}

$ # end anchor

Also see SO Regex FAQ; Please let me know, if it fails.

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

I use pendulum:

import pendulum


d = pendulum.now("UTC").to_iso8601_string()
print(d)

>>> 2019-10-30T00:11:21.818265Z

How can I get dict from sqlite query?

After you connect to SQLite: con = sqlite3.connect(.....) it is sufficient to just run:

con.row_factory = sqlite3.Row

Voila!

How to find minimum value from vector?

#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
#include <iterator>  // std::begin, std::end

int main() {
    std::vector<int> v = {5,14,2,4,6};
    auto result = std::min_element(std::begin(v), std::end(v));
    if (std::end(v)!=result)
        std::cout << *result << '\n';
}

The program you show has a few problems, the primary culprit being the for condition: i<v[n]. You initialize the array, setting the first 5 elements to various values and the rest to zero. n is set to the number of elements you explicitly initialized so v[n] is the first element that was implicitly initialized to zero. Therefore the loop condition is false the first time around and the loop does not run at all; your code simply prints out the first element.

Some minor issues:

  • avoid raw arrays; they behave strangely and inconsistently (e.g., implicit conversion to pointer to the array's first element, can't be assigned, can't be passed to/returned from functions by value)

  • avoid magic numbers. int v[100] is an invitation to a bug if you want your array to get input from somewhere and then try to handle more than 100 elements.

  • avoid using namespace std; It's not a big deal in implementation files, although IMO it's better to just get used to explicit qualification, but it can cause problems if you blindly use it everywhere because you'll put it in header files and start causing unnecessary name conflicts.

Unable to Resolve Module in React Native App

If you recently had a name change in git that only includes changing the case of file. MacOS will ignore the change. So, you will have to go to the file in console and change the name. for example if name change is menu.js -> Menu.js use terminal to do a manual rename after the pull.

mv menu.js Menu.js

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Don't use HTTP use SSH instead

change

https://github.com/WEMP/project-slideshow.git 

to

[email protected]:WEMP/project-slideshow.git

you can do it in .git/config file

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

Illegal pattern character 'T' when parsing a date string to java.util.Date

Update for Java 8 and higher

You can now simply do Instant.parse("2015-04-28T14:23:38.521Z") and get the correct thing now, especially since you should be using Instant instead of the broken java.util.Date with the most recent versions of Java.

You should be using DateTimeFormatter instead of SimpleDateFormatter as well.

Original Answer:

The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.

This works with the input with the trailing Z as demonstrated:

In the pattern the T is escaped with ' on either side.

The pattern for the Z at the end is actually XXX as documented in the JavaDoc for SimpleDateFormat, it is just not very clear on actually how to use it since Z is the marker for the old TimeZone information as well.

Q2597083.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Q2597083
{
    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;

    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;

    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;

    static
    {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }

    public static void main(String[] args) throws Exception
    {

        final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
        System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
        System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
        System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
        System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
        System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
    }
}

Produces the following output:

sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994

How to generate xsd from wsdl

  1. Soap ui -> New SOAPUI project -> use wsdl to create a project (lets assume we have a testService in it)
  2. you will have a folder called TestService and then inside it there will be tokenTestServiceSoapBinding (example) -> right click on it
  3. Export definition -> give location where you need to place the definition.
  4. Exported location will have xsd and wsdl files. Hope this helps!

jQuery if statement to check visibility

try

if ($('#column-left form:visible').length > 0) { ...

Select data from date range between two dates

SELECT *
FROM Product_sales
WHERE (
From_date >= '2013-08-19'
AND To_date <= '2013-08-23'
)
OR (
To_date >= '2013-08-19'
AND From_date <= '2013-08-23'
)

create multiple tag docker image

docker build  -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .

AngularJS - Passing data between pages

If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.

How to pass html string to webview on android

i have successfully done by below line

 //data == html data which you want to load
 String data = "Your data which you want to load";

 WebView webview = (WebView)this.findViewById(R.id.webview);
 webview.getSettings().setJavaScriptEnabled(true);
 webview.loadData(data, "text/html; charset=utf-8", "UTF-8");

Or You can try

 webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

XPath query to get nth instance of an element

This seems to work:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.

Table with fixed header and fixed column on pure css

Here is another solution I have just build with css grids based on the answers in here:

https://codesandbox.io/s/sweet-resonance-m733i

PostgreSQL - max number of parameters in "IN" clause?

explain select * from test where id in (values (1), (2));

QUERY PLAN

 Seq Scan on test  (cost=0.00..1.38 rows=2 width=208)
   Filter: (id = ANY ('{1,2}'::bigint[]))

But if try 2nd query:

explain select * from test where id = any (values (1), (2));

QUERY PLAN

Hash Semi Join  (cost=0.05..1.45 rows=2 width=208)
       Hash Cond: (test.id = "*VALUES*".column1)
       ->  Seq Scan on test  (cost=0.00..1.30 rows=30 width=208)
       ->  Hash  (cost=0.03..0.03 rows=2 width=4)
             ->  Values Scan on "*VALUES*"  (cost=0.00..0.03 rows=2 width=4)

We can see that postgres build temp table and join with it

How do I temporarily disable triggers in PostgreSQL?

SET session_replication_role = replica;  

also dosent work for me in Postgres 9.1. i use the two function described by bartolo-otrit with some modification. I modified the first function to make it work for me because the namespace or the schema must be present to identify the table correctly. The new code is :

CREATE OR REPLACE FUNCTION disable_triggers(a boolean, nsp character varying)
  RETURNS void AS
$BODY$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_namespace n
        join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
        where n.nspname = nsp
    loop
        execute format('alter table %I.%I %s trigger all', nsp,r.relname, act); 
    end loop;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION disable_triggers(boolean, character varying)
  OWNER TO postgres;

then i simply do a select query for every schema :

SELECT disable_triggers(true,'public');
SELECT disable_triggers(true,'Adempiere');

java.io.InvalidClassException: local class incompatible:

I believe this happens because you use the different versions of the same class on client and server. It can be different data fields or methods

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Hope the below works. I tried this in Azure custom policy.

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&amp;*\-_+=[\]{}|\\:',?/`~&quot;();!])([A-Za-z\d@#$%^&amp;*\-_+=[\]{}|\\:',?/`~&quot;();!]|\.(?!@)){6,16}$

Add image in title bar

That method will not work. The <title> only supports plain text. You will need to create an .ico image with the filename of favicon.ico and save it into the root folder of your site (where your default page is).

Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head> section of your HTML and reference your icon:

<link rel="shortcut icon" href="your_image_path_and_name.ico" />

You can use Photoshop (with a plug in) or GIMP (free) to create an .ico file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).

Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.

Update 2: You can also use .png images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico files.

Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

go to the phpmyadmin and open the console and execute this request

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

Cookies on localhost with explicit domain

Results I had varied by browser.

Chrome- 127.0.0.1 worked but localhost .localhost and "" did not. Firefox- .localhost worked but localhost, 127.0.0.1, and "" did not.

Have not tested in Opera, IE, or Safari

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

One option which worked for me on MAC.

Click on the Docker Icon in the tray. Open Preferences -> Proxies. Click on Manual Proxy and specify Web Server (HTTP) proxy and Secure Web server (HTTPS) proxy in the same format as we specify in HTTPS_PROXY env variable. Choose Apply and Restart.

This Worked for me

Can't find System.Windows.Media namespace?

The System.Windows.Media.Imaging namespace is part of PresentationCore.dll (if you are using Visual Studio 2008 then the WPF application template will automatically add this reference). Note that this namespace is not a direct wrapping of the WIC library, although a large proportion of the more common uses are still available and it is relatively obvious how these map to the WIC versions. For more information on the classes in this namespace check out

http://msdn2.microsoft.com/en-us/library/system.windows.media.imaging.aspx

docker cannot start on windows

I am using window 10 and i performed below steps to resolve this issue.

  1. check Virtualization is enabled from taskmanager-->performance
  2. Restarted the docker service
  3. Install the latest docker build and restarted the machine.
  4. Make sure the docker service is running.

Above steps helped me to resolve the issue.

Babel 6 regeneratorRuntime is not defined

For people looking to use the babel-polyfill version 7^ do this with webpack ver3^.

Npm install the module npm i -D @babel/polyfill

Then in your webpack file in your entry point do this

entry: ['@babel/polyfill', path.resolve(APP_DIR, 'App.js')],

Create a file from a ByteArrayOutputStream

You can use a FileOutputStream for this.

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File("myFile")); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Put data in your baos

    baos.writeTo(fos);
} catch(IOException ioe) {
    // Handle exception here
    ioe.printStackTrace();
} finally {
    fos.close();
}

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

My 2 cents on the problem: I was experiencing the same problem, while some part of my path was in Cyrillic. So check the path to your project for special characters. Once I removed this, the problem was fixed

How could I create a function with a completion handler in Swift?

Simple Example:

func method(arg: Bool, completion: (Bool) -> ()) {
    print("First line of code executed")
    // do stuff here to determine what you want to "send back".
    // we are just sending the Boolean value that was sent in "back"
    completion(arg)
}

How to use it:

method(arg: true, completion: { (success) -> Void in
    print("Second line of code executed")
    if success { // this will be equal to whatever value is set in this method call
          print("true")
    } else {
         print("false")
    }
})

How to downgrade php from 5.5 to 5.3

Short answer is no.

XAMPP is normally built around a specific PHP version to ensure plugins and modules are all compatible and working correctly.

If your project specifically needs PHP 5.3 - the cleanest method is simply reinstalling an older version of XAMPP with PHP 5.3 packaged into it.

XAMPP 1.7.7 was their last update before moving off PHP 5.3.

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

Play infinitely looping video on-load in HTML5

You can do this the following two ways:

1) Using loop attribute in video element (mentioned in the first answer):

2) and you can use the ended media event:

window.addEventListener('load', function(){
    var newVideo = document.getElementById('videoElementId');
    newVideo.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);

    newVideo.play();

});

Get program execution time in the shell

For a line-by-line delta measurement, try gnomon.

A command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

You can also use the --high and/or --medium options to specify a length threshold in seconds, over which gnomon will highlight the timestamp in red or yellow. And you can do a few other things, too.

example

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

webpack command not working

I had to reinstall webpack to get it working with my local version of webpack, e.g:

$ npm uninstall webpack
$ npm i -D webpack

Should I use 'border: none' or 'border: 0'?

In my point,

border:none is working but not valid w3c standard

so better we can use border:0;

How to use workbook.saveas with automatic Overwrite

To hide the prompt set xls.DisplayAlerts = False

ConflictResolution is not a true or false property, it should be xlLocalSessionChanges

Note that this has nothing to do with displaying the Overwrite prompt though!

Set xls = CreateObject("Excel.Application")    
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges    
wb.Close (True)

Apache server keeps crashing, "caught SIGTERM, shutting down"

I had mysterious SIGTERM shutdowns in our L.A.M.P. server, and it turned out to be an error in a custom PHP module, which was caused by mismatched versions. It was found by looking in the apache access/error logs at the time of malfunction. Don't forget to turn error logging on.

How to get the last N rows of a pandas DataFrame?

Don't forget DataFrame.tail! e.g. df1.tail(10)

AngularJS - get element attributes values

_x000D_
_x000D_
function onContentLoad() {_x000D_
  var item = document.getElementById("id1");_x000D_
  var x = item.dataset.x;_x000D_
  var data = item.dataset.myData;_x000D_
_x000D_
  var resX = document.getElementById("resX");_x000D_
  var resData = document.getElementById("resData");_x000D_
_x000D_
  resX.innerText = x;_x000D_
  resData.innerText = data;_x000D_
_x000D_
  console.log(x);_x000D_
  console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
  <div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
  Read 'x':_x000D_
  <label id="resX"></label>_x000D_
  <br/>Read 'my-data':_x000D_
  <label id="resData"></label>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Is it possible to implement a Python for range loop without an iterator variable?

Here's a random idea that utilizes (abuses?) the data model (Py3 link).

class Counter(object):
    def __init__(self, val):
        self.val = val

    def __nonzero__(self):
        self.val -= 1
        return self.val >= 0
    __bool__ = __nonzero__  # Alias to Py3 name to make code work unchanged on Py2 and Py3

x = Counter(5)
while x:
    # Do something
    pass

I wonder if there is something like this in the standard libraries?

How to change position of Toast in Android?

setting toast at topin screen

toast.setView(view);
toast.setGravity(Gravity.BOTTOM , 0, 0); // here i am setting toast at bottom
 toast.setDuration(Toast.LENGTH_LONG);
 toast.show(); 

now at bottom

 toast.setView(view);
 toast.setGravity(Gravity.BOTTOM , 0, 0); // here i am setting toast at bottom
 toast.setDuration(Toast.LENGTH_LONG);
 toast.show();  

the same way we can set toast in left, right and also center

Click here

Rails find_or_create_by more than one attribute?

Multiple attributes can be connected with an and:

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

(use find_or_initialize_by if you don't want to save the record right away)

Edit: The above method is deprecated in Rails 4. The new way to do it will be:

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create

and

GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize

Edit 2: Not all of these were factored out of rails just the attribute specific ones.

https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

Example

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

became

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

How can I disable the Maven Javadoc plugin from the command line?

The Javadoc generation can be skipped by setting the property maven.javadoc.skip to true [1], i.e.

-Dmaven.javadoc.skip=true

(and not false)

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

I had the same issue with gcc "gnat1" and it was due to the path being wrong. Gnat1 was on version 4.6 but I was executing version 4.8.1, which I had installed. As a temporary solution, I copied gnat1 from 4.6 and pasted under the 4.8.1 folder.

The path to gcc on my computer is /usr/lib/gcc/i686-linux-gnu/

You can find the path by using the find command:

find /usr -name "gnat1"

In your case you would look for cc1plus:

find /usr -name "cc1plus"

Of course, this is a quick solution and a more solid answer would be fixing the broken path.

How do I run a program with a different working directory from current, from Linux shell?

why not keep it simple

cd SOME_PATH && run_some_command && cd -

the last 'cd' command will take you back to the last pwd directory. This should work on all *nix systems.

Create an empty data.frame

Just declare

table = data.frame()

when you try to rbind the first line it will create the columns

Convert a negative number to a positive one in JavaScript

I know another way to do it. This technique works negative to positive & Vice Versa

var x = -24;
var result = x * -1;

Vice Versa:

var x = 58;
var result = x * -1;

LIVE CODE:

_x000D_
_x000D_
// NEGATIVE TO POSITIVE: ******************************************_x000D_
var x = -24;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// VICE VERSA: ****************************************************_x000D_
var x = 58;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// FLOATING POINTS: ***********************************************_x000D_
var x = 42.8;_x000D_
var result = x * -1;_x000D_
console.log(result);_x000D_
_x000D_
// FLOATING POINTS VICE VERSA: ************************************_x000D_
var x = -76.8;_x000D_
var result = x * -1;_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Tomcat 8 is not able to handle get request with '|' in query parameters?

Escape it. The pipe symbol is one that has been handled differently over time and between browsers. For instance, Chrome and Firefox convert a URL with pipe differently when copy/paste them. However, the most compatible, and necessary with Tomcat 8.5 it seems, is to escape it:

http://localhost:8080/app/handleResponse?msg=name%7Cid%7C

Best radio-button implementation for IOS

I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!

https://github.com/goosoftware/GSRadioButtonSetController

Letsencrypt add domain to existing certificate

You need to specify all of the names, including those already registered.

I used the following command originally to register some certificates:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--email [email protected] \
--expand -d example.com,www.example.com

... and just now I successfully used the following command to expand my registration to include a new subdomain as a SAN:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--expand -d example.com,www.example.com,click.example.com

From the documentation:

--expand "If an existing cert covers some subset of the requested names, always expand and replace it with the additional names."

Don't forget to restart the server to load the new certificates if you are running nginx.

"Cannot start compilation: the output path is not specified for module..."

You just have to go to your Module settings > Project and specify a "Project compiler output" and make your modules inherit from project. (For that go to Modules > Paths > Inherit project.

This did the trick for me.

Using margin:auto to vertically-align a div

variable height ,margin top and bottom auto

_x000D_
_x000D_
.black {background:rgba(0,0,0,.5);_x000D_
width: 300px;_x000D_
height: 100px;_x000D_
display: -webkit-flex; /* Safari */_x000D_
display: flex;}_x000D_
.message{_x000D_
background:tomato;_x000D_
margin:auto;_x000D_
padding:5%;_x000D_
width:auto;_x000D_
}
_x000D_
<div class="black">_x000D_
<div class="message">_x000D_
    This is a popup message._x000D_
</div>
_x000D_
_x000D_
_x000D_

variable height ,margin top and bottom auto

pip install mysql-python fails with EnvironmentError: mysql_config not found

On Mac:

brew install mysql-client

locate mysql

mdfind mysql | grep bin

then add to path

export PATH=$PATH:/usr/local/Cellar/mysql-client/8.0.23/bin/

or permanently

echo "export PATH=$PATH:/usr/local/Cellar/mysql-client/8.0.23/bin/" >> ~/.zshrc
source ~/.zshrc

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

The problem is that these two queries are each returning more than one row:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate

You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1), OR you can switch your = to IN and return multiple rows, like this:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

Fairly new to using PowerShell, think I might be able to help. Could you try this?

I believe you're not getting the correct parameters to your script block:

param([string]$one, [string]$two)
$res = Invoke-Command -Credential $migratorCreds -ScriptBlock {Get-LocalUsers -parentNodeXML $args[0] -migratorUser $args[1] } -ArgumentList $xmlPRE, $migratorCreds

"id cannot be resolved or is not a field" error?

Just came across this myself.

Finally found my issue was with a .png file that I added that had a capital letter in it an caused exactly the same problem. Eclipse never flagged the file until I closed it and opened Eclipse back up.

bootstrap datepicker setDate format dd/mm/yyyy

Changing to format: 'dd/mm/yyyy' didn't work for me, and changing that to dateFormat: 'dd/mm/yyyy' added year multiple times, The finest one for me was,

dateFormat: 'dd/mm/yy'

Create MSI or setup project with Visual Studio 2012

I think that Deploying an Office Solution by Using ClickOnce (MSDN) can be useful.

After creating an Outlook plugin for Office 2010 the problem was to install it on the customer's computer, without using ISLE or other complex tools (or expensive).

The solution was to use the publish instrument of the Visual Studio project, as described in the link. Just two things to be done before the setup will work:

Indent List in HTML and CSS

You can use [Adjacent sibling combinators] as described in the W3 CSS Selectors Recommendation1 So you can use a + sign (or even a ~ tilde) apply a padding to the nested ul tag, as you described in your question and you'll get the result you need. I also think what you want it to override the main css, locally. You can do this:

<style>
    li+ul {padding-left: 20px;}
</style>

This way the inner ul will be nested including the bullets of the li elements. I wish this was helpful! =)

Disabling SSL Certificate Validation in Spring RestTemplate

Java code example for HttpClient > 4.3

package com.example.teocodownloader;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class Example {
    public static void main(String[] args) {
        CloseableHttpClient httpClient
                = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
    }
}

By the way, don't forget to add the following dependencies to the pom file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

You could find Java code example for HttpClient < 4.3 as well.

HTML: How to make a submit button with text + image in it?

input type="submit" is the best way to have a submit button in a form. The downside of this is that you cannot put anything other than text as its value. The button element can contain other HTML elements and content.

Try putting type="submit" instead of type="button" in your button element (source).

Pay particular attention however to the following from that page:

If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the <button> and </button> tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.

Project vs Repository in GitHub

This is my personal understanding about the topic.

For a project, we can do the version control by different repositories. And for a repository, it can manage a whole project or part of projects.

Regarding on your project (several prototype applications which are independent of each them). You can manage the project by one repository or by several repositories, the difference:

  1. Manage by one repository. If one of the applications is changed, the whole project (all the applications) will be committed to a new version.

  2. Manage by several repositories. If one application is changed, it will only affect the repository which manages the application. Version for other repositories was not changed.

TypeLoadException says 'no implementation', but it is implemented

I also ran into this problem while running my unittests. The application ran fine and with no errors. The cause of the problem in my case was that I had turned off the building of the test projects. Reenabling the building of my testprojects solved the issues.

Case Statement Equivalent in R

case_when(), which was added to dplyr in May 2016, solves this problem in a manner similar to memisc::cases().

For example:

library(dplyr)
mtcars %>% 
  mutate(category = case_when(
    .$cyl == 4 & .$disp < median(.$disp) ~ "4 cylinders, small displacement",
    .$cyl == 8 & .$disp > median(.$disp) ~ "8 cylinders, large displacement",
    TRUE ~ "other"
  )
)

As of dplyr 0.7.0,

mtcars %>% 
  mutate(category = case_when(
    cyl == 4 & disp < median(disp) ~ "4 cylinders, small displacement",
    cyl == 8 & disp > median(disp) ~ "8 cylinders, large displacement",
    TRUE ~ "other"
  )
)

Show default value in Spinner in android

Try below:

   <Spinner
    android:id="@+id/YourSpinnerId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="Gender" />

SQL Server - Convert date field to UTC

If they're all local to you, then here's the offset:

SELECT GETDATE() AS CurrentTime, GETUTCDATE() AS UTCTime

and you should be able to update all the data using:

UPDATE SomeTable
   SET DateTimeStamp = DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), DateTimeStamp)

Would that work, or am I missing another angle of this problem?

Excel - match data from one range to another and get the value from the cell to the right of the matched data

I have added the following on my excel sheet

=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)

Still doesn't seem to work. I get an #N/A
BUT

=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)

Works

Basic example of using .ajax() with JSONP?

There is even easier way how to work with JSONP using jQuery

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.

How to change the size of the font of a JLabel to take the maximum size

label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));

taken from How to Use HTML in Swing Components

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

In my case adding Microsoft.AspNet.WebApi.Owin reference via nuget did the trick.

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

How to install "ifconfig" command in my ubuntu docker image?

I came here because I was trying to use ifconfig on the container to find its IPAaddress and there was no ifconfig. If you really need ifconfig on the container go with @vishnu-narayanan answer above, however you may be able to get the information you need by using docker inspect on the host:

docker inspect <containerid>

There is lots of good stuff in the output including IPAddress of container:

"Networks": {
    "bridge": {
        "IPAMConfig": null,
        "Links": null,
        "Aliases": null,
        "NetworkID": "12345FAKEID",
        "EndpointID": "12345FAKEENDPOINTID",
        "Gateway": "172.17.0.1",
        "IPAddress": "172.17.0.3",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "MacAddress": "01:02:03:04:05:06",
        "DriverOpts": null
    }
}

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

This had occurred to me and I have found out that it was because of faulty internet connection. If I use the public wifi at my place, which blocks various websites for security reasons, Mongo refuses to connect. But if I were to use my own mobile data, I can connect to the database.

C# Error "The type initializer for ... threw an exception

I got this error with my own code. My problem was that I had duplicate keys in the config file.

How to use <md-icon> in Angular Material?

md-icons aren't in the bower release of angular-material yet. I've been using Polymer's icons, they'll probably be the same anyway.

bower install polymer/core-icons

The performance impact of using instanceof in Java

Instanceof is very fast. It boils down to a bytecode that is used for class reference comparison. Try a few million instanceofs in a loop and see for yourself.

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

I use Ubuntu 18.04

Installing the corresponding "-dev" package worked for me,

sudo apt install libgconf2-dev

I was getting the below error till I installed the above package,

turtl: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory

Notification Icon with the new Firebase Cloud Messaging system

My solution is similar to ATom's one, but easier to implement. You don't need to create a class that shadows FirebaseMessagingService completely, you can just override the method that receives the Intent (which is public, at least in version 9.6.1) and take the information to be displayed from the extras. The "hacky" part is that the method name is indeed obfuscated and is gonna change every time you update the Firebase sdk to a new version, but you can look it up quickly by inspecting FirebaseMessagingService with Android Studio and looking for a public method that takes an Intent as the only parameter. In version 9.6.1 it's called zzm. Here's how my service looks like:

public class MyNotificationService extends FirebaseMessagingService {

    public void onMessageReceived(RemoteMessage remoteMessage) {
        // do nothing
    }

    @Override
    public void zzm(Intent intent) {
        Intent launchIntent = new Intent(this, SplashScreenActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R    equest code */, launchIntent,
                PendingIntent.FLAG_ONE_SHOT);
        Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setLargeIcon(rawBitmap)
                .setContentTitle(intent.getStringExtra("gcm.notification.title"))
                .setContentText(intent.getStringExtra("gcm.notification.body"))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager)     getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

How to use Java property files?

Example:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file 
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ",";                         //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);

How do I programmatically force an onchange event on an input?

ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:

document.getElementById("test").onchange()

Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

How do I change UIView Size?

Assigning questionFrame.frame.size.height= screenSize.height * 0.30 will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.

questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)

Mathematical functions in Swift

To be perfectly precise, Darwin is enough. No need to import the whole Cocoa framework.

import Darwin

Of course, if you need elements from Cocoa or Foundation or other higher level frameworks, you can import them instead

Using new line(\n) in string and rendering the same in HTML

You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
         var display_txt = "1st line text" +"\n" + "2nd line text";
         $('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>

<pre>
<p id="somediv"></p>
</pre>

</body>
</html>

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Error: class X is public should be declared in a file named X.java

Name of public class must match the name of .java file in which it is placed (like public class Foo{} must be placed in Foo.java file). So either:

  • rename your file from Main.java to WeatherArray.java
  • rename the class from public class WeatherArray { to public class Main {

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER

I had this same problem when using the Ruby Gem.

To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:

mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })

https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection

mongo_client = MongoClient.new # (optional host/port args)

Notice that 'args' is the third optional argument.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

No, there's no way to use browser JavaScript to improve password security. I highly recommend you read this article. In your case, the biggest problem is the chicken-egg problem:

What's the "chicken-egg problem" with delivering Javascript cryptography?

If you don't trust the network to deliver a password, or, worse, don't trust the server not to keep user secrets, you can't trust them to deliver security code. The same attacker who was sniffing passwords or reading diaries before you introduce crypto is simply hijacking crypto code after you do.

[...]

Why can't I use TLS/SSL to deliver the Javascript crypto code?

You can. It's harder than it sounds, but you safely transmit Javascript crypto to a browser using SSL. The problem is, having established a secure channel with SSL, you no longer need Javascript cryptography; you have "real" cryptography.

Which leads to this:

The problem with running crypto code in Javascript is that practically any function that the crypto depends on could be overridden silently by any piece of content used to build the hosting page. Crypto security could be undone early in the process (by generating bogus random numbers, or by tampering with constants and parameters used by algorithms), or later (by spiriting key material back to an attacker), or --- in the most likely scenario --- by bypassing the crypto entirely.

There is no reliable way for any piece of Javascript code to verify its execution environment. Javascript crypto code can't ask, "am I really dealing with a random number generator, or with some facsimile of one provided by an attacker?" And it certainly can't assert "nobody is allowed to do anything with this crypto secret except in ways that I, the author, approve of". These are two properties that often are provided in other environments that use crypto, and they're impossible in Javascript.

Basically the problem is this:

  • Your clients don't trust your servers, so they want to add extra security code.
  • That security code is delivered by your servers (the ones they don't trust).

Or alternatively,

  • Your clients don't trust SSL, so they want you use extra security code.
  • That security code is delivered via SSL.

Note: Also, SHA-256 isn't suitable for this, since it's so easy to brute force unsalted non-iterated passwords. If you decide to do this anyway, look for an implementation of bcrypt, scrypt or PBKDF2.

In java how to get substring from a string till a character c?

How about using regex?

String firstWord = filename.replaceAll("\\..*","")

This replaces everything from the first dot to the end with "" (ie it clears it, leaving you with what you want)

Here's a test:

System.out.println("abc.def.hij".replaceAll("\\..*", "");

Output:

abc

Python: Pandas Dataframe how to multiply entire column with a scalar

Also it's possible to use numerical indeces with .iloc.

df.iloc[:,0]  *= -1

What should a JSON service return on failure / error

I think if you just bubble an exception, it should be handled in the jQuery callback that is passed in for the 'error' option. (We also log this exception on the server side to a central log). No special HTTP error code required, but I'm curious to see what other folks do, too.

This is what I do, but that's just my $.02

If you are going to be RESTful and return error codes, try to stick to the standard codes set forth by the W3C: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Java variable number or arguments for a method

Variable number of arguments

It is possible to pass a variable number of arguments to a method. However, there are some restrictions:

  • The variable number of parameters must all be the same type
  • They are treated as an array within the method
  • They must be the last parameter of the method

To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:

private static int largest(int... numbers) {
     int currentLargest = numbers[0];
     for (int number : numbers) {
        if (number > currentLargest) {
            currentLargest = number;
        }
     }
     return currentLargest;
}

source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012

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

The correct syntax is:

FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
                                   , LCASE( SUBSTRING( NEW.bname, 2 ) ) )

How to read XML response from a URL in java?

I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm.

import org.xml.sax.*;
import javax.xml.parsers.*;

XMLReader        parser;

try {
    SAXParserFactory factory;

    factory = SAXParserFactory.newInstance ();
    factory.setNamespaceAware (true);
    parser = factory.newSAXParser ().getXMLReader ();
    // success!

} catch (FactoryConfigurationError err) {
    System.err.println ("can't create JAXP SAXParserFactory, "
    + err.getMessage ());
} catch (ParserConfigurationException err) {
    System.err.println ("can't create XMLReader with namespaces, "
    + err.getMessage ());
} catch (SAXException err) {
    System.err.println ("Hmm, SAXException, " + err.getMessage ());
}

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

When you use trusted connections, username and password are IGNORED, because SQL Server using windows authentication.

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

Select where count of one field is greater than one

For me, Not having a group by just returned empty result. So i guess having a group by for the having statement is pretty important

javax.net.ssl.SSLException: Received fatal alert: protocol_version

I was getting the same error. For Java version 7, following is working for me.

java.lang.System.setProperty("https.protocols", "TLSv1.2");

Binding a list in @RequestParam

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}

That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

This is the simplest solution :)

Accessing constructor of an anonymous class

That is not possible, but you can add an anonymous initializer like this:

final int anInt = ...;
Object a = new Class1()
{
  {
    System.out.println(anInt);
  }

  void someNewMethod() {
  }
};

Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.

Typescript : Property does not exist on type 'object'

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

This is not my answer, but I just copied it from https://gist.github.com/anonymous/2388015 just because the answer is awesome and fixes the problem completely. Credit completely goes to the anonymous author.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        if (/iPhone|iPod|iPad/.test(navigator.userAgent))
            $('iframe').wrap(function(){
                var $this = $(this);
                return $('<div />').css({
                    width: $this.attr('width'),
                    height: $this.attr('height'),
                    overflow: 'auto',
                    '-webkit-overflow-scrolling': 'touch'
                });
            });
    })
</script>

How do I convert an existing callback API to promises?

The callback style function always like this(almost all function in node.js is this style):

//fs.readdir(path[, options], callback)
fs.readdir('mypath',(err,files)=>console.log(files))

This style has same feature:

  1. the callback function is passed by last argument.

  2. the callback function always accept the error object as it's first argument.

So, you could write a function for convert a function with this style like this:

const R =require('ramda')

/**
 * A convenient function for handle error in callback function.
 * Accept two function res(resolve) and rej(reject) ,
 * return a wrap function that accept a list arguments,
 * the first argument as error, if error is null,
 * the res function will call,else the rej function.
 * @param {function} res the function which will call when no error throw
 * @param {function} rej the function which will call when  error occur
 * @return {function} return a function that accept a list arguments,
 * the first argument as error, if error is null, the res function
 * will call,else the rej function
 **/
const checkErr = (res, rej) => (err, ...data) => R.ifElse(
    R.propEq('err', null),
    R.compose(
        res,
        R.prop('data')
    ),
    R.compose(
        rej,
        R.prop('err')
    )
)({err, data})

/**
 * wrap the callback style function to Promise style function,
 * the callback style function must restrict by convention:
 * 1. the function must put the callback function where the last of arguments,
 * such as (arg1,arg2,arg3,arg...,callback)
 * 2. the callback function must call as callback(err,arg1,arg2,arg...)
 * @param {function} fun the callback style function to transform
 * @return {function} return the new function that will return a Promise,
 * while the origin function throw a error, the Promise will be Promise.reject(error),
 * while the origin function work fine, the Promise will be Promise.resolve(args: array),
 * the args is which callback function accept
 * */
 const toPromise = (fun) => (...args) => new Promise(
    (res, rej) => R.apply(
        fun,
        R.append(
            checkErr(res, rej),
            args
        )
    )
)

For more concise, above example used ramda.js. Ramda.js is a excellent library for functional programming. In above code, we used it's apply(like javascript function.prototype.apply) and append(like javascript function.prototype.push ). So, we could convert the a callback style function to promise style function now:

const {readdir} = require('fs')
const readdirP = toPromise(readdir)
readdir(Path)
    .then(
        (files) => console.log(files),
        (err) => console.log(err)
    )

toPromise and checkErr function is own by berserk library, it's a functional programming library fork by ramda.js(create by me).

Hope this answer is useful for you.

Why can't I duplicate a slice with `copy()`?

NOTE: This is an incorrect solution as @benlemasurier proved

Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice), which copies the slice. This code:

package main

import "fmt"

func main() {
    var foo = []int{1, 2, 3, 4, 5}
    fmt.Println("foo:", foo)
    var bar = append(foo)
    fmt.Println("bar:", bar)
    bar = append(bar, 6)
    fmt.Println("foo after:", foo)
    fmt.Println("bar after:", bar)
}

Outputs this:

foo: [1 2 3 4 5]
bar: [1 2 3 4 5]
foo after: [1 2 3 4 5]
bar after: [1 2 3 4 5 6]

R - argument is of length zero in if statement

The simplest solution to the problem is to change your for loop statement :

Instead of using

      for (i in **0**:n))

Use

      for (i in **1**:n))

Go To Definition: "Cannot navigate to the symbol under the caret."

I'm using VS 2017 15.7.5 and this stopped working for certain test files. I noticed that they were all the new ones I had recently added and that in Solution Explorer there was no arrow available to expand and see the properties / methods.

I excluded and then re-included them into my project and the go to definition command worked again.

How does strcmp() work?

This, from the masters themselves (K&R, 2nd ed., pg. 106):

// strcmp: return < 0 if s < t, 0 if s == t, > 0 if s > t
int strcmp(char *s, char *t) 
{
    int i;

    for (i = 0; s[i] == t[i]; i++)
        if (s[i] == '\0')
            return 0;
    return s[i] - t[i];
}

getActivity() returns null in Fragment function

PJL is right. I have used his suggestion and this is what i have done:

  1. defined global variables for fragment:

    private final Object attachingActivityLock = new Object();

    private boolean syncVariable = false;

  2. implemented

@Override
public void onAttach(Activity activity) {
  super.onAttach(activity);
  synchronized (attachingActivityLock) {
      syncVariable = true;
      attachingActivityLock.notifyAll();
  }
}

3 . I wrapped up my function, where I need to call getActivity(), in thread, because if it would run on main thread, i would block the thread with the step 4. and onAttach() would never be called.

    Thread processImage = new Thread(new Runnable() {

        @Override
        public void run() {
            processImage();
        }
    });
    processImage.start();

4 . in my function where I need to call getActivity(), I use this (before the call getActivity())

    synchronized (attachingActivityLock) {
        while(!syncVariable){
            try {
                attachingActivityLock.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

If you have some UI updates, remember to run them on UI thread. I need to update ImgeView so I did:

image.post(new Runnable() {

    @Override
    public void run() {
        image.setImageBitmap(imageToShow);
    }
});

What is "pom" packaging in maven?

To simply answer your question when you do a mvn:install, maven will create a packaged artifact based on (packaging attribute in pom.xml), After you run your maven install you can find the file with .package extension

  • In target directory of the project workspace
  • Also where your maven 2 local repository is search for (.m2/respository) on your box, Your artifact is listed in .m2 repository under (groupId/artifactId/artifactId-version.packaging) directory
  • If you look under the directory you will find packaged extension file and also pom extension (pom extension is basically the pom.xml used to generate this package)
  • If your maven project is multi-module each module will two files as described above except for the top level project that will only have a pom

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

Which is better, return value or out parameter?

return value is the normal value which is returned by your method.

Where as out parameter, well out and ref are 2 key words of C# they allow to pass variables as reference.

The big difference between ref and out is, ref should be initialised before and out don't

Word wrapping in phpstorm

  • File | Settings | Editor --> Use soft wraps in editor : to turn them on for all files by default.

  • File | Settings | Code Style | General --> Wrap when typing reaches right margin

    .. but that's different (it will make new line).

Qt Creator color scheme

I found a way to change the Application Output theme and everything that can't be edited from .css.

If you use osX:

  1. Navigate to your Qt install directory.
  2. Right click Qt Creator application and select "Show Package Contents"
  3. Copy the following file to your desktop> Contents/Resources/themes/dark.creatortheme or /default.creatortheme. Depending on if you are using dark theme or default theme.
  4. Edit the file in text editor.
  5. Under [Palette], there is a line that says error=ffff0000.
  6. Set a new color, save, and override the original file.

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.

I did it a different way, without using VBA, by using a table containing the query parameters.

E.g:

SELECT a_table.a_field 
FROM QueryParameters, a_table 
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min 
AND QueryParameters.a_field_max

Where QueryParameters is a table with two fields, a_field_min and a_field_max

It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.

javascript node.js next()

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

See, for example, the code samples here:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
        res.redirect('/sessions/new');
      }
    });
  } else {
    res.redirect('/sessions/new');
  }
}

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...
});

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

There's nothing special about the name next in this example; we could have named it anything.

Sample database for exercise

You want huge?

Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));

insert into foo(crap) values ('');

-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;

run it twenty more times, you have over a million rows to play with.

Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)

Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".

Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.

Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.

Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.

For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.

Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.

By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

Slight update to cumul's solution.

The function upperFirstAll doesn't work properly if there is more than one space between words. Replace the regular expression for this one to solve it:

$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)+(.)/g,

Join a list of items with different types as string in Python

For example:

lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]

lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']

As to me, I want to add a str before each str list:

# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']

Or single list:

lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482

lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482

What is a NullPointerException, and how do I fix it?

When you declare a reference variable (i.e., an object), you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int:

int x;
x = 10;

In this example, the variable x is an int and Java will initialize it to 0 for you. When you assign the value of 10 on the second line, your value of 10 is written into the memory location referred to by x.

But, when you try to declare a reference type, something different happens. Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is Integer which is a reference type). Since you have not yet said what to point to, Java sets it to null, which means "I am pointing to nothing".

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the pointer variable num is assigned to that Integer object.

The NullPointerException (NPE) occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable (called dereferencing). So you are pointing to something that does not actually exist.

Dereferencing usually happens when using . to access a method or field, or using [ to index an array.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

public void doSomething(SomeObject obj) {
   // Do something to obj, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

doSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       // Do something
    } else {
       // Do something else
    }
}

Finally, How to pinpoint the exception & cause using Stack Trace

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006. The following is 2 minutes read to understand this amazing language feature.

https://jfeatures.com/blog/NullPointerException

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

Given the lat/long coordinates, how can we find out the city/country?

I was searching for a similar functionality and I saw the data "http://download.geonames.org/export/dump/" shared on earlier reply (thank you for sharing, it is an excellent source), and implemented a service based on the cities1000.txt data.

You can see it running at http://scatter-otl.rhcloud.com/location?lat=36&long=-78.9 (broken link) Just change the latitude and longitude for your locations.

It is deployed on OpenShift (RedHat Platform). First call after a long idle period may take sometime, but usually performance is satisfactory. Feel free to use this service as you like...

Also, you can find the project source at https://github.com/turgos/Location.

java: use StringBuilder to insert at the beginning

This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an exit condition.

public class Test {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        doRecursive(sb, 100, 0);
        System.out.println(sb.toString());
    }

    public static void doRecursive(StringBuilder sb, int limit, int index) {
        if (index < limit) {
            doRecursive(sb, limit, index + 1);
            sb.append(Integer.toString(index));
        }
    }
}

Add a space (" ") after an element using :after

I needed this instead of using padding because I used inline-block containers to display a series of individual events in a workflow timeline. The last event in the timeline needed no arrow after it.

Ended up with something like:

.transaction-tile:after {
  content: "\f105";
}

.transaction-tile:last-child:after {
  content: "\00a0";
}

Used fontawesome for the gt (chevron) character. For whatever reason "content: none;" was producing alignment issues on the last tile.

How to get the user input in Java?

You can get user input using BufferedReader.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;  

System.out.println("Enter your Account number: ");
accStr = br.readLine();

It will store a String value in accStr so you have to parse it to an int using Integer.parseInt.

int accInt = Integer.parseInt(accStr);

How to create a Multidimensional ArrayList in Java?

Once I required 2-D arrayList and I created using List and ArrayList and the code is as follows:

import java.util.*;

public class ArrayListMatrix {

    public static void main(String args[]){

        List<ArrayList<Integer>> a = new ArrayList<>();

        ArrayList<Integer> a1 = new ArrayList<Integer>();
        ArrayList<Integer> a2 = new ArrayList<Integer>();
        ArrayList<Integer> a3 = new ArrayList<Integer>();


        a1.add(1);
        a1.add(2);
        a1.add(3);

        a2.add(4);
        a2.add(5);
        a2.add(6);

        a3.add(7);
        a3.add(8);
        a3.add(9);

        a.add(a1);
        a.add(a2);
        a.add(a3);


        for(ArrayList obj:a){

            ArrayList<Integer> temp = obj;

            for(Integer job : temp){
                System.out.print(job+" ");
            }
            System.out.println();
        }
    }
}

Output:

1 2 3

4 5 6

7 8 9

Source : https://www.codepuran.com/java/2d-matrix-arraylist-collection-class-java/

Bootstrap 3 .col-xs-offset-* doesn't work?

Remove the dot in front of your class so it looks like this:

<div class="col-xs-2 col-xs-offset-1">col</div>

How can I get a file's size in C++?

If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.

How can I delete a file from a Git repository?

Additionally, if it's a folder to be removed and it's subsequent child folders or files, use:

git rm -r foldername

subtract two times in python

The python timedelta library should do what you need. A timedelta is returned when you subtract two datetime instances.

import datetime
dt_started = datetime.datetime.utcnow()

# do some stuff

dt_ended = datetime.datetime.utcnow()
print((dt_ended - dt_started).total_seconds())

How to delete a row from GridView?

You're deleting the row from the gridview and then rebinding it to the datasource (which still contains the row). Either delete the row from the datasource, or don't rebind the gridview afterwards.

How to set the image from drawable dynamically in android?

Try this Dynamic code

String fnm = "cat"; //  this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null);
System.out.println("IMG ID :: "+imgId);
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME);
//    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));

In above code you will need Image-file-Name and Image-View object which both you are having.

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())