Programs & Examples On #Gnu classpath

GNU Classpath - Essential Libraries for Java, is a GNU project to create free core class libraries.

How to create an exit message

I got here searching for a way to execute some code whenever the program ends.
Found this:

Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call

Called multiple times will register multiple handlers.

How do you attach and detach from Docker's process?

To detach from the container you simply hold Ctrl and press P + Q.

To attach to a running container you use:

$ docker container attach "container_name"

What is ADT? (Abstract Data Type)

The Abstact data type Wikipedia article has a lot to say.

In computer science, an abstract data type (ADT) is a mathematical model for a certain class of data structures that have similar behavior; or for certain data types of one or more programming languages that have similar semantics. An abstract data type is defined indirectly, only by the operations that may be performed on it and by mathematical constraints on the effects (and possibly cost) of those operations.

In slightly more concrete terms, you can take Java's List interface as an example. The interface doesn't explicitly define any behavior at all because there is no concrete List class. The interface only defines a set of methods that other classes (e.g. ArrayList and LinkedList) must implement in order to be considered a List.

A collection is another abstract data type. In the case of Java's Collection interface, it's even more abstract than List, since

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods.

A bag is also known as a multiset.

In mathematics, the notion of multiset (or bag) is a generalization of the notion of set in which members are allowed to appear more than once. For example, there is a unique set that contains the elements a and b and no others, but there are many multisets with this property, such as the multiset that contains two copies of a and one of b or the multiset that contains three copies of both a and b.

In Java, a Bag would be a collection that implements a very simple interface. You only need to be able to add items to a bag, check its size, and iterate over the items it contains. See Bag.java for an example implementation (from Sedgewick & Wayne's Algorithms 4th edition).

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

A quicker way to write it

var arrayBuffer = new Uint8Array(nodeBuffer).buffer;

However, this appears to run roughly 4 times slower than the suggested toArrayBuffer function on a buffer with 1024 elements.

Where is the kibana error log? Is there a kibana error log?

Kibana 4 logs to stdout by default. Here is an excerpt of the config/kibana.yml defaults:

# Enables you specify a file where Kibana stores log output.
# logging.dest: stdout

So when invoking it with service, use the log capture method of that service. For example, on a Linux distribution using Systemd / systemctl (e.g. RHEL 7+):

journalctl -u kibana.service

One way may be to modify init scripts to use the --log-file option (if it still exists), but I think the proper solution is to properly configure your instance YAML file. For example, add this to your config/kibana.yml:

logging.dest: /var/log/kibana.log

Note that the Kibana process must be able to write to the file you specify, or the process will die without information (it can be quite confusing).

As for the --log-file option, I think this is reserved for CLI operations, rather than automation.

How to set HTML5 required attribute in Javascript?

What matters isn't the attribute but the property, and its value is a boolean.

You can set it using

 document.getElementById("edName").required = true;

How to check if a specific key is present in a hash or not?

While Hash#has_key? gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

hash.key?(some_key)

How to remove youtube branding after embedding video in web page?

I tried this, but it is not possible to remove "Watch on YouTube" icon. Following solution of mine does not remove the icon itself but "blocks" the mouse hover so that watch on YouTube is not click-able. I added a div over icon, so no mouseover will be affected for that logo.

 <div class="holder">
     <div class="frame" id="player" style="height 350"></div>
     <div class="bar" id="bottom-layer">.</div>
 </div>

Where frame is my embedded player. include following to your css file

.holder{
position:relative;
width:640px;
height:350px;
}

.frame{
width: 100%;
height:100%;
}

.bar{
position:absolute;
bottom:0;
right:0;
width:100%;
height:40px;
}

This is not full solution but helps you if you are bothered with users' getting full youtube url.

Ansible date variable

I tried the lookup('pipe,'date') method and got trouble when I push the playbook to the tower. The tower is somehow using UTC timezone. All play executed as early as the + hours of my TZ will give me one day later of the actual date.

For example: if my TZ is Asia/Manila I supposed to have UTC+8. If I execute the playbook earlier than 8:00am in Ansible Tower, the date will follow to what was in UTC+0. It took me a while until I found this case. It let me use the date option '-d \"+8 hours\" +%F'. Now it gives me the exact date that I wanted.

Below is the variable I set in my playbook:

  vars:
    cur_target_wd: "{{ lookup('pipe','date -d \"+8 hours\" +%Y/%m-%b/%d-%a') }}"

That will give me the value of "cur_target_wd = 2020/05-May/28-Thu" even I run it earlier than 8:00am now.

Compare two files line by line and generate the difference in another file

If you have a CSV file with single or even multiple columns, you can do these line by line "diff" operations using the sqlite3 embedded db. It comes with python, so should be available on most linux/macs. You can script the sqlite3 commands on the bash shell without needing to write python.

  1. Create your a.csv and b.csv files
  2. Ensure sqlite3 is installed using the command "sqlite3 -help"
  3. Run the below commands directly on the Linux/Mac shell (or put it in a script)
echo "
.mode csv
.import a.csv atable
.import b.csv btable
create table result as select * from atable EXCEPT select * from btable;
.output result.csv
select * from result ;
.quit
" | sqlite3 temp.db

Note : Ensure there is a newline for each of the sqlite3 commands.

How it works

  1. Import the 2 csvs into "atable" and "btable" respectively.
  2. Use the "except" sql operator to select the data available in "atable" but missing in "btable". Create a "result" table using the select query statement
  3. Output the result table to result.csv by running "select * from result;"

If you need to operate on specific columns, sqlite3 or any db is the way to go.

I have tried diff'ing on multiple GB files using the builtin diff and comm tools. Sqlite beats linux utilities by a mile.

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

Jquery date picker z-index issue

simply in your css use '.ui-datepicker{ z-index: 9999 !important;}' Here 9999 can be replaced to whatever layer value you want your datepicker available. Neither any code is to be commented nor adding 'position:relative;' css on input elements. Because increasing the z-index of input elements will have effect on all input type buttons, which may not be needed for some cases.

Removing pip's cache?

Since pip 20.1b1, which was released on 21 April 2020 and "added pip cache command for inspecting/managing pip’s wheel cache", it is possible to issue this command:

pip cache purge

The reference guide is here:
https://pip.pypa.io/en/stable/reference/pip_cache/
The corresponding pull request is here.

MINGW64 "make build" error: "bash: make: command not found"

  • Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/

  • Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)

  • Extract zip
  • Copy the contents to C:\ProgramFiles\Git\mingw64\ merging the folders, but do NOT overwrite/replace any exisiting files.

How to store a dataframe using Pandas

The easiest way is to pickle it using to_pickle:

df.to_pickle(file_name)  # where to save it, usually as a .pkl

Then you can load it back using:

df = pd.read_pickle(file_name)

Note: before 0.11.1 save and load were the only way to do this (they are now deprecated in favor of to_pickle and read_pickle respectively).


Another popular choice is to use HDF5 (pytables) which offers very fast access times for large datasets:

import pandas as pd
store = pd.HDFStore('store.h5')

store['df'] = df  # save it
store['df']  # load it

More advanced strategies are discussed in the cookbook.


Since 0.13 there's also msgpack which may be be better for interoperability, as a faster alternative to JSON, or if you have python object/text-heavy data (see this question).

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

I modified from @PsychoCoder. All controls could be found now (include nested).

public static IEnumerable<T> GetChildrens<T>(Control control)
{
  var type = typeof (T);

  var allControls = GetAllChildrens(control);

  return allControls.Where(c => c.GetType() == type).Cast<T>();
}

private static IEnumerable<Control> GetAllChildrens(Control control)
{
  var controls = control.Controls.Cast<Control>();
  return controls.SelectMany(c => GetAllChildrens(c))
    .Concat(controls);
}

Resizing image in Java

If you have an java.awt.Image, rezising it doesn't require any additional libraries. Just do:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

Ovbiously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.

There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:

See the Javadoc for more info.

How is OAuth 2 different from OAuth 1?

Note there are serious security arguments against using Oauth 2:

one bleak article

and a more technical one

Note these are coming from Oauth 2's lead author.

Key points:

  • Oauth 2 offers no security on top of SSL while Oauth 1 is transport-independent.

  • in a sense SSL isn't secure in that the server does not verify the connection and the common client libraries make it easy to ignore failures.

    The problem with SSL/TLS, is that when you fail to verify the certificate on the client side, the connection still works. Any time ignoring an error leads to success, developers are going to do just that. The server has no way of enforcing certificate verification, and even if it could, an attacker will surely not.

  • you can fat-finger away all of your security, which is much harder to do in OAuth 1.0:

    The second common potential problem are typos. Would you consider it a proper design when omitting one character (the ‘s’ in ‘https’) voids the entire security of the token? Or perhaps sending the request (over a valid and verified SSL/TLS connection) to the wrong destination (say ‘http://gacebook.com’?). Remember, being able to use OAuth bearer tokens from the command line was clearly a use case bearer tokens advocates promoted.

change array size

You can use Array.Resize(), documented in MSDN.

But yeah, I agree with Corey, if you need a dynamically sized data structure, we have Lists for that.

Important: Array.Resize() doesn't resize the array (the method name is misleading), it creates a new array and only replaces the reference you passed to the method.

An example:

var array1 = new byte[10];
var array2 = array1;
Array.Resize<byte>(ref array1, 20);

// Now:
// array1.Length is 20
// array2.Length is 10
// Two different arrays.

Which command do I use to generate the build of a Vue app?

I think you can use vue-cli

If you are using Vue CLI along with a backend framework that handles static assets as part of its deployment, all you need to do is making sure Vue CLI generates the built files in the correct location, and then follow the deployment instruction of your backend framework.

If you are developing your frontend app separately from your backend - i.e. your backend exposes an API for your frontend to talk to, then your frontend is essentially a purely static app. You can deploy the built content in the dist directory to any static file server, but make sure to set the correct baseUrl

Is it possible to start a shell session in a running container (without ssh)

Keep an eye on this pull request: https://github.com/docker/docker/pull/7409

Which implements the forthcoming docker exec <container_id> <command> utility. When this is available it should be possible to e.g. start and stop the ssh service inside a running container.

There is also nsinit to do this: "nsinit provides a handy way to access a shell inside a running container's namespace", but it looks difficult to get running. https://gist.github.com/ubergarm/ed42ebbea293350c30a6

sys.argv[1], IndexError: list index out of range

sys.argv is the list of command line arguments passed to a Python script, where sys.argv[0] is the script name itself.

It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv[1] is out of bounds.

To "fix", just make sure to pass a commandline argument when you run the script, e.g.

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

REST, HTTP DELETE and parameters

It's an old question, but here are some comments...

  1. In SQL, the DELETE command accepts a parameter "CASCADE", which allows you to specify that dependent objects should also be deleted. This is an example of a DELETE parameter that makes sense, but 'man rm' could provide others. How would these cases possibly be implemented in REST/HTTP without a parameter?
  2. @Jan, it seems to be a well-established convention that the path part of the URL identifies a resource, whereas the querystring does not (at least not necessarily). Examples abound: getting the same resource but in a different format, getting specific fields of a resource, etc. If we consider the querystring as part of the resource identifier, it is impossible to have a concept of "different views of the same resource" without turning to non-RESTful mechanisms such as HTTP content negotiation (which can be undesirable for many reasons).

Missing Authentication Token while accessing API Gateway?

In my case it was quite a stupid thing. I've get used that new entities are created using POST and it was failing with "Missing Authentication Token". I've missed that for some reason it was defined as PUT which is working fine.

Warning - Build path specifies execution environment J2SE-1.4

Just change the version in Window-> Preferences-> Java -> Installed JREs. Check the installed JREs list. Then, Right-click on your project -> properties -> Java build path -> libraries. Change the "JRE System Library" to the version in "installed JREs".

The warning will be gone.

How to get dictionary values as a generic list

Dictionary<string, MyType> myDico = GetDictionary();

var items = myDico.Select(d=> d.Value).ToList();

If hasClass then addClass to parent

You probably want to change the condition to if ($(this).hasClass('active'))

Also, hasClass and addClass take classnames, not selectors.
Therefore, you shouldn't include a ..

Efficient way to add spaces between characters in a string

The most efficient way is to take input make the logic and run

so the code is like this to make your own space maker

need = input("Write a string:- ")
result = ''
for character in need:
   result = result + character + ' '
print(result)    # to rid of space after O

but if you want to use what python give then use this code

need2 = input("Write a string:- ")

print(" ".join(need2))

Making PHP var_dump() values display one line per value

If you got XDebug installed, you can use it's var_dump replacement. Quoting:

Xdebug replaces PHP's var_dump() function for displaying variables. Xdebug's version includes different colors for different types and places limits on the amount of array elements/object properties, maximum depth and string lengths. There are a few other functions dealing with variable display as well.

You will likely want to tweak a few of the following settings:

There is a number of settings that control the output of Xdebug's modified var_dump() function: xdebug.var_display_max_children, xdebug.var_display_max_data and xdebug.var_display_max_depth. The effect of these three settings is best shown with an example. The script below is run four time, each time with different settings. You can use the tabs to see the difference.

But keep in mind that XDebug will significantly slow down your code, even when it's just loaded. It's not advisable to run in on production servers. But hey, you are not var_dumping on production servers anyway, are you?

C - error: storage size of ‘a’ isn’t known

correct typo of

struct xyz a;

to

struct xyx a;

Better you can try typedef, easy to b

Is it better to use "is" or "==" for number comparison in Python?

Others have answered your question, but I'll go into a little bit more detail:

Python's is compares identity - it asks the question "is this one thing actually the same object as this other thing" (similar to == in Java). So, there are some times when using is makes sense - the most common one being checking for None. Eg, foo is None. But, in general, it isn't what you want.

==, on the other hand, asks the question "is this one thing logically equivalent to this other thing". For example:

>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False

And this is true because classes can define the method they use to test for equality:

>>> class AlwaysEqual(object):
...     def __eq__(self, other):
...         return True
...
>>> always_equal = AlwaysEqual()
>>> always_equal == 42
True
>>> always_equal == None
True

But they cannot define the method used for testing identity (ie, they can't override is).

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

Once you have established that they don't match, you still have a problem -- what to do about it. Often, the certificate may merely be assembled incorrectly. When a CA signs your certificate, they send you a block that looks something like

-----BEGIN CERTIFICATE-----
MIIAA-and-a-buncha-nonsense-that-is-your-certificate
-and-a-buncha-nonsense-that-is-your-certificate-and-
a-buncha-nonsense-that-is-your-certificate-and-a-bun
cha-nonsense-that-is-your-certificate-and-a-buncha-n
onsense-that-is-your-certificate-AA+
-----END CERTIFICATE-----

they'll also send you a bundle (often two certificates) that represent their authority to grant you a certificate. this will look something like

-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-your-request
-this-is-the-certificate-that-signed-your-request-this
-is-the-certificate-that-signed-your-request-this-is-t
he-certificate-that-signed-your-request-this-is-the-ce
rtificate-that-signed-your-request-A
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-for-that-one
-this-is-the-certificate-that-signed-for-that-one-this
-is-the-certificate-that-signed-for-that-one-this-is-t
he-certificate-that-signed-for-that-one-this-is-the-ce
rtificate-that-signed-for-that-one-this-is-the-certifi
cate-that-signed-for-that-one-AA
-----END CERTIFICATE-----

except that unfortunately, they won't be so clearly labeled.

a common practice, then, is to bundle these all up into one file -- your certificate, then the signing certificates. But since they aren't easily distinguished, it sometimes happens that someone accidentally puts them in the other order -- signing certs, then the final cert -- without noticing. In that case, your cert will not match your key.

You can test to see what the cert thinks it represents by running

openssl x509 -noout -text -in yourcert.cert

Near the top, you should see "Subject:" and then stuff that looks like your data. If instead it lookslike your CA, your bundle is probably in the wrong order; you might try making a backup, and then moving the last cert to the beginning, hoping that is the one that is your cert.

If this doesn't work, you might just have to get the cert re-issued. When I make a CSR, I like to clearly label what server it's for (instead of just ssl.key or server.key) and make a copy of it with the date in the name, like mydomain.20150306.key etc. that way they private and public key pairs are unlikely to get mixed up with another set.

SSRS Query execution failed for dataset

I experienced the same issue, it was related to security not being granted to part of the tables. review your user has access to the databases/ tables/views/functions etc used by the report.

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

javascript return true or return false when and how to use it?

returning true or false indicates that whether execution should continue or stop right there. So just an example

<input type="button" onclick="return func();" />

Now if func() is defined like this

function func()
{
 // do something
return false;
}

the click event will never get executed. On the contrary if return true is written then the click event will always be executed.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

Here are my working example

@RequestMapping(value = "/api/v1/files/upload", method =RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("files") MultipartFile[] files) {
    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    List<String> tempFileNames = new ArrayList<>();
    String tempFileName;
    FileOutputStream fo;

    try {
        for (MultipartFile file : files) {
            tempFileName = "/tmp/" + file.getOriginalFilename();
            tempFileNames.add(tempFileName);
            fo = new FileOutputStream(tempFileName);
            fo.write(file.getBytes());
            fo.close();
            map.add("files", new FileSystemResource(tempFileName));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
        String response = restTemplate.postForObject(uploadFilesUrl, requestEntity, String.class);

    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String fileName : tempFileNames) {
        File f = new File(fileName);
        f.delete();
    }
    return new ResponseEntity<Object>(HttpStatus.OK);
}

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

Include another JSP file

What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.

What you need is a dynamic include:

<jsp:include page="..." />

Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.

Could not create the Java virtual machine

Just be careful. You will get this message if you try to enter a command that doesn't exist like this

/usr/bin/java -v

VSCode cannot find module '@angular/core' or any other modules

Occurs when cloning or opening existing projects in Visual Studio Code. In the integrated terminal run the command npm install

Avoid duplicates in INSERT INTO SELECT query in SQL Server

Using NOT EXISTS:

INSERT INTO TABLE_2
  (id, name)
SELECT t1.id,
       t1.name
  FROM TABLE_1 t1
 WHERE NOT EXISTS(SELECT id
                    FROM TABLE_2 t2
                   WHERE t2.id = t1.id)

Using NOT IN:

INSERT INTO TABLE_2
  (id, name)
SELECT t1.id,
       t1.name
  FROM TABLE_1 t1
 WHERE t1.id NOT IN (SELECT id
                       FROM TABLE_2)

Using LEFT JOIN/IS NULL:

INSERT INTO TABLE_2
  (id, name)
   SELECT t1.id,
          t1.name
     FROM TABLE_1 t1
LEFT JOIN TABLE_2 t2 ON t2.id = t1.id
    WHERE t2.id IS NULL

Of the three options, the LEFT JOIN/IS NULL is less efficient. See this link for more details.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

In the middle of the stack trace, lost in the "reflection" junk, you can find the root cause:

The specified datastore driver ("com.mysql.jdbc.Driver") was not found in the CLASSPATH. Please check your CLASSPATH specification, and the name of the driver.

Using a Python subprocess call to invoke a Python script

Windows? Unix?

Unix will need a shebang and exec attribute to work:

#!/usr/bin/env python

as the first line of script and:

chmod u+x script.py

at command-line or

call('python script.py'.split())

as mentioned previously.

Windows should work if you add the shell=True parameter to the "call" call.

What is the difference between Java RMI and RPC?

RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.

Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.

How do I compile the asm generated by GCC?

Yes, gcc can also compile assembly source code. Alternatively, you can invoke as, which is the assembler. (gcc is just a "driver" program that uses heuristics to call C compiler, C++ compiler, assembler, linker, etc..)

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

Decimal number regular expression, where digit after decimal is optional

In Perl, use Regexp::Common which will allow you to assemble a finely-tuned regular expression for your particular number format. If you are not using Perl, the generated regular expression can still typically be used by other languages.

Printing the result of generating the example regular expressions in Regexp::Common::Number:

$ perl -MRegexp::Common=number -E 'say $RE{num}{int}'
(?:(?:[-+]?)(?:[0123456789]+))

$ perl -MRegexp::Common=number -E 'say $RE{num}{real}'
(?:(?i)(?:[-+]?)(?:(?=[.]?[0123456789])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[-+]?)(?:[0123456789]+))|))

$ perl -MRegexp::Common=number -E 'say $RE{num}{real}{-base=>16}'
(?:(?i)(?:[-+]?)(?:(?=[.]?[0123456789ABCDEF])(?:[0123456789ABCDEF]*)(?:(?:[.])(?:[0123456789ABCDEF]{0,}))?)(?:(?:[G])(?:(?:[-+]?)(?:[0123456789ABCDEF]+))|))

Android Viewpager as Image Slide Gallery

Just use this https://gist.github.com/8cbe094bb7a783e37ad1 for make surrounding pages visible and http://viewpagerindicator.com/ this, for indicator. That's pretty cool, i'm using it for a gallery.

Sort a List of objects by multiple fields

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
            }
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

How can I create a keystore?

If you don't want to or can't use Android Studio, you can use the create-android-keystore NPM tool:

$ create-android-keystore quick

Which results in a newly generated keystore in the current directory.

More info: https://www.npmjs.com/package/create-android-keystore

Generate sql insert script from excel worksheet

I think importing using one of the methods mentioned is ideal if it truly is a large file, but you can use Excel to create insert statements:

="INSERT INTO table_name VALUES('"&A1&"','"&B1&"','"&C1&"')"

In MS SQL you can use:

SET NOCOUNT ON

To forego showing all the '1 row affected' comments. And if you are doing a lot of rows and it errors out, put a GO between statements every once in a while

How do I push amended commit to the remote Git repository?

You are seeing a Git safety feature. Git refuses to update the remote branch with your branch, because your branch's head commit is not a direct descendent of the current head commit of the branch that you are pushing to.

If this were not the case, then two people pushing to the same repository at about the same time would not know that there was a new commit coming in at the same time and whoever pushed last would lose the work of the previous pusher without either of them realising this.

If you know that you are the only person pushing and you want to push an amended commit or push a commit that winds back the branch, you can 'force' Git to update the remote branch by using the -f switch.

git push -f origin master

Even this may not work as Git allows remote repositories to refuse non-fastforward pushes at the far end by using the configuration variable receive.denynonfastforwards. If this is the case the rejection reason will look like this (note the 'remote rejected' part):

 ! [remote rejected] master -> master (non-fast forward)

To get around this, you either need to change the remote repository's configuration or as a dirty hack you can delete and recreate the branch thus:

git push origin :master
git push origin master

In general the last parameter to git push uses the format <local_ref>:<remote_ref>, where local_ref is the name of the branch on the local repository and remote_ref is the name of the branch on the remote repository. This command pair uses two shorthands. :master has a null local_ref which means push a null branch to the remote side master, i.e. delete the remote branch. A branch name with no : means push the local branch with the given name to the remote branch with the same name. master in this situation is short for master:master.

What is attr_accessor in Ruby?

Basically they fake publicly accessible data attributes, which Ruby doesn't have.

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
 8) org.jmeld.vc.svn.InfoCmd
 9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#? 

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

ValueError: could not convert string to float: id

Perhaps your numbers aren't actually numbers, but letters masquerading as numbers?

In my case, the font I was using meant that "l" and "1" looked very similar. I had a string like 'l1919' which I thought was '11919' and that messed things up.

Android - Dynamically Add Views into View

// Parent layout
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);

// Layout inflater
LayoutInflater layoutInflater = getLayoutInflater();
View view;

for (int i = 1; i < 101; i++){
    // Add the text layout to the parent layout
    view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);

    // In order to get the view we have to use the new view with text_layout in it
    TextView textView = (TextView)view.findViewById(R.id.text);
    textView.setText("Row " + i);

    // Add the text view to the parent layout
    parentLayout.addView(textView);
}

Make elasticsearch only return certain fields?

A REST API GET request could be made with '_source' parameter.

Example Request

http://localhost:9200/opt_pr/_search?q=SYMBOL:ITC AND OPTION_TYPE=CE AND TRADE_DATE=2017-02-10 AND EXPIRY_DATE=2017-02-23&_source=STRIKE_PRICE

Response

{
"took": 59,
"timed_out": false,
"_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
},
"hits": {
    "total": 104,
    "max_score": 7.3908954,
    "hits": [
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLc",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 160
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLh",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 185
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLi",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 190
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLm",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 210
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLp",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 225
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLr",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 235
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLw",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 260
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uL5",
            "_score": 7.3908954,
            "_source": {
                "STRIKE_PRICE": 305
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLd",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 165
            }
        },
        {
            "_index": "opt_pr",
            "_type": "opt_pr_r",
            "_id": "AV3K4QTgNHl15Mv30uLy",
            "_score": 7.381078,
            "_source": {
                "STRIKE_PRICE": 270
            }
        }
    ]
}

}

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.

How to get position of a certain element in strings vector, to use it as an index in ints vector?

If you want an index, you can use std::find in combination with std::distance.

auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
  // name not in vector
} else
{
  auto index = std::distance(Names.begin(), it);
}

Why do I get the "Unhandled exception type IOException"?

You should add "throws IOException" to your main method:

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

You can read a bit more about checked exceptions (which are specific to Java) in JLS.

How to detect IE11?

IE11 no longer reports as MSIE, according to this list of changes it's intentional to avoid mis-detection.

What you can do if you really want to know it's IE is to detect the Trident/ string in the user agent if navigator.appName returns Netscape, something like (the untested);

_x000D_
_x000D_
function getInternetExplorerVersion()_x000D_
{_x000D_
  var rv = -1;_x000D_
  if (navigator.appName == 'Microsoft Internet Explorer')_x000D_
  {_x000D_
    var ua = navigator.userAgent;_x000D_
    var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  }_x000D_
  else if (navigator.appName == 'Netscape')_x000D_
  {_x000D_
    var ua = navigator.userAgent;_x000D_
    var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  }_x000D_
  return rv;_x000D_
}_x000D_
_x000D_
console.log('IE version:', getInternetExplorerVersion());
_x000D_
_x000D_
_x000D_

Note that IE11 (afaik) still is in preview, and the user agent may change before release.

How to run .jar file by double click on Windows 7 64-bit?

I had the same problem with .jar files not opening on a double click. It turned out that I had two versions of Java installed (Java 6 and 7). Uninstalling Java 6 from Control Panel-> Uninstall a Program was what finally allowed .jar files to open on a double click without using the command window.

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Alt + Shift + ? (Left Arrow)

or

Ctrl + E (Recent Files pop-up).

Also check:

Ctrl + Shift + E (the Recently Edited Files pop-up).

Mac users, replace Ctrl with ? (command) and Alt with ? (option).

Update In v12.0 it's Alt + Shift +? (Left Arrow) instead of Alt + Ctrl + ? (Left Arrow).

Update 2 In v14.1 (and possibly earlier) it's Ctrl + [

Update 3 In IntelliJ IDEA 2016.3 it's Ctrl + Alt + ? (Left Arrow)

Update 4 In IntelliJ IDEA 2018.3 it's Alt + Shift + ? (Left Arrow)

Update 5 In IntelliJ IDEA 2019.3 it's Ctrl + Alt + ? (Left Arrow)

What is the right way to write my script 'src' url for a local development environment?

This is an old post but...

You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

Example directory structure:

/html/public/
- index.html
- script2.js
- js/
   - script.js

To load script.js from inside index.html:

<script type="text/javascript" src="./js/script.js">

This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

CSS Cell Margin

Try padding-right. You're not allowed to put margin's between cells.

<table>
   <tr>
      <td style="padding-right: 10px;">one</td>
      <td>two</td>
   </tr>
</table>

Jenkins Pipeline Wipe Out Workspace

In my case, I want to clear out old files at the beginning of the build, but this is problematic since the source code has been checked out.

My solution is to ask git to clean out any files (from the last build) that it doesn't know about:

    sh "git clean -x -f"

That way I can start the build out clean, and if it fails, the workspace isn't cleaned out and therefore easily debuggable.

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

How do I prevent a form from being resized by the user?

Set FormBorderStyle to 'FixedDialog'

FixedDialog

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

How to detect when a UIScrollView has finished scrolling

There is a method of UIScrollViewDelegate which can be used to detect (or better to say 'predict') when scrolling has really finished:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)

of UIScrollViewDelegate which can be used to detect (or better to say 'predict') when scrolling has really finished.

In my case I used it with horizontal scrolling as following (in Swift 3):

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    perform(#selector(self.actionOnFinishedScrolling), with: nil, afterDelay: Double(velocity.x))
}
func actionOnFinishedScrolling() {
    print("scrolling is finished")
    // do what you need
}

Remove unwanted parts from strings in a column

data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))

Python: How to increase/reduce the fontsize of x and y tick labels?

One shouldn't use set_yticklabels to change the fontsize, since this will also set the labels (i.e. it will replace any automatic formatter by a FixedFormatter), which is usually undesired. The easiest is to set the respective tick_params:

ax.tick_params(axis="x", labelsize=8)
ax.tick_params(axis="y", labelsize=20)

or

ax.tick_params(labelsize=8)

in case both axes shall have the same size.

Of course using the rcParams as in @tmdavison's answer is possible as well.

How to create Password Field in Model Django

I thinks it is vary helpful way.

models.py

from django.db import models
class User(models.Model):
    user_name = models.CharField(max_length=100)
    password = models.CharField(max_length=32)

forms.py

from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
    class Meta:
        model= User
        fields=[
           'user_name',
           'password'
            ]
       widgets = {
      'password': forms.PasswordInput()
         }

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

You just need to manually set the desired permissions with chmod():

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);

    // Set perms with chmod()
    chmod($file, 0777);
    return true;
}

ReferenceError: fetch is not defined

If you want to avoid npm install and not running in browser, you can also use nodejs https module;

const https = require('https')
const url = "https://jsonmock.hackerrank.com/api/movies";
https.get(url, res => {
  let data = '';
  res.on('data', chunk => {
    data += chunk;
  });
  res.on('end', () => {
    data = JSON.parse(data);
    console.log(data);
  })
}).on('error', err => {
  console.log(err.message);
})

How to uninstall Golang?

You might try

rm -rvf /usr/local/go/

then remove any mention of go in e.g. your ~/.bashrc; then you need at least to logout and login.

However, be careful when doing that. You might break your system badly if something is wrong.

PS. I am assuming a Linux or POSIX system.

Counting the number of files in a directory using Java

Unfortunately, I believe that is already the best way (although list() is slightly better than listFiles(), since it doesn't construct File objects).

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Android Text over image

Try the below code this will help you`

  <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="150dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:src="@drawable/gallery1"/>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#7ad7d7d7"
        android:gravity="center"
        android:text="Juneja Art Gallery"
        android:textColor="#000000"
        android:textSize="15sp"/>
</RelativeLayout>

Fill remaining vertical space - only CSS

You can use CSS Flexbox instead another display value, The Flexbox Layout (Flexible Box) module aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic.

Example

/* CONTAINER */
#wrapper
{
   width:300px;
   height:300px;
    display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox; /* TWEENER - IE 10 */
    display: -webkit-flex; /* NEW - Chrome */
    display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
    -ms-flex-direction: column;
    -moz-flex-direction: column;
    -webkit-flex-direction: column;
    flex-direction: column;
}

/* SOME ITEM CHILD ELEMENTS */
#first
{
   width:300px;
    height: 200px;
   background-color:#F5DEB3;

}

#second
{
   width:300px;
   background-color: #9ACD32;
    -webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1; /* OLD - Firefox 19- */
    -webkit-flex: 1; /* Chrome */
    -ms-flex: 1; /* IE 10 */
    flex: 1; /* NEW, */
}

jsfiddle Example

If you want to have full support for old browsers like IE9 or below, you will have to use a polyfills like flexy, this polyfill enable support for Flexbox model but only for 2012 spec of flexbox model.

Recently I found another polyfill to help you with Internet Explorer 8 & 9 or any older browser that not have support for flexbox model, I still have not tried it but I leave the link here

You can find a usefull and complete Guide to Flexbox model by Chris Coyer here

Exception in thread "main" java.util.NoSuchElementException

Everyone explained pretty well on it. Let me answer when should this class be used.

When Should You Use NoSuchElementException?

Java includes a few different ways to iterate through elements in a collection. The first of these classes, Enumeration, was introduced in JDK1.0 and is generally considered deprecated in favor of newer iteration classes, like Iterator and ListIterator.

As with most programming languages, the Iterator class includes a hasNext() method that returns a boolean indicating if the iteration has anymore elements. If hasNext() returns true, then the next() method will return the next element in the iteration. Unlike Enumeration, Iterator also has a remove() method, which removes the last element that was obtained via next().

While Iterator is generalized for use with all collections in the Java Collections Framework, ListIterator is more specialized and only works with List-based collections, like ArrayList, LinkedList, and so forth. However, ListIterator adds even more functionality by allowing iteration to traverse in both directions via hasPrevious() and previous() methods.

HTML Input="file" Accept Attribute File Type (CSV)

You can know the correct content-type for any file by just doing the following:

1) Select interested file,

2) And run in console this:

console.log($('.file-input')[0].files[0].type);

You can also set attribute "multiple" for your input to check content-type for several files at a time and do next:

for (var i = 0; i < $('.file-input')[0].files.length; i++){
    console.log($('.file-input')[0].files[i].type);
}

Attribute accept has some problems with multiple attribute and doesn't work correctly in this case.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

How to downgrade tensorflow, multiple versions possible?

Is it possible to have multiple version of tensorflow on the same OS?

Yes, you can use python virtual environments for this. From the docs:

A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.

After you have install virtualenv (see the docs), you can create a virtual environment for the tutorial and install the tensorflow version you need in it:

PATH_TO_PYTHON=/usr/bin/python3.5
virtualenv -p $PATH_TO_PYTHON my_tutorial_env 
source my_tutorial_env/bin/activate # this activates your new environment
pip install tensorflow==1.1

PATH_TO_PYTHON should point to where python is installed on your system. When you want to use the other version of tensorflow execute:

deactivate my_tutorial_env

Now you can work again with the tensorflow version that was already installed on your system.

No templates in Visual Studio 2017

I found the path and wrote it in the options enter image description here

How do I resolve `The following packages have unmet dependencies`

First of all try this

sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove

If error still persists then do this

sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f

Afterwards try this again:

sudo apt-get install npm

But if it still couldn't resolve issues check for the dependencies using sudo dpkg --configure -a and remove them one-by-one . Let's say dependencies are on npm then go for this ,

sudo apt-get remove nodejs
sudo apt-get remove npm

Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a

sudo apt-get update

Then check for the dependencies problem again using sudo dpkg --configure -a and if it's all clear then you are done . Later on install npm again using this

v=8   # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -

Then install the Node.js package.

sudo apt-get install -y nodejs

The answer above will work for general cases also(for dependencies on other packages like django ,etc) just after first two processes use the same process for the package you are facing dependency with.

Differences between Ant and Maven

Maven is a Framework, Ant is a Toolbox

Maven is a pre-built road car, whereas Ant is a set of car parts. With Ant you have to build your own car, but at least if you need to do any off-road driving you can build the right type of car.

To put it another way, Maven is a framework whereas Ant is a toolbox. If you're content with working within the bounds of the framework then Maven will do just fine. The problem for me was that I kept bumping into the bounds of the framework and it wouldn't let me out.

XML Verbosity

tobrien is a guy who knows a lot about Maven and I think he provided a very good, honest comparison of the two products. He compared a simple Maven pom.xml with a simple Ant build file and he made mention of how Maven projects can become more complex. I think that its worth taking a look at a comparison of a couple of files that you are more likely to see in a simple real-world project. The files below represent a single module in a multi-module build.

First, the Maven file:

<project 
    xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-4_0_0.xsd">

    <parent>
        <groupId>com.mycompany</groupId>
        <artifactId>app-parent</artifactId>
        <version>1.0</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>persist</artifactId>
    <name>Persistence Layer</name>

    <dependencies>

        <dependency>
            <groupId>com.mycompany</groupId>
            <artifactId>common</artifactId>
            <scope>compile</scope>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>com.mycompany</groupId>
            <artifactId>domain</artifactId>
            <scope>provided</scope>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>${hibernate.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>${commons-lang.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>${spring.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.dbunit</groupId>
            <artifactId>dbunit</artifactId>
            <version>2.2.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
            <classifier>jdk15</classifier>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${commons-dbcp.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc</artifactId>
            <version>${oracle-jdbc.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>${easymock.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

And the equivalent Ant file:

<project name="persist" >

    <import file="../build/common-build.xml" />


    <path id="compile.classpath.main">
        <pathelement location="${common.jar}" />
        <pathelement location="${domain.jar}" />
        <pathelement location="${hibernate.jar}" />
        <pathelement location="${commons-lang.jar}" />
        <pathelement location="${spring.jar}" />
    </path>


    <path id="compile.classpath.test">
        <pathelement location="${classes.dir.main}" />
        <pathelement location="${testng.jar}" />
        <pathelement location="${dbunit.jar}" />
        <pathelement location="${easymock.jar}" />
        <pathelement location="${commons-dbcp.jar}" />
        <pathelement location="${oracle-jdbc.jar}" />
        <path refid="compile.classpath.main" />
    </path>


    <path id="runtime.classpath.test">
        <pathelement location="${classes.dir.test}" />
        <path refid="compile.classpath.test" />
    </path>


</project>

tobrien used his example to show that Maven has built-in conventions but that doesn't necessarily mean that you end up writing less XML. I have found the opposite to be true. The pom.xml is 3 times longer than the build.xml and that is without straying from the conventions. In fact, my Maven example is shown without an extra 54 lines that were required to configure plugins. That pom.xml is for a simple project. The XML really starts to grow significantly when you start adding in extra requirements, which is not out of the ordinary for many projects.

But you have to tell Ant what to do

My Ant example above is not complete of course. We still have to define the targets used to clean, compile, test etc. These are defined in a common build file that is imported by all modules in the multi-module project. Which leads me to the point about how all this stuff has to be explicitly written in Ant whereas it is declarative in Maven.

Its true, it would save me time if I didn't have to explicitly write these Ant targets. But how much time? The common build file I use now is one that I wrote 5 years ago with only slight refinements since then. After my 2 year experiment with Maven, I pulled the old Ant build file out of the closet, dusted it off and put it back to work. For me, the cost of having to explicitly tell Ant what to do has added up to less than a week over a period of 5 years.

Complexity

The next major difference I'd like to mention is that of complexity and the real-world effect it has. Maven was built with the intention of reducing the workload of developers tasked with creating and managing build processes. In order to do this it has to be complex. Unfortunately that complexity tends to negate their intended goal.

When compared with Ant, the build guy on a Maven project will spend more time:

  • Reading documentation: There is much more documentation on Maven, because there is so much more you need to learn.
  • Educating team members: They find it easier to ask someone who knows rather than trying to find answers themselves.
  • Troubleshooting the build: Maven is less reliable than Ant, especially the non-core plugins. Also, Maven builds are not repeatable. If you depend on a SNAPSHOT version of a plugin, which is very likely, your build can break without you having changed anything.
  • Writing Maven plugins: Plugins are usually written with a specific task in mind, e.g. create a webstart bundle, which makes it more difficult to reuse them for other tasks or to combine them to achieve a goal. So you may have to write one of your own to workaround gaps in the existing plugin set.

In contrast:

  • Ant documentation is concise, comprehensive and all in one place.
  • Ant is simple. A new developer trying to learn Ant only needs to understand a few simple concepts (targets, tasks, dependencies, properties) in order to be able to figure out the rest of what they need to know.
  • Ant is reliable. There haven't been very many releases of Ant over the last few years because it already works.
  • Ant builds are repeatable because they are generally created without any external dependencies, such as online repositories, experimental third-party plugins etc.
  • Ant is comprehensive. Because it is a toolbox, you can combine the tools to perform almost any task you want. If you ever need to write your own custom task, it's very simple to do.

Familiarity

Another difference is that of familiarity. New developers always require time to get up to speed. Familiarity with existing products helps in that regard and Maven supporters rightly claim that this is a benefit of Maven. Of course, the flexibility of Ant means that you can create whatever conventions you like. So the convention I use is to put my source files in a directory name src/main/java. My compiled classes go into a directory named target/classes. Sounds familiar doesn't it.

I like the directory structure used by Maven. I think it makes sense. Also their build lifecycle. So I use the same conventions in my Ant builds. Not just because it makes sense but because it will be familiar to anyone who has used Maven before.

NVIDIA NVML Driver/library version mismatch

These answers not worked for me:

https://stackoverflow.com/a/43023000/1179925

https://stackoverflow.com/a/45319156/1179925

https://stackoverflow.com/a/54349675/1179925

dmesg

NVRM: API mismatch: the client has the version 418.67, but
NVRM: this kernel module has the version 430.26.  Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.

Uninstall old driver 418.67 and install new driver 430.26 (download NVIDIA-Linux-x86_64-430.26.run):

sudo apt-get --purge remove "*nvidia*"
sudo /usr/bin/nvidia-uninstall
chmod +x NVIDIA-Linux-x86_64-430.26.run
sudo ./NVIDIA-Linux-x86_64-430.26.run
[ignore abort]

cat /proc/driver/nvidia/version

NVRM version: NVIDIA UNIX x86_64 Kernel Module  430.26  Tue Jun  4 17:40:52 CDT 2019
GCC version:  gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)

Check that an email address is valid on iOS

Heres a good one with NSRegularExpression that's working for me.

[text rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;

You can insert whatever regex you want but I like being able to do it in one line.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

I found a working win7 binary here: Unofficial Windows Binaries for Python Extension Packages It's from Christoph Gohlke at UC Irvine. There are binaries for python 2.5, 2.6, 2.7 , 3.1 and 3.2 for both 32bit and 64 bit windows.

There are a whole lot of other compiled packages here, too.

Be sure to uninstall your old PILfirst. If you used easy_install: easy_install -mnX pil
And then remove the egg in python/Lib/site-packages

Be sure to remove any other failed attempts. I had moved the _image dll into Python*.*/DLLs and I had to remove it.

Get unicode value of a character

First, I get the high side of the char. After, get the low side. Convert all of things in HexString and put the prefix.

int hs = (int) c  >> 8;
int ls = hs & 0x000F;

String highSide = Integer.toHexString(hs);
String lowSide = Integer.toHexString(ls);
lowSide = Integer.toHexString(hs & 0x00F0);
String hexa = Integer.toHexString( (int) c );

System.out.println(c+" = "+"\\u"+highSide+lowSide+hexa);

Highlight a word with jQuery

function hiliter(word, element) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span class="myClass">' + word + '</span>';
    element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
hiliter('dolor');

Set focus on TextBox in WPF from view model

After implementing the accepted answer I did run across an issue that when navigating views with Prism the TextBox would still not get focus. A minor change to the PropertyChanged handler resolved it

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uie = (UIElement)d;
        if ((bool)e.NewValue)
        {
            uie.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
            {
                uie.Focus();
            }));
        }
    }

3D Plotting from X, Y, Z Data, Excel or other Tools

You can use r libraries for 3 D plotting.

Steps are:

First create a data frame using data.frame() command.

Create a 3D plot by using scatterplot3D library.

Or You can also rotate your chart using rgl library by plot3d() command.

Alternately you can use plot3d() command from rcmdr library.

In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.

[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]

How to horizontally center an unordered list of unknown width?

Try wrapping the list in a div and give that div the inline property instead of your list.

How to align LinearLayout at the center of its parent?

this worked for me.

<LinearLayout>
.
.
.
android:gravity="center"
.
.>

<TextView
android:layout_gravity = "center"
/>
<Button
android:layout_gravity="center"
/>

</LinearLayout>

so you're designing the Linear Layout to place all its contents(TextView and Button) in its center and then the TextView and Button are placed relative to the center of the Linear Layout

How can I run multiple npm scripts in parallel?

My solution is similar to Piittis', though I had some problems using Windows. So I had to validate for win32.

const { spawn } = require("child_process");

function logData(data) {
    console.info(`stdout: ${data}`);
}

function runProcess(target) {
    let command = "npm";
    if (process.platform === "win32") {
        command = "npm.cmd"; // I shit you not
    }
    const myProcess = spawn(command, ["run", target]); // npm run server

    myProcess.stdout.on("data", logData);
    myProcess.stderr.on("data", logData);
}

(() => {
    runProcess("server"); // package json script
    runProcess("client");
})();

Create a tar.xz in one command

Try this: tar -cf file.tar file-to-compress ; xz -z file.tar

Note:

  1. tar.gz and tar.xz are not the same; xz provides better compression.
  2. Don't use pipe | because this runs commands simultaneously. Using ; or & executes commands one after another.

Split a string by another string in C#

There is an overload of Split that takes strings.

"THExxQUICKxxBROWNxxFOX".Split(new [] { "xx" }, StringSplitOptions.None);

You can use either of these StringSplitOptions

  • None - The return value includes array elements that contain an empty string
  • RemoveEmptyEntries - The return value does not include array elements that contain an empty string

So if the string is "THExxQUICKxxxxBROWNxxFOX", StringSplitOptions.None will return an empty entry in the array for the "xxxx" part while StringSplitOptions.RemoveEmptyEntries will not.

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

startsWith() and endsWith() functions in PHP

You can use substr_compare function to check start-with and ends-with:

function startsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function endsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}

This should be one of the fastest solutions on PHP 7 (benchmark script). Tested against 8KB haystacks, various length needles and full, partial and no match cases. strncmp is a touch faster for starts-with but it cannot check ends-with.

Transport security has blocked a cleartext HTTP

This was tested and was working on iOS 9 GM seed - this is the configuration to allow a specific domain to use HTTP instead of HTTPS:

<key>NSAppTransportSecurity</key>
<dict>
      <key>NSAllowsArbitraryLoads</key> 
      <false/>
       <key>NSExceptionDomains</key>
       <dict>
            <key>example.com</key> <!--Include your domain at this line -->
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
            </dict>
       </dict>
</dict>

NSAllowsArbitraryLoads must be false, because it disallows all insecure connection, but the exceptions list allows connection to some domains without HTTPS.

How to select only the first rows for each unique value of a column?

In SQL 2k5+, you can do something like:

;with cte as (
  select CName, AddressLine,
  rank() over (partition by CName order by AddressLine) as [r]
  from MyTable
)
select CName, AddressLine
from cte
where [r] = 1

Show an image preview before upload

For background images, make sure to use url()

node.backgroundImage = 'url(' + e.target.result + ')';

Java: Casting Object to Array type

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0];

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.

Best way to determine user's locale within browser

You said your website has Flash, then, as another option, you can get operation system's language with flash.system.Capabilities.language— see How to determine OS language within browser to guess an operation system locale.

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

How to turn off caching on Firefox?

Firefox 48 Developer Tools

Allows you to turn off cache only when toolbox is open, which is perfect for web development:

  • F12
  • gearbox on right upper corner
  • scroll down top Advanced settings
  • check "Disable Cache (when toolbox is open)"

enter image description here

https://stackoverflow.com/a/27397425/895245 has similar content, but positioning changed a bit since.

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

Outline effect to text

I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn't involve extra mark-up, js and works in IE7-9 (I haven't tested 6), and doesn't cause aliasing problems.

This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE. CSS3 text-stroke support is poor at the moment.

IE Filters

The glow filter (http://www.impressivewebs.com/css3-text-shadow-ie/) looks terrible, so I didn't use that.

David Hewitt's answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.

I then combined some of the elements suggested on useragentman with the dropshadow filters.

Putting it together

This example would be black text with a white stroke. I'm using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).

#myelement {
    color: #000000;
    text-shadow:
    -1px -1px 0 #ffffff,  
    1px -1px 0 #ffffff,
    -1px 1px 0 #ffffff,
    1px 1px 0 #ffffff;
}

html.ie7 #myelement,
html.ie8 #myelement,
html.ie9 #myelement {
    background-color: white;
    filter: progid:DXImageTransform.Microsoft.Chroma(color='white') progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=-1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=-1);
    zoom: 1;
}

MongoDb shuts down with Code 100

first you have to create data directory where MongoDB stores data. MongoDB’s default data directory path is the absolute path \data\db on the drive from which you start MongoDB.

if you have install in C:/ drive then you have to create data\db directory. for doing this run command in cmd

C:\>mkdir data\db

To start MongoDB, run mongod.exe.

"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"

The --dbpath option points to your database directory. enter image description here

Connect to MongoDB.

"C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"

to check all work good :

show dbs

enter image description here

How to change text color and console color in code::blocks?

This is a function online, I created a header file with it, and I use Setcolor(); instead, I hope this helped! You can change the color by choosing any color in the range of 0-256. :) Sadly, I believe CodeBlocks has a later build of the window.h library...

#include <windows.h>            //This is the header file for windows.
#include <stdio.h>              //C standard library header file

void SetColor(int ForgC);

int main()
{
    printf("Test color");       //Here the text color is white
    SetColor(30);               //Function call to change the text color
    printf("Test color");       //Now the text color is green
    return 0;
}

void SetColor(int ForgC)
{
     WORD wColor;
     //This handle is needed to get the current background attribute

     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     //csbi is used for wAttributes word

     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
          //To mask out all but the background attribute, and to add the color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
}

Don't understand why UnboundLocalError occurs (closure)

The reason of why your code throws an UnboundLocalError is already well explained in other answers.

But it seems to me that you're trying to build something that works like itertools.count().

So why don't you try it out, and see if it suits your case:

>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)

Is there a Python Library that contains a list of all the ascii characters?

ASCII defines 128 characters whose byte values range from 0 to 127 inclusive. So to get a string of all the ASCII characters, you could just do

''.join([chr(i) for i in range(128)])

Only some of those are printable, however- the printable ASCII characters can be accessed in Python via

import string
string.printable

How to convert POJO to JSON and vice versa?

We can also make use of below given dependency and plugin in your pom file - I make use of maven. With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src) or vice-versa. Look at the code below:

Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());

Gson gson2 = new Gson();
Error expectederr = gson2.fromJson(payloadStr, Error.class);

And the Maven settings:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.7.1</version>
</dependency>

<plugin>
    <groupId>com.googlecode.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>0.3.7</version>
    <configuration>
        <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
        <targetPackage>com.example.types</targetPackage>
    </configuration>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Identify if a string is a number

I know this is an old thread, but none of the answers really did it for me - either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here's my string extension method:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

Simple to use:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

Or, if you want to test other types of number, you can specify the 'style'. So, to convert a number with an Exponent, you could use:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

Or to test a potential Hex string, you could use:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

The optional 'culture' parameter can be used in much the same way.

It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you'll probably need additional specialised number handling functions anyway.

What is event bubbling and capturing?

There's also the Event.eventPhase property which can tell you if the event is at target or comes from somewhere else, and it is fully supported by browsers.

Expanding on the already great snippet from the accepted answer, this is the output using the eventPhase property

_x000D_
_x000D_
var logElement = document.getElementById('log');

function log(msg) {
  if (logElement.innerHTML == "<p>No logs</p>")
    logElement.innerHTML = "";
  logElement.innerHTML += ('<p>' + msg + '</p>');
}

function humanizeEvent(eventPhase){
  switch(eventPhase){
    case 1: //Event.CAPTURING_PHASE
      return "Event is being propagated through the target's ancestor objects";
    case 2: //Event.AT_TARGET
      return "The event has arrived at the event's target";
    case 3: //Event.BUBBLING_PHASE
      return "The event is propagating back up through the target's ancestors in reverse order";
  }
}
function capture(e) {
  log('capture: ' + this.firstChild.nodeValue.trim() + "; " + 
  humanizeEvent(e.eventPhase));
}

function bubble(e) {
  log('bubble: ' + this.firstChild.nodeValue.trim() + "; " + 
  humanizeEvent(e.eventPhase));
}

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', capture, true);
  divs[i].addEventListener('click', bubble, false);
}
_x000D_
p {
  line-height: 0;
}

div {
  display:inline-block;
  padding: 5px;

  background: #fff;
  border: 1px solid #aaa;
  cursor: pointer;
}

div:hover {
  border: 1px solid #faa;
  background: #fdd;
}
_x000D_
<div>1
  <div>2
    <div>3
      <div>4
        <div>5</div>
      </div>
    </div>
  </div>
</div>
<button onclick="document.getElementById('log').innerHTML = '<p>No logs</p>';">Clear logs</button>
<section id="log"></section>
_x000D_
_x000D_
_x000D_

How do the post increment (i++) and pre increment (++i) operators work in Java?

I believe you are executing all these statements differently
executing together will result => 38 ,29

int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated, 
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)

Correlation between two vectors?

For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.

Select rows which are not present in other table

A.) The command is NOT EXISTS, you're missing the 'S'.

B.) Use NOT IN instead

SELECT ip 
  FROM login_log 
  WHERE ip NOT IN (
    SELECT ip
    FROM ip_location
  )
;

Open JQuery Datepicker by clicking on an image w/ no input field

HTML:

<div class="CalendarBlock">
    <input type="hidden">
</div>

CODE:

$CalendarBlock=$('.CalendarBlock');
$CalendarBlock.click(function(){
    var $datepicker=$(this).find('input');
    datepicker.datepicker({dateFormat: 'mm/dd/yy'});
    $datepicker.focus(); });

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

Simply remove the Microsoft SQL Server Management Studio Express 2005 from control panel

WordPress - Check if user is logged in

Example: Display different output depending on whether the user is logged in or not.

<?php

if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
} else {
    echo 'Welcome, visitor!';
}

?>

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

I too struggled with something similar. My guess is your actual problem is connecting to a SQL Express instance running on a different machine. The steps to do this can be summarized as follows:

  1. Ensure SQL Express is configured for SQL Authentication as well as Windows Authentication (the default). You do this via SQL Server Management Studio (SSMS) Server Properties/Security
  2. In SSMS create a new login called "sqlUser", say, with a suitable password, "sql", say. Ensure this new login is set for SQL Authentication, not Windows Authentication. SSMS Server Security/Logins/Properties/General. Also ensure "Enforce password policy" is unchecked
  3. Under Properties/Server Roles ensure this new user has the "sysadmin" role
  4. In SQL Server Configuration Manager SSCM (search for SQLServerManagerxx.msc file in Windows\SysWOW64 if you can't find SSCM) under SQL Server Network Configuration/Protocols for SQLExpress make sure TCP/IP is enabled. You can disable Named Pipes if you want
  5. Right-click protocol TCP/IP and on the IPAddresses tab, ensure every one of the IP addresses is set to Enabled Yes, and TCP Port 1433 (this is the default port for SQL Server)
  6. In Windows Firewall (WF.msc) create two new Inbound Rules - one for SQL Server and another for SQL Browser Service. For SQL Server you need to open TCP Port 1433 (if you are using the default port for SQL Server) and very importantly for the SQL Browser Service you need to open UDP Port 1434. Name these two rules suitably in your firewall
  7. Stop and restart the SQL Server Service using either SSCM or the Services.msc snap-in
  8. In the Services.msc snap-in make sure SQL Browser Service Startup Type is Automatic and then start this service

At this point you should be able to connect remotely, using SQL Authentication, user "sqlUser" password "sql" to the SQL Express instance configured as above. A final tip and easy way to check this out is to create an empty text file with the .UDL extension, say "Test.UDL" on your desktop. Double-clicking to edit this file invokes the Microsoft Data Link Properties dialog with which you can quickly test your remote SQL connection

Get the last inserted row ID (with SQL statement)

Assuming a simple table:

CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);

We can capture IDENTITY values in a table variable for further consumption.

DECLARE @IDs TABLE(ID INT);

-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name) 
  OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';

SELECT ID FROM @IDs;

The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

How can I tell which button was clicked in a PHP form submit?

With an HTML form like:

<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />

The PHP code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Something posted

    if (isset($_POST['btnDelete'])) {
        // btnDelete
    } else {
        // Assume btnSubmit
    }
}

You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:

  1. The user literally clicks the submit button with the mouse or pointing device
  2. Or there is focus on the submit button (they tabbed to it), and then the Enter key is pressed.

Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.

Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.

I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Your service must answer an OPTIONS request with headers like these:

Access-Control-Allow-Origin: [the same origin from the request]
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: [the same ACCESS-CONTROL-REQUEST-HEADERS from request]

Here is a good doc: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

How to install maven on redhat linux

Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file

Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:

wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz

And then proceed to install it.

UPDATE: Adding complete instructions (copied from the comment below)

  1. Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  2. run the following to extract the tar:

    tar xvf apache-maven-3.2.1-bin.tar.gz
    
  3. Next add the env varibles such as

    export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1

    export M2=$M2_HOME/bin

    export PATH=$M2:$PATH

  4. Verify

    mvn -version
    

Unknown column in 'field list' error on MySQL Update query

Just sharing my experience on this. I was having this same issue. The insert or update statement is correct. And I also checked the encoding. The column does exist. Then! I found out that I was referencing the column in my Trigger. You should also check your trigger see if any script is referencing the column you are having the problem with.

Why use static_cast<int>(x) instead of (int)x?

One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.

how to force maven to update local repo

Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.

Press CTRL+Shift+A to open up the Actions menu. Type Maven and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line

Create instance of generic type in Java?

You can use:

Class.forName(String).getConstructor(arguments types).newInstance(arguments)

But you need to supply the exact class name, including packages, eg. java.io.FileInputStream. I used this to create a math expressions parser.

wait until all threads finish their work in java

Another possibility is the CountDownLatch object, which is useful for simple situations : since you know in advance the number of threads, you initialize it with the relevant count, and pass the reference of the object to each thread.
Upon completion of its task, each thread calls CountDownLatch.countDown() which decrements the internal counter. The main thread, after starting all others, should do the CountDownLatch.await() blocking call. It will be released as soon as the internal counter has reached 0.

Pay attention that with this object, an InterruptedException can be thrown as well.

How to use string.substr() function?

Another interesting variant question can be:

How would you make "12345" as "12 23 34 45" without using another string?

Will following do?

    for(int i=0; i < a.size()-1; ++i)
    {
        //b = a.substr(i, 2);
        c = atoi((a.substr(i, 2)).c_str());
        cout << c << " ";
    }

How can you get the build/version number of your Android application?

No, you don't need to do anything with AndroidManifest.xml

Basically, your app's version name and version code is inside the app level Gradle file, under defaultConfig tag:

defaultConfig {
   versionCode 1
   versionName "1.0"
}

Note: When you wish to upload an app to the playstore, it can give any name as the version name, but the version code have to be different than the current version code if this app is already in the play store.

Simply use the following code snippet to get the version code & version name from anywhere in your app:

try {
    PackageInfo pInfo =   context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
    int verCode = pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

What's wrong with using == to compare floats in Java?

As mentioned in other answers, doubles can have small deviations. And you could write your own method to compare them using an "acceptable" deviation. However ...

There is an apache class for comparing doubles: org.apache.commons.math3.util.Precision

It contains some interesting constants: SAFE_MIN and EPSILON, which are the maximum possible deviations of simple arithmetic operations.

It also provides the necessary methods to compare, equal or round doubles. (using ulps or absolute deviation)

history.replaceState() example?

Suppose https://www.mozilla.org/foo.html executes the following JavaScript:

const stateObj = { foo: 'bar' };

history.pushState(stateObj, '', 'bar.html');

This will cause the URL bar to display https://www.mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.

show and hide divs based on radio button click

With $("div.desc").hide(); you are essentially trying to hide a div with a class name of desc. Which doesn't exist. With $("#"+test).show(); you are trying to show either a div with an id of #2 or #3. Those are illegal id's in HTML (can't start with a number), though they will work in many browsers. However, they don't exist.

I'd rename the two divs to carDiv2 and carDiv3 and then use different logic to hide or show.

if((test) == 2) { ... }

Also, use a class for your checkboxes so your binding becomes something like

$('.carCheckboxes').click(function ...

Get elements by attribute when querySelectorAll is not available without using libraries?

Don't use in Browser

In the browser, use document.querySelect('[attribute-name]').

But if you're unit testing and your mocked dom has a flakey querySelector implementation, this will do the trick.

This is @kevinfahy's answer, just trimmed down to be a bit with ES6 fat arrow functions and by converting the HtmlCollection into an array at the cost of readability perhaps.

So it'll only work with an ES6 transpiler. Also, I'm not sure how performant it'll be with a lot of elements.

function getElementsWithAttribute(attribute) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) !== null);
}

And here's a variant that will get an attribute with a specific value

function getElementsWithAttributeValue(attribute, value) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) === value);
}

How to call a JavaScript function, declared in <head>, in the body when I want to call it

I'm not sure what you mean by "myself".

Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.

e.g. On page load:

<body onload="myfunction();">

Or on mouseover:

<table onmouseover="myfunction();">

As a result the first question is, "What do you want to do to cause the function to execute?"

After you determine that it will be much easier to give you a direct answer.

How do I encrypt and decrypt a string in python?

Although its very old, but I thought of sharing another idea to do this:

from Crypto.Cipher import AES    
from Crypto.Hash import SHA256

password = ("anything")    
hash_obj = SHA256.new(password.encode('utf-8'))    
hkey = hash_obj.digest()

def encrypt(info):
    msg = info
    BLOCK_SIZE = 16
    PAD = "{"
    padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD
    cipher = AES.new(hkey, AES.MODE_ECB)
    result = cipher.encrypt(padding(msg).encode('utf-8'))
    return result  

msg = "Hello stackoverflow!"
cipher_text = encrypt(msg)
print(cipher_text)

def decrypt(info):
    msg = info
    PAD = "{"
    decipher = AES.new(hkey, AES.MODE_ECB)
    pt = decipher.decrypt(msg).decode('utf-8')
    pad_index = pt.find(PAD)
    result = pt[: pad_index]
    return result

plaintext = decrypt(cipher_text)
print(plaintext)

Outputs:

> b'\xcb\x0b\x8c\xdc#\n\xdd\x80\xa6|\xacu\x1dEg;\x8e\xa2\xaf\x80\xea\x95\x80\x02\x13\x1aem\xcb\xf40\xdb'

> Hello stackoverflow!

Shell script to set environment variables

I cannot solve it with source ./myscript.sh. It says the source not found error.
Failed also when using . ./myscript.sh. It gives can't open myscript.sh.

So my option is put it in a text file to be called in the next script.

#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

Tnen call it whenever is needed:

while read -r line; do
    line=$(sed -e 's/[[:space:]]*$//' <<<${line})
    var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
    if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt

Foreign key referring to primary keys across multiple tables?

Actually I do this myself. I have a table called 'Comments' which contains comments for records in 3 other tables. Neither solution actually handles everything you probably want it to. In your case, you would do this:

Solution 1:

  1. Add a tinyint field to employees_ce and employees_sn that has a default value which is different in each table (This field represents a 'table identifier', so we'll call them tid_ce & tid_sn)

  2. Create a Unique Index on each table using the table's PK and the table id field.

  3. Add a tinyint field to your 'Deductions' table to store the second half of the foreign key (the Table ID)

  4. Create 2 foreign keys in your 'Deductions' table (You can't enforce referential integrity, because either one key will be valid or the other...but never both:

    ALTER TABLE [dbo].[Deductions]  WITH NOCHECK ADD  CONSTRAINT [FK_Deductions_employees_ce] FOREIGN KEY([id], [fk_tid])
    REFERENCES [dbo].[employees_ce] ([empid], [tid])
    NOT FOR REPLICATION 
    GO
    ALTER TABLE [dbo].[Deductions] NOCHECK CONSTRAINT [FK_600_WorkComments_employees_ce]
    GO
    ALTER TABLE [dbo].[Deductions]  WITH NOCHECK ADD  CONSTRAINT [FK_Deductions_employees_sn] FOREIGN KEY([id], [fk_tid])
    REFERENCES [dbo].[employees_sn] ([empid], [tid])
    NOT FOR REPLICATION 
    GO
    ALTER TABLE [dbo].[Deductions] NOCHECK CONSTRAINT [FK_600_WorkComments_employees_sn]
    GO
    
    employees_ce
    --------------
    empid    name     tid
    khce1   prince    1
    
    employees_sn
    ----------------
    empid    name     tid 
    khsn1   princess  2
    
    deductions
    ----------------------
    id      tid       name  
    khce1   1         gold
    khsn1   2         silver         
    ** id + tid creates a unique index **
    

Solution 2: This solution allows referential integrity to be maintained: 1. Create a second foreign key field in 'Deductions' table , allow Null values in both foreign keys, and create normal foreign keys:

    employees_ce
    --------------
    empid   name
    khce1   prince 

    employees_sn
    ----------------
    empid   name     
    khsn1   princess 

    deductions
    ----------------------
    idce    idsn      name  
    khce1   *NULL*    gold
    *NULL*  khsn1     silver         

Integrity is only checked if the column is not null, so you can maintain referential integrity.

Create dataframe from a matrix

If you change your time column into row names, then you can use as.data.frame(as.table(mat)) for simple cases like this.

Example:

data <- c(0.1, 0.2, 0.3, 0.3, 0.4, 0.5)
dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
as.data.frame(as.table(mat))
  time name Freq
1    0  C_0  0.1
2  0.5  C_0  0.2
3    1  C_0  0.3
4    0  C_1  0.3
5  0.5  C_1  0.4
6    1  C_1  0.5

In this case time and name are both factors. You may want to convert time back to numeric, or it may not matter.

Extending an Object in Javascript

You want to 'inherit' from Person's prototype object:

var Person = function (name) {
    this.name = name;
    this.type = 'human';
};

Person.prototype.info = function () {
    console.log("Name:", this.name, "Type:", this.type);
};

var Robot = function (name) {
    Person.apply(this, arguments);
    this.type = 'robot';
};

Robot.prototype = Person.prototype;  // Set prototype to Person's
Robot.prototype.constructor = Robot; // Set constructor back to Robot

person = new Person("Bob");
robot = new Robot("Boutros");

person.info();
// Name: Bob Type: human

robot.info();
// Name: Boutros Type: robot

Find Active Tab using jQuery and Twitter Bootstrap

Here is the answer for those of you who need a Boostrap 3 solution.

In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line

// tab
$('#rowTab a:first').tab('show');

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
 console.log ( $(e.target).attr('id') );
});

What's the difference between a null pointer and a void pointer?

A null pointer is guaranteed to not compare equal to a pointer to any object. It's actual value is system dependent and may vary depending on the type. To get a null int pointer you would do

int* p = 0;

A null pointer will be returned by malloc on failure.

We can test if a pointer is null, i.e. if malloc or some other function failed simply by testing its boolean value:

if (p) {
    /* Pointer is not null */
} else {
    /* Pointer is null */
}

A void pointer can point to any type and it is up to you to handle how much memory the referenced objects consume for the purpose of dereferencing and pointer arithmetic.

MongoDB query with an 'or' condition

In case anyone finds it useful, www.querymongo.com does translation between SQL and MongoDB, including OR clauses. It can be really helpful for figuring out syntax when you know the SQL equivalent.

In the case of OR statements, it looks like this

SQL:

SELECT * FROM collection WHERE columnA = 3 OR columnB = 'string';

MongoDB:

db.collection.find({
    "$or": [{
        "columnA": 3
    }, {
        "columnB": "string"
    }]
});

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

The issue is in the deserialization of the bean Customer. Your programs knows how to do it in XML, with JAXB as Daniel is writing, but most likely doesn't know how to do it in JSON.

Here you have an example with Resteasy/Jackson http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/

The same with Jersey: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

Way to insert text having ' (apostrophe) into a SQL table

try this

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

React Native Error: ENOSPC: System limit for number of file watchers reached

As already pointed out by @snishalaka, you can increase the number of inotify watchers.

However, I think the default number is high enough and is only reached when processes are not cleaned up properly. Hence, I simply restarted my computer as proposed on a related github issue and the error message was gone.

Pip - Fatal error in launcher: Unable to create process using '"'

run this python code:

import pip
pip.main(['install','flask']) # replace flask with the name of module you want to install

If you need to install multiple modules from a requirements.txt file,

import pip
fo = open("C:/...../requirements.txt", "r")
inp = fo.read()
ls =inp.split()     

for i in ls:
    pip.main(['install',i])

Is there an Eclipse plugin to run system shell in the Console?

I recommend EasyShell, which features 'open' (console), 'run', 'explore', and 'copy path'.

How to sort a List<Object> alphabetically using Object name field

public class ObjectComparator implements Comparator<Object> {

    public int compare(Object obj1, Object obj2) {
        return obj1.getName().compareTo(obj2.getName());
    }

}

Please replace Object with your class which contains name field

Usage:

ObjectComparator comparator = new ObjectComparator();
Collections.sort(list, comparator);

Angular2 Material Dialog css, dialog size

dialog-component.css

This code works perfectly for me, other solutions don't work. Use the ::ng-deep shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The ::ng-deep combinator works to any depth of nested components, and it applies to both the view children and content children of the component.

 ::ng-deep .mat-dialog-container {
    height: 400px !important;
    width: 400px !important;
}

Java Date vs Calendar

I always advocate Joda-time. Here's why.

  1. the API is consistent and intuitive. Unlike the java.util.Date/Calendar APIs
  2. it doesn't suffer from threading issues, unlike java.text.SimpleDateFormat etc. (I've seen numerous client issues relating to not realising that the standard date/time formatting is not thread-safe)
  3. it's the basis of the new Java date/time APIs (JSR310, scheduled for Java 8. So you'll be using APIs that will become core Java APIs.

EDIT: The Java date/time classes introduced with Java 8 are now the preferred solution, if you can migrate to Java 8

MongoDB Aggregation: How to get total records count?

Use the $count aggregation pipeline stage to get the total document count:

Query :

db.collection.aggregate(
  [
    {
      $match: {
        ...
      }
    },
    {
      $group: {
        ...
      }
    },
    {
      $count: "totalCount"
    }
  ]
)

Result:

{
   "totalCount" : Number of records (some integer value)
}

How do I convert csv file to rdd

I'd recommend reading the header directly from the driver, not through Spark. Two reasons for this: 1) It's a single line. There's no advantage to a distributed approach. 2) We need this line in the driver, not the worker nodes.

It goes something like this:

// Ridiculous amount of code to read one line.
val uri = new java.net.URI(filename)
val conf = sc.hadoopConfiguration
val fs = hadoop.fs.FileSystem.get(uri, conf)
val path = new hadoop.fs.Path(filename)
val stream = fs.open(path)
val source = scala.io.Source.fromInputStream(stream)
val header = source.getLines.head

Now when you make the RDD you can discard the header.

val csvRDD = sc.textFile(filename).filter(_ != header)

Then we can make an RDD from one column, for example:

val idx = header.split(",").indexOf(columnName)
val columnRDD = csvRDD.map(_.split(",")(idx))

What are the most common naming conventions in C?

I'm confused by one thing: You're planning to create a new naming convention for a new project. Generally you should have a naming convention that is company- or team-wide. If you already have projects that have any form of naming convention, you should not change the convention for a new project. If the convention above is just codification of your existing practices, then you are golden. The more it differs from existing de facto standards the harder it will be to gain mindshare in the new standard.

About the only suggestion I would add is I've taken a liking to _t at the end of types in the style of uint32_t and size_t. It's very C-ish to me although some might complain it's just "reverse" Hungarian.

Change bootstrap datepicker date format on select

If by ID:

$('#datepicker').datepicker({
    format: 'dd/mm/yyyy'

});

If by Class:

$('.datepicker').datepicker({
    format: 'dd/mm/yyyy'

});

Display SQL query results in php

You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.

For getting the result you have to add a lil things in your script like

require_once('db.php');  
 $sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) ORDER BY idM1O LIMIT 1";

 $result = mysql_query($sql);
 //echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    print_r($row);
}

This will give you result;

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Write to file, but overwrite it if it exists

Despite NylonSmile's answer, which is "sort of" correct.. I was unable to overwrite files, in this manner..

echo "i know about Pipes, girlfriend" > thatAnswer

zsh: file exists: thatAnswer

to solve my issues.. I had to use... >!, á la..

[[ $FORCE_IT == 'YES' ]] && echo "$@" >! "$X" || echo "$@" > "$X"

Obviously, be careful with this...

Automatic exit from Bash shell script on error

Use it in conjunction with pipefail.

set -e
set -o pipefail

-e (errexit): Abort the script at the first error, when a command exits with non-zero status (except in until or while loops, if-tests, and list constructs)

-o pipefail: Causes a pipeline to return the exit status of the last command in the pipe that returned a non-zero return value.

Chapter 33. Options

An existing connection was forcibly closed by the remote host

Had the same bug. Actually worked in case the traffic was sent using some proxy (fiddler in my case). Updated .NET framework from 4.5.2 to >=4.6 and now everything works fine. The actual request was:
new WebClient().DownloadData("URL");
The exception was:

SocketException: An existing connection was forcibly closed by the remote host

Convert string to Color in C#

 Color red = Color.FromName("Red");   

The MSDN doesn't say one way or another, so there's a good chance that it is case-sensitive. (UPDATE: Apparently, it is not.)

As far as I can tell, ColorTranslator.FromHtml is also.

If Color.FromName cannot find a match, it returns new Color(0,0,0);

If ColorTranslator.FromHtml cannot find a match, it throws an exception.

UPDATE:

Since you're using Microsoft.Xna.Framework.Graphics.Color, this gets a bit tricky:

using XColor = Microsoft.Xna.Framework.Graphics.Color;
using CColor = System.Drawing.Color;

 CColor clrColor = CColor.FromName("Red"); 
 XColor xColor = new XColor(clrColor.R, clrColor.G, clrColor.B, clrColor.A);

Error during installing HAXM, VT-X not working

I had exactly the same problem. And this is how I could fix it.

Step 1: Turn virtualization on in BIOS settings.

Step 2: Control Panel -> "Programs" -> "Turn Windows features on or off" (under "Programs and Features") and locate "Hyper-V", uncheck, reboot.

Step 3: In Avast->Settings->Troubleshooting. Uncheck "Enable hardware-assisted virtualization" & "Enable avast self-defense module"

Final step and the main:
Go to MyPC / right click / Advanced System Settings / Advanced / In Performance click SETTINGS / Data Execution Prevention and enable DEP for all programs and services.

The last step helped me to solve this problem. Hope you too.

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need

now.MONTH now.HOUR

etc.

How to read data from a file in Lua

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);

Why do we have to normalize the input for an artificial neural network?

When you use unnormalized input features, the loss function is likely to have very elongated valleys. When optimizing with gradient descent, this becomes an issue because the gradient will be steep with respect some of the parameters. That leads to large oscillations in the search space, as you are bouncing between steep slopes. To compensate, you have to stabilize optimization with small learning rates.

Consider features x1 and x2, where range from 0 to 1 and 0 to 1 million, respectively. It turns out the ratios for the corresponding parameters (say, w1 and w2) will also be large.

Normalizing tends to make the loss function more symmetrical/spherical. These are easier to optimize because the gradients tend to point towards the global minimum and you can take larger steps.

Quicksort: Choosing the pivot

If you are sorting a random-accessible collection (like an array), it's general best to pick the physical middle item. With this, if the array is all ready sorted (or nearly sorted), the two partitions will be close to even, and you'll get the best speed.

If you are sorting something with only linear access (like a linked-list), then it's best to choose the first item, because it's the fastest item to access. Here, however,if the list is already sorted, you're screwed -- one partition will always be null, and the other have everything, producing the worst time.

However, for a linked-list, picking anything besides the first, will just make matters worse. It pick the middle item in a listed-list, you'd have to step through it on each partition step -- adding a O(N/2) operation which is done logN times making total time O(1.5 N *log N) and that's if we know how long the list is before we start -- usually we don't so we'd have to step all the way through to count them, then step half-way through to find the middle, then step through a third time to do the actual partition: O(2.5N * log N)

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

enter image description here

How to return a value from __init__ in Python?

Just wanted to add, you can return classes in __init__

@property
def failureException(self):
    class MyCustomException(AssertionError):
        def __init__(self_, *args, **kwargs):
            *** Your code here ***
            return super().__init__(*args, **kwargs)

    MyCustomException.__name__ = AssertionError.__name__
    return MyCustomException

The above method helps you implement a specific action upon an Exception in your test

Installing Numpy on 64bit Windows 7 with Python 2.7.3

You may also try this, anaconda http://continuum.io/downloads

But you need to modify your environment variable PATH, so that the anaconda folder is before the original Python folder.

How to get character array from a string?

The ES6 way to split a string into an array character-wise is by using the spread operator. It is simple and nice.

array = [...myString];

Example:

_x000D_
_x000D_
let myString = "Hello world!"
array = [...myString];
console.log(array);

// another example:

console.log([..."another splitted text"]);
_x000D_
_x000D_
_x000D_

Split a List into smaller lists of N size

I have a generic method that would take any types include float, and it's been unit-tested, hope it helps:

    /// <summary>
    /// Breaks the list into groups with each group containing no more than the specified group size
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="values">The values.</param>
    /// <param name="groupSize">Size of the group.</param>
    /// <returns></returns>
    public static List<List<T>> SplitList<T>(IEnumerable<T> values, int groupSize, int? maxCount = null)
    {
        List<List<T>> result = new List<List<T>>();
        // Quick and special scenario
        if (values.Count() <= groupSize)
        {
            result.Add(values.ToList());
        }
        else
        {
            List<T> valueList = values.ToList();
            int startIndex = 0;
            int count = valueList.Count;
            int elementCount = 0;

            while (startIndex < count && (!maxCount.HasValue || (maxCount.HasValue && startIndex < maxCount)))
            {
                elementCount = (startIndex + groupSize > count) ? count - startIndex : groupSize;
                result.Add(valueList.GetRange(startIndex, elementCount));
                startIndex += elementCount;
            }
        }


        return result;
    }

How do I list all the columns in a table?

For MS SQL Server:

select * from information_schema.columns where table_name = 'tableName'

Creating a custom JButton in Java

I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit javax.swing.AbstractButton and create your own. Should be pretty simple to wire something together with their existing framework.

Foreign Key to non-primary key

As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic.

Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a significant overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications.

Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.

How to break lines at a specific character in Notepad++?

  1. Click Ctrl + h or Search -> Replace on the top menu
  2. Under the Search Mode group, select Regular expression
  3. In the Find what text field, type ],\s*
  4. In the Replace with text field, type ],\n
  5. Click Replace All

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Sort array by value alphabetically php

You want the php function "asort":

http://php.net/manual/en/function.asort.php

it sorts the array, maintaining the index associations.

Edit: I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort():

http://php.net/manual/en/function.sort.php

The mysqli extension is missing. Please check your PHP configuration

I encountered this problem today and eventually I realize it was the comment on the line before the mysql dll's that was causing the problem.

This is what you should have in php.ini by default for PHP 5.5.16:

;extension=php_exif.dll       Must be after mbstring as it depends on it
;extension=php_mysql.dll
;extension=php_mysqli.dll

Besides removing the semi-colons, you also need to delete the line of comment that came after php_exif.dll. This leaves you with

extension=php_exif.dll      
extension=php_mysql.dll
extension=php_mysqli.dll

This solves the problem in my case.

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

How can I access an internal class from an external assembly?

Reflection.

using System.Reflection;

Vendor vendor = new Vendor();
object tag = vendor.Tag;

Type tagt = tag.GetType();
FieldInfo field = tagt.GetField("test");

string value = field.GetValue(tag);

Use the power wisely. Don't forget error checking. :)

JavaFX FXML controller - constructor vs initialize method

In a few words: The constructor is called first, then any @FXML annotated fields are populated, then initialize() is called.

This means the constructor does not have access to @FXML fields referring to components defined in the .fxml file, while initialize() does have access to them.

Quoting from the Introduction to FXML:

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

If treating strings as bytes is more your thing, you can use the following functions

function u_atob(ascii) {
    return Uint8Array.from(atob(ascii), c => c.charCodeAt(0));
}

function u_btoa(buffer) {
    var binary = [];
    var bytes = new Uint8Array(buffer);
    for (var i = 0, il = bytes.byteLength; i < il; i++) {
        binary.push(String.fromCharCode(bytes[i]));
    }
    return btoa(binary.join(''));
}


// example, it works also with astral plane characters such as ''
var encodedString = new TextEncoder().encode('?');
var base64String = u_btoa(encodedString);
console.log('?' === new TextDecoder().decode(u_atob(base64String)))

Traits vs. interfaces

If you know English and know what trait means, it is exactly what the name says. It is a class-less pack of methods and properties you attach to existing classes by typing use.

Basically, you could compare it to a single variable. Closures functions can use these variables from outside of the scope and that way they have the value inside. They are powerful and can be used in everything. Same happens to traits if they are being used.

Bootstrap alert in a fixed floating div at the top of page

You can use this class : class="sticky-top alert alert-dismissible"

Changing the width of Bootstrap popover

I used this(working fine) :

.popover{
   background-color:#b94a48;
   border:none;
   border-radius:unset;
   min-width:100px;
   width:100%;
   max-width:400px;
   overflow-wrap:break-word;
}

Simplest code for array intersection in javascript

"filter" and "indexOf" aren't supported on Array in IE. How about this:

var array1 = [1, 2, 3];
var array2 = [2, 3, 4, 5];

var intersection = [];
for (i in array1) {
    for (j in array2) {
        if (array1[i] == array2[j]) intersection.push(array1[i]);
    }
}

Is std::vector copying the objects with a push_back?

Not only does std::vector make a copy of whatever you're pushing back, but the definition of the collection states that it will do so, and that you may not use objects without the correct copy semantics within a vector. So, for example, you do not use auto_ptr in a vector.

Batch Script to Run as Administrator

Create a shortcut and set the shortcut to always run as administrator.

How-To Geek forum Make a batch file to run cmd as administrator solution:

Make a batch file in an editor and nameit.bat then create a shortcut to it. Nameit.bat - shortcut. then right click on Nameit.bat - shortcut ->Properties->Shortcut tab -> Advanced and click Run as administrator. Execute it from the shortcut.

How to check if a variable is an integer or a string?

The isdigit method of the str type returns True iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.