Programs & Examples On #Character class

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

img onclick call to JavaScript function

Put the javascript part and the end right before the closing </body> then it should work.

http://jsfiddle.net/Q3Zy3/1/

  <img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
  <button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>

  <script type="text/javascript">
      function exportToForm(a,b,c,d,e) {
      alert(a + b);
      window.external.values(a.value, b.value, c.value, d.value, e.value);
  }
</script>

Laravel view not found exception

Somewhat embarrassingly, I discovered another rather trivial cause for this error: I had a full stop in the filename of my blade file (eg resources/views/pages/user.invitation.blade.php). It really did make sense at the time!

I was trying to reference it like so: view('pages.user.invitation')

but of course Laravel was looking for the file at resources/views/pages/user/invitation.blade.php and throwing the view not found.

Hope this helps someone.

Usage of MySQL's "IF EXISTS"

The accepted answer works well and one can also just use the

If Exists (...) Then ... End If; 

syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert

One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!

How to disable the ability to select in a DataGridView?

I liked user4101525's answer best in theory but it doesn't actually work. Selection is not an overlay so you see whatever is under the control

Ramgy Borja's answer doesn't deal with the fact that default style is not actually a color at all so applying it doesn't help. This handles the default style and works if applying your own colors (which may be what edhubbell refers to as nasty results)

dgv.RowsDefaultCellStyle.SelectionBackColor = dgv.RowsDefaultCellStyle.BackColor.IsEmpty ? System.Drawing.Color.White : dgv.RowsDefaultCellStyle.BackColor;
dgv.RowsDefaultCellStyle.SelectionForeColor = dgv.RowsDefaultCellStyle.ForeColor.IsEmpty ? System.Drawing.Color.Black : dgv.RowsDefaultCellStyle.ForeColor;

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Make sure, following jar file included in your class path and lib folder.

spring-core-3.0.5.RELEASE.jar

enter image description here

if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${org.springframework.version}</version>
</dependency>

Note : Replace ${org.springframework.version} with version number.

An object reference is required to access a non-static member

playSound is a static method in your class, but you are referring to members like audioSounds or minTime which are not declared static so they would require a SoundManager sm = new SoundManager(); to operate as sm.audioSounds or sm.minTime respectively

Solution:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Actually, You are blocked by SSMS not the SQL Server.

So the solution are either change setting of SSMS or use a SQL query.

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

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

Another perspective from Logging point of view Only.

I see a lot of discussion related to logging on this thread so thought of adding my experience in answer. May be someone will find it useful.

I guess the motivation of logging using formatter comes from avoiding the string concatenation. Basically, you do not want to have an overhead of string concat if you are not going to log it.

You do not really need to concat/format unless you want to log. Lets say if I define a method like this

public void logDebug(String... args, Throwable t) {
    if(debugOn) {
       // call concat methods for all args
       //log the final debug message
    }
}

In this approach the cancat/formatter is not really called at all if its a debug message and debugOn = false

Though it will still be better to use StringBuilder instead of formatter here. The main motivation is to avoid any of that.

At the same time I do not like adding "if" block for each logging statement since

  • It affects readability
  • Reduces coverage on my unit tests - thats confusing when you want to make sure every line is tested.

Therefore I prefer to create a logging utility class with methods like above and use it everywhere without worrying about performance hit and any other issues related to it.

Find everything between two XML tags with RegEx

It is not a good idea to use regex for HTML/XML parsing...

However, if you want to do it anyway, search for regex pattern

<primaryAddress>[\s\S]*?<\/primaryAddress>

and replace it with empty string...

Why does adb return offline after the device string?

After wasting hours on it, I have updated my version of adb and now adb devices shows my device online and I can run the app on it again.

How do I iterate over a JSON structure?

Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];
}

RESULT: John Doe 25

How to get an absolute file path in Python

This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess.

import sys,os

filename = sys.argv[0]

from there, you can get the script's full path with:

>>> os.path.abspath(filename)
'/foo/bar/script.py'

It also makes easier to navigate folders by just appending /.. as many times as you want to go 'up' in the directories' hierarchy.

To get the cwd:

>>> os.path.abspath(filename+"/..")
'/foo/bar'

For the parent path:

>>> os.path.abspath(filename+"/../..")
'/foo'

By combining "/.." with other filenames, you can access any file in the system.

SQL Stored Procedure: If variable is not null, update statement

Another approach when you have many updates would be to use COALESCE:

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = COALESCE(@ABC, [ABC]),
    [ABCD] = COALESCE(@ABCD, [ABCD])

Remove first 4 characters of a string with PHP

You could use the substr function please check following example,

$string1 = "tarunmodi";
$first4 = substr($string1, 4);
echo $first4;

Output: nmodi

T-SQL - function with default parameters

With user defined functions, you have to declare every parameter, even if they have a default value.

The following would execute successfully:

IF dbo.CheckIfSFExists( 23, default ) = 0
    SET @retValue = 'bla bla bla;

How do you receive a url parameter with a spring controller mapping

You have a lot of variants for using @RequestParam with additional optional elements, e.g.

@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr

If you don't put required = false - param will be required by default.

defaultValue = "someValue" - the default value to use as a fallback when the request parameter is not provided or has an empty value.

If request and method param are the same - you don't need value = "someAttr"

How to convert FileInputStream to InputStream?

InputStream is;

try {
    is = new FileInputStream("c://filename");

    is.close(); 
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

return is;

Jenkins Host key verification failed

Copy host keys from both bitbucket and github:

ssh root@deployserver 'echo "$(ssh-keyscan -t rsa,dsa bitbucket.org)" >> /root/.ssh/known_hosts'
ssh root@deployserver 'echo "$(ssh-keyscan -t rsa,dsa github.com)" >> /root/.ssh/known_hosts'

In Python, can I call the main() of an imported module?

It depends. If the main code is protected by an if as in:

if __name__ == '__main__':
    ...main code...

then no, you can't make Python execute that because you can't influence the automatic variable __name__.

But when all the code is in a function, then might be able to. Try

import myModule

myModule.main()

This works even when the module protects itself with a __all__.

from myModule import * might not make main visible to you, so you really need to import the module itself.

Background Image for Select (dropdown) does not work in Chrome

Generally, it's considered a bad practice to style standard form controls because the output looks so different on each browser. See: http://www.456bereastreet.com/lab/styling-form-controls-revisited/select-single/ for some rendered examples.

That being said, I've had some luck making the background color an RGBA value:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        background: #d00;
      }
      select {
        background: rgba(255,255,255,0.1) url('http://www.google.com/images/srpr/nav_logo6g.png') repeat-x 0 0; 
        padding:4px; 
        line-height: 21px;
        border: 1px solid #fff;
      }
    </style>
  </head>
  <body>
    <select>
      <option>Foo</option>
      <option>Bar</option>      
      <option>Something longer</option>     
  </body>
</html>

Google Chrome still renders a gradient on top of the background image in the color that you pass to rgba(r,g,b,0.1) but choosing a color that compliments your image and making the alpha 0.1 reduces the effect of this.

Getting Python error "from: can't read /var/mail/Bio"

No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).

Another possibility is to add the following line to the top of the script:

#!/usr/bin/env python

This will instruct your shell to execute the script via python instead of trying to interpret it on its own.

How can I add spaces between two <input> lines using CSS?

You can also wrap your text in label fields, so your form will be more self-explainable semantically.

Just remember to float labels and inputs to the left and to add a specific width to them, and the containing form. Then you can add margins to both of them, to adjust the spacing between the lines (you understand, of course, that this is a pretty minimal markup that expects content to be as big as to some limit).

That way you wont have to add any more elements, just the label-input pairs, all of them wrapped in a form element.

For example:

<form>
<label for="txtName">Name</label>
<input id"txtName" type="text">
<label for="txtEmail">Email</label>
<input id"txtEmail" type="text">
<label for="txtAddress">Address</label>
<input id"txtAddress" type="text">
...
<input type="submit" value="Submit The Form">
</form>

And the css will be:

form{
float:left; /*to clear the floats of inner elements,usefull if you wanna add a border or background image*/
width:300px;
}
label{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
input{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}

Returning a boolean value in a JavaScript function

You could wrap your return value in the Boolean function

Boolean([return value])

That'll ensure all falsey values are false and truthy statements are true.

Print JSON parsed object?

You know what JSON stands for? JavaScript Object Notation. It makes a pretty good format for objects.

JSON.stringify(obj) will give you back a string representation of the object.

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

I had the same problem. Try to go to Build - Rebuild project. I didn't get that problem again and my app successfully started.

Why use argparse rather than optparse?

There are also new kids on the block!

  • Besides the already mentioned deprecated optparse. [DO NOT USE]
  • argparse was also mentioned, which is a solution for people not willing to include external libs.
  • docopt is an external lib worth looking at, which uses a documentation string as the parser for your input.
  • click is also external lib and uses decorators for defining arguments. (My source recommends: Why Click)
  • python-inquirer For selection focused tools and based on Inquirer.js (repo)

If you need a more in-depth comparison please read this and you may end up using docopt or click. Thanks to Kyle Purdon!

Convert normal date to unix timestamp

var datestr = '2012.08.10';
var timestamp = (new Date(datestr.split(".").join("-")).getTime())/1000;

write a shell script to ssh to a remote machine and execute commands

You can follow this approach :

  • Connect to remote machine using Expect Script. If your machine doesn't support expect you can download the same. Writing Expect script is very easy (google to get help on this)
  • Put all the action which needs to be performed on remote server in a shell script.
  • Invoke remote shell script from expect script once login is successful.

The character encoding of the HTML document was not declared

I had the same problem when I ran my form application in Firefox. Adding <meta charset="utf-8"/> in the html code solved my issue in Firefox.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>Voice clip upload</title>_x000D_
  <script src="voiceclip.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <h2>Upload Voice Clip</h2>_x000D_
  <form id="upload_form" enctype="multipart/form-data" method="post">_x000D_
    <input type="file" name="file1" id="file1" onchange="uploadFile()"><br>_x000D_
    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>_x000D_
  </form>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Get current value when change select option - Angular2

Checkout this working Plunker

<select (change)="onItemChange($event.target.value)">
    <option *ngFor="#value of values" [value]="value.key">{{value.value}}</option>
</select>

How do I pass JavaScript variables to PHP?

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

What are .NumberFormat Options In Excel VBA?

dovers gives us his great answer and based on it you can try use it like

public static class CellDataFormat
{
        public static string General { get { return "General"; } }
        public static string Number { get { return "0"; } }

        // Your custom format 
        public static string NumberDotTwoDigits { get { return "0.00"; } }

        public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
        public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
        public static string Date { get { return "m/d/yy"; } }
        public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
        public static string Percentage { get { return "0.00%"; } }
        public static string Fraction { get { return "# ?/?"; } }
        public static string Scientific { get { return "0.00E+00"; } }
        public static string Text { get { return "@"; } }
        public static string Special { get { return ";;"; } }
        public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

How to hide Bootstrap previous modal when you opening new one?

Toggle both modals

$('#modalOne').modal('toggle');
$('#modalTwo').modal('toggle');

HTML combo box with option to type an entry

Given that the HTML datalist tag is still not fully supported, an alternate approach that I used is the Dojo Toolkit ComboBox. It was easier to implement and better documented than other options I've explored. It also plays nicely with existing frameworks. In my case, I added this combobox to an existing website that's based on Codeigniter and Bootstrap with no problems You just need to be sure to apply the Dojo theme (e.g. class="claro") to the combo's parent element instead of the body tag to avoid styling conflicts.

First, include the CSS for one of the Dojo themes (such as 'Claro'). It's important that the CSS file is included prior to the JS files below.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.9.6/dijit/themes/claro/claro.css" />

Next, include jQuery and Dojo Toolkit via CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"></script>

Next, you can just follow Dojo's sample code or use the sample below to get a working combobox.

<body>
    <!-- Dojo Dijit ComboBox with 'Claro' theme -->
    <div class="claro"><input id="item_name_1" class=""/></div>

    <script type="text/javascript">
        $(document).ready(function () {
            //In this example, dataStore is simply an array of JSON-encoded id/name pairs
            dataStore = [{"id":"43","name":"Domain Name Renewal"},{"id":"42","name":"Hosting Renewal"}];

            require(
                [ "dojo/store/Memory", "dijit/form/ComboBox", "dojo/domReady!"], 
                function (Memory, ComboBox) {
                    var stateStore = new Memory({
                        data: dataStore
                    });

                    var combo = new ComboBox({
                        id: "item_name_1",
                        name: "desc_1",
                        store: stateStore,
                        searchAttr: "name"},                        
                        "item_name_1"
                        ).startup();

                });

        });

    </script>
</body>

Get today date in google appScript

The following can be used to get the date:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

split string only on first instance of specified character

Non-regex solution

I ran some benchmarks, and this solution won hugely:1

str.slice(str.indexOf(delim) + delim.length)

// as function
function gobbleStart(str, delim) {
    return str.slice(str.indexOf(delim) + delim.length);
}

// as polyfill
String.prototype.gobbleStart = function(delim) {
    return this.slice(this.indexOf(delim) + delim.length);
};

Performance comparison with other solutions

The only close contender was the same line of code, except using substr instead of slice.

Other solutions I tried involving split or RegExps took a big performance hit and were about 2 orders of magnitude slower. Using join on the results of split, of course, adds an additional performance penalty.

Why are they slower? Any time a new object or array has to be created, JS has to request a chunk of memory from the OS. This process is very slow.

Here are some general guidelines, in case you are chasing benchmarks:

  • New dynamic memory allocations for objects {} or arrays [] (like the one that split creates) will cost a lot in performance.
  • RegExp searches are more complicated and therefore slower than string searches.
  • If you already have an array, destructuring arrays is about as fast as explicitly indexing them, and looks awesome.

Removing beyond the first instance

Here's a solution that will slice up to and including the nth instance. It's not quite as fast, but on the OP's question, gobble(element, '_', 1) is still >2x faster than a RegExp or split solution and can do more:

/*
`gobble`, given a positive, non-zero `limit`, deletes
characters from the beginning of `haystack` until `needle` has
been encountered and deleted `limit` times or no more instances
of `needle` exist; then it returns what remains. If `limit` is
zero or negative, delete from the beginning only until `-(limit)`
occurrences or less of `needle` remain.
*/
function gobble(haystack, needle, limit = 0) {
  let remain = limit;
  if (limit <= 0) { // set remain to count of delim - num to leave
    let i = 0;
    while (i < haystack.length) {
      const found = haystack.indexOf(needle, i);
      if (found === -1) {
        break;
      }
      remain++;
      i = found + needle.length;
    }
  }

  let i = 0;
  while (remain > 0) {
    const found = haystack.indexOf(needle, i);
    if (found === -1) {
      break;
    }
    remain--;
    i = found + needle.length;
  }
  return haystack.slice(i);
}

With the above definition, gobble('path/to/file.txt', '/') would give the name of the file, and gobble('prefix_category_item', '_', 1) would remove the prefix like the first solution in this answer.


  1. Tests were run in Chrome 70.0.3538.110 on macOSX 10.14.

org.hibernate.PersistentObjectException: detached entity passed to persist

Here you have used native and assigning value to the primary key, in native primary key is auto generated.

Hence the issue is coming.

Save array in mysql database

Store it in multi valued column with a comma separator in an RDBMs table.

In Python script, how do I set PYTHONPATH?

PYTHONPATH ends up in sys.path, which you can modify at runtime.

import sys
sys.path += ["whatever"]

How to convert Nvarchar column to INT

You can always use the ISNUMERIC helper function to convert only what's really numeric:

SELECT
     CAST(A.my_NvarcharColumn AS BIGINT)
FROM 
     A
WHERE
     ISNUMERIC(A.my_NvarcharColumn) = 1

jQuery window scroll event does not fire up

To whom its just not working to (like me) no matter what you tried: <element onscroll="myFunction()"></element> works like a charm

exactly as they explain in W3 schools https://www.w3schools.com/tags/ev_onscroll.asp

Pandas Merging 101

A supplemental visual view of pd.concat([df0, df1], kwargs). Notice that, kwarg axis=0 or axis=1 's meaning is not as intuitive as df.mean() or df.apply(func)


on pd.concat([df0, df1])

When should we call System.exit in Java

In that case, it's not needed. No extra threads will have been started up, you're not changing the exit code (which defaults to 0) - basically it's pointless.

When the docs say the method never returns normally, it means the subsequent line of code is effectively unreachable, even though the compiler doesn't know that:

System.exit(0);
System.out.println("This line will never be reached");

Either an exception will be thrown, or the VM will terminate before returning. It will never "just return".

It's very rare to be worth calling System.exit() IME. It can make sense if you're writing a command line tool, and you want to indicate an error via the exit code rather than just throwing an exception... but I can't remember the last time I used it in normal production code.

How to close an iframe within iframe itself

None of this solution worked for me since I'm in a cross-domain scenario creating a bookmarklet like Pinterest's Pin It.

I've found a bookmarklet template on GitHub https://gist.github.com/kn0ll/1020251 that solved the problem of closing the Iframe sending the command from within it.

Since I can't access any element from parent window within the IFrame, this communication can only be made posting events between the two windows using window.postMessage

All these steps are on the GitHub link:

1- You have to inject a JS file on the parent page.

2- In this file injected on the parent, add a window event listner

    window.addEventListener('message', function(e) {
       var someIframe = window.parent.document.getElementById('iframeid');
       someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
    });

This listener will handle the close and any other event you wish

3- Inside the Iframe page you send the close command via postMessage:

   $(this).trigger('post-message', [{
                    event: 'unload-bookmarklet'
                }]);

Follow the template on https://gist.github.com/kn0ll/1020251 and you'll be fine!

Hope it helps,

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

You need to put package-info.java in your generated jaxb package. Its content should be something like that

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.org/StudentOperations/")
package generated.marsh;

Passing capturing lambda as function pointer

Shafik Yaghmour's answer correctly explains why the lambda cannot be passed as a function pointer if it has a capture. I'd like to show two simple fixes for the problem.

  1. Use std::function instead of raw function pointers.

    This is a very clean solution. Note however that it includes some additional overhead for the type erasure (probably a virtual function call).

    #include <functional>
    #include <utility>
    
    struct Decide
    {
      using DecisionFn = std::function<bool()>;
      Decide(DecisionFn dec) : dec_ {std::move(dec)} {}
      DecisionFn dec_;
    };
    
    int
    main()
    {
      int x = 5;
      Decide greaterThanThree { [x](){ return x > 3; } };
    }
    
  2. Use a lambda expression that doesn't capture anything.

    Since your predicate is really just a boolean constant, the following would quickly work around the current issue. See this answer for a good explanation why and how this is working.

    // Your 'Decide' class as in your post.
    
    int
    main()
    {
      int x = 5;
      Decide greaterThanThree {
        (x > 3) ? [](){ return true; } : [](){ return false; }
      };
    }
    

How to upper case every first letter of word in a string?

public class WordChangeInCapital{

   public static void main(String[]  args)
   {
      String s="this is string example";
      System.out.println(s);
      //this is input data.
      //this example for a string where each word must be started in capital letter
      StringBuffer sb=new StringBuffer(s);
      int i=0;
      do{
        b.replace(i,i+1,sb.substring(i,i+1).toUpperCase());
        i=b.indexOf(" ",i)+1;
      } while(i>0 && i<sb.length());
      System.out.println(sb.length());
   }

}

Fit cell width to content

There are many ways to do this!

correct me if I'm wrong but the question is looking for this kind of result.

<table style="white-space:nowrap;width:100%;">
<tr>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:auto">this should be the content width</td>
</tr>
</table>

The first 2 fields will "share" the remaining page (NOTE: if you add more text to either 50% fields it will take more space), and the last field will dominate the table constantly.

If you are happy to let text wrap you can move white-space:nowrap; to the style of the 3rd field
will be the only way to start a new line in that field.

alternatively, you can set a length on the last field ie. width:150px, and leave percentage's on the first 2 fields.

Hope this helps!

Long vs Integer, long vs int, what to use and when?

An int is a 32-bit integer; a long is a 64-bit integer. Which one to use depends on how large the numbers are that you expect to work with.

int and long are primitive types, while Integer and Long are objects. Primitive types are more efficient, but sometimes you need to use objects; for example, Java's collection classes can only work with objects, so if you need a list of integers you have to make it a List<Integer>, for example (you can't use int in a List directly).

find if an integer exists in a list of integers

The best of code and complete is here:

NumbersList.Exists(p => p.Equals(Input)

Use:

List<int> NumbersList = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
    int Input = Convert.ToInt32(textBox1.Text);
    if (!NumbersList.Exists(p => p.Equals(Input)))
    {
       NumbersList.Add(Input);
    }
    else
    {
        MessageBox.Show("The number entered is in the list","Error");
    }
}

How do I use WPF bindings with RelativeSource?

If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

If you want to get a property on an ancestor:

{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}

Subtract a value from every number in a list in Python?

This will work:

for i in range(len(a)):
  a[i] -= 13

What is the proper REST response code for a valid request but an empty data?

I'd say, neither is really appropriate. As has been said – e.g. by @anneb, I, too, think that part of the problems arises from using an HTTP response code to transport a status relating to a RESTful service. Anything the REST service has to say about its own processing should be transported by means of REST specific codes.

1

I'd argue that, if the HTTP server finds any service that is ready to answer a request it was sent, it should not respond with an HTTP 404 – in the end, something was found by the server – unless told so explicitly by the service that processes the request.

Let's assume for a moment the following URL: http://example.com/service/return/test.

  • Case A is that the server is “simply looking for the file on the file system“. If it is not present, 404 is correct. The same is true, if it asks some kind of service to deliver exactly this file and that service tells it that nothing of that name exists.
  • In case B, the server does not work with “real” files but actually the request is processed by some other service – e.g. some kind of templating system. Here, the server cannot make any claim about the existence of the resource as it knows nothing about it (unless told by the service handling it).

Without any response from the service explicitly requiring a different behaviour, the HTTP server can only say 3 things:

  • 503 if the service that is supposed to handle the request is not running or responding;
  • 200 otherwise as the HTTP server can actually satisfy the request – no matter what the service will say later;
  • 400 or 404 to indicate that there is no such service (as opposed to “exists but offline”) and nothing else was found.

2

To get back to the question at hand: I think the cleanest approach would be to not use an HTTP any response code at all other than said before. If the service is present and responding, the HTTP code should be 200. The response should contain the status the service returned in a separate header – here, the service can say

  • REST:EMPTY e.g. if it was asked to search for sth. and that research returned empty;
  • REST:NOT FOUND if it was asked specifically for sth. “ID-like” – be that a file name or a resource by ID or entry No. 24, etc. – and that specific resource was not found (usually, one specific resource was requested and not found);
  • REST:INVALID if any part of the request it was sent is not recognized by the service.

(note that I prefixed these with “REST:” on purpose to mark the fact that while these may have the same values or wording as do HTTP response codes, they are sth. completely different)

3

Let's get back to the URL above and inspect case B where service indicates to the HTTP server that it does not handle this request itself but passes it on to SERVICE. HTTP only serves out what it is handed back by SERVICE, it does not know anything about the return/test portion as that is handeled by SERVICE. If that service is running, HTTP should return 200 as it did indeed find something to handle the request.

The status returned by SERVICE (and which, as said above, would like to see in a separate header) depends on what action is actually expected:

  • if return/test asks for a specific resource: if it exists, return it with a status of REST:FOUND; if that resource does not exist, return REST:NOT FOUND; this could be extended to return REST:GONE if we know it once existed and will not return, and REST:MOVED if we know it has gone hollywood
  • if return/test is considered a search or filter-like operation: if the result set is empty, return an empty set in the type requested and a status of REST:EMPTY; a set of results in the type requested and a status of REST:SUCCESS
  • if return/test is not an operation recogized by SERVICE: return REST:ERROR if it is completely wrong (e.g. a typo like retrun/test), or REST:NOT IMPLEMENTED in case it is planned for later.

4

This distinction is a lot cleaner than mixing the two different things up. It will also make debugging easier and processing only slightly more complex, if at all.

  • If an HTTP 404 is returned, the server tells me, “I have no idea what you're talking about”. While the REST portion of my request might be perectly okay, I'm looking for par'Mach in all the wrong places.
  • On the other hand, HTTP 200 and REST:ERR tells me I got the service but did something wrong in my request to the service.
  • From HTTP 200 and REST:EMPTY, I know that I did nothing wrong – right server, the server found the service, right request to the service – but the search result is empty.

Summary

The problem and discussion arises from the fact that HTTP response codes are being used to denote the state of a service whose results are served by HTTP, or to denote sth. that is not in the scope of the HTTP server itself. Due to this discrepancy, the question cannot be answered and all opinions are subject to a lot of discussion.

The state of a request processed by a service and not the HTTP server REALLY SHOULD NOT (RFC 6919) be given by an HTTP response code. The HTTP code SHOULD (RFC 2119) only contain information the HTTP server can give from its own scope: namely, whether the service was found to process the request or not.

Instead, a different way SHOULD be used to tell a consumer about the state of the request to the service that is actually processing the request. My proposal is to do so via a specific header. Ideally, both the name of the header and its contents follow a standard that makes it easy for consumers to work with theses responses.

Java - Reading XML file

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

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

    }
}

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I had this problem in MacOS, and I solved it by linking the brew installed python 3 version, with

brew link python3

After that, it worked without a problem.

How to mock void methods with Mockito

In your example you should mock Listener item and use Mockito.verify to check interactions with it

Python check if website exists

code:

a="http://www.example.com"
try:    
    print urllib.urlopen(a)
except:
    print a+"  site does not exist"

Doing a cleanup action just before Node.js exits

async-exit-hook seems to be the most up-to-date solution for handling this problem. It's a forked/re-written version of exit-hook that supports async code before exiting.

Big O, how do you calculate/approximate it?

Lets start from the beginning.

First of all, accept the principle that certain simple operations on data can be done in O(1) time, that is, in time that is independent of the size of the input. These primitive operations in C consist of

  1. Arithmetic operations (e.g. + or %).
  2. Logical operations (e.g., &&).
  3. Comparison operations (e.g., <=).
  4. Structure accessing operations (e.g. array-indexing like A[i], or pointer fol- lowing with the -> operator).
  5. Simple assignment such as copying a value into a variable.
  6. Calls to library functions (e.g., scanf, printf).

The justification for this principle requires a detailed study of the machine instructions (primitive steps) of a typical computer. Each of the described operations can be done with some small number of machine instructions; often only one or two instructions are needed. As a consequence, several kinds of statements in C can be executed in O(1) time, that is, in some constant amount of time independent of input. These simple include

  1. Assignment statements that do not involve function calls in their expressions.
  2. Read statements.
  3. Write statements that do not require function calls to evaluate arguments.
  4. The jump statements break, continue, goto, and return expression, where expression does not contain a function call.

In C, many for-loops are formed by initializing an index variable to some value and incrementing that variable by 1 each time around the loop. The for-loop ends when the index reaches some limit. For instance, the for-loop

for (i = 0; i < n-1; i++) 
{
    small = i;
    for (j = i+1; j < n; j++)
        if (A[j] < A[small])
            small = j;
    temp = A[small];
    A[small] = A[i];
    A[i] = temp;
}

uses index variable i. It increments i by 1 each time around the loop, and the iterations stop when i reaches n - 1.

However, for the moment, focus on the simple form of for-loop, where the difference between the final and initial values, divided by the amount by which the index variable is incremented tells us how many times we go around the loop. That count is exact, unless there are ways to exit the loop via a jump statement; it is an upper bound on the number of iterations in any case.

For instance, the for-loop iterates ((n - 1) - 0)/1 = n - 1 times, since 0 is the initial value of i, n - 1 is the highest value reached by i (i.e., when i reaches n-1, the loop stops and no iteration occurs with i = n-1), and 1 is added to i at each iteration of the loop.

In the simplest case, where the time spent in the loop body is the same for each iteration, we can multiply the big-oh upper bound for the body by the number of times around the loop. Strictly speaking, we must then add O(1) time to initialize the loop index and O(1) time for the first comparison of the loop index with the limit, because we test one more time than we go around the loop. However, unless it is possible to execute the loop zero times, the time to initialize the loop and test the limit once is a low-order term that can be dropped by the summation rule.


Now consider this example:

(1) for (j = 0; j < n; j++)
(2)   A[i][j] = 0;

We know that line (1) takes O(1) time. Clearly, we go around the loop n times, as we can determine by subtracting the lower limit from the upper limit found on line (1) and then adding 1. Since the body, line (2), takes O(1) time, we can neglect the time to increment j and the time to compare j with n, both of which are also O(1). Thus, the running time of lines (1) and (2) is the product of n and O(1), which is O(n).

Similarly, we can bound the running time of the outer loop consisting of lines (2) through (4), which is

(2) for (i = 0; i < n; i++)
(3)     for (j = 0; j < n; j++)
(4)         A[i][j] = 0;

We have already established that the loop of lines (3) and (4) takes O(n) time. Thus, we can neglect the O(1) time to increment i and to test whether i < n in each iteration, concluding that each iteration of the outer loop takes O(n) time.

The initialization i = 0 of the outer loop and the (n + 1)st test of the condition i < n likewise take O(1) time and can be neglected. Finally, we observe that we go around the outer loop n times, taking O(n) time for each iteration, giving a total O(n^2) running time.


A more practical example.

enter image description here

What is the default maximum heap size for Sun's JVM from Java SE 6?

java 1.6.0_21 or later, or so...

$ java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
uintx MaxHeapSize                         := 12660904960      {product}

It looks like the min(1G) has been removed.

Or on Windows using findstr

C:\>java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize

Android: How to Programmatically set the size of a Layout

You can get the actual height of called layout with this code:

public int getLayoutSize() {
// Get the layout id
    final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
    final AtomicInteger layoutHeight = new AtomicInteger();

    root.post(new Runnable() { 
    public void run() { 
        Rect rect = new Rect(); 
        Window win = getWindow();  // Get the Window
                win.getDecorView().getWindowVisibleDisplayFrame(rect);

                // Get the height of Status Bar
                int statusBarHeight = rect.top;

                // Get the height occupied by the decoration contents 
                int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();

                // Calculate titleBarHeight by deducting statusBarHeight from contentViewTop  
                int titleBarHeight = contentViewTop - statusBarHeight; 
                Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop); 

                // By now we got the height of titleBar & statusBar
                // Now lets get the screen size
                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);   
                int screenHeight = metrics.heightPixels;
                int screenWidth = metrics.widthPixels;
                Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);   

                // Now calculate the height that our layout can be set
                // If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also 
                layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
                Log.i("MY", "Layout Height = " + layoutHeight);   

            // Lastly, set the height of the layout       
            FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
            rootParams.height = layoutHeight.get();
            root.setLayoutParams(rootParams);
        }
    });

return layoutHeight.get();
}

How to change the MySQL root account password on CentOS7?

Please stop all services MySQL with following command /etc/init.d/mysqld stop After it use this

mysqld_safe --skip-grant-tables

its may work properly

Angular pass callback function to child component as @Input similar to AngularJS way

I think that is a bad solution. If you want to pass a Function into component with @Input(), @Output() decorator is what you are looking for.

export class SuggestionMenuComponent {
    @Output() onSuggest: EventEmitter<any> = new EventEmitter();

    suggestionWasClicked(clickedEntry: SomeModel): void {
        this.onSuggest.emit([clickedEntry, this.query]);
    }
}

<suggestion-menu (onSuggest)="insertSuggestion($event[0],$event[1])">
</suggestion-menu>

Uploading multiple files using formData()

The way to go with javascript:

var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('file', file);
});

$.ajax({
    type: 'POST',
    url: '/your/url',
    cache: false,
    contentType: false,
    processData: false,
    data : data,
    success: function(result){
        console.log(result);
    },
    error: function(err){
        console.log(err);
    }
})

If you call data.append('file', file) multiple times your request will contain an array of your files.

From MDN web docs:

"The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values."

Myself using node.js and multipart handler middleware multer get the data as follows:

router.post('/trip/save', upload.array('file', 10), function(req, res){
    // Your array of files is in req.files
}

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

How to sort alphabetically while ignoring case sensitive?

Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);

react-router go back a page how do you configure history?

In react-router v4.x you can use history.goBack which is equivalent to history.go(-1).

App.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
import Back from "./Back";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "left"
};

const App = () => (
  <div style={styles}>
    <Router>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
        </ul>

        <hr />

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />

        <Back />{/* <----- This is component that will render Back button */}
      </div>
    </Router>
  </div>
);

render(<App />, document.getElementById("root"));

Back.js

import React from "react";
import { withRouter } from "react-router-dom";

const Back = ({ history }) => (
  <button onClick={history.goBack}>Back to previous page</button>
);

export default withRouter(Back);

Demo: https://codesandbox.io/s/ywmvp95wpj

Please remember that by using history your users can leave because history.goBack() can load a page that visitor has visited before opening your application.


To prevent such situation as described above, I've created a simple library react-router-last-location that watch your users last location.

Usage is very straight forward. First you need to install react-router-dom and react-router-last-location from npm.

npm install react-router-dom react-router-last-location --save

Then use LastLocationProvider as below:

App.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { LastLocationProvider } from "react-router-last-location";
//              ?
//              |
//              |
//
//       Import provider
//
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
import Back from "./Back";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "left"
};

const App = () => (
  <div style={styles}>
    <h5>Click on About to see your last location</h5>
    <Router>
      <LastLocationProvider>{/* <---- Put provider inside <Router> */}
        <div>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/contact">Contact</Link></li>
          </ul>

          <hr />

          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/contact" component={Contact} />

          <Back />
        </div>
      </LastLocationProvider>
    </Router>
  </div>
);

render(<App />, document.getElementById("root"));

Back.js

import React from "react";
import { Link } from "react-router-dom";
import { withLastLocation } from "react-router-last-location";
//              ?
//              |
//              |
//
//    `withLastLocation` higher order component
//    will pass `lastLocation` to your component               
//
//                   |
//                   |
//                   ?
const Back = ({ lastLocation }) => (
  lastLocation && <Link to={lastLocation || '/'}>Back to previous page</Link>
);


//          Remember to wrap
//   your component before exporting
//
//                   |
//                   |
//                   ?
export default withLastLocation(Back);

Demo: https://codesandbox.io/s/727nqm99jj

Does a favicon have to be 32x32 or 16x16?

I am not sure if/how browsers scale large icons, but The W3C suggests the following1:

The format for the image you have chosen must be 16x16 pixels or 32x32 pixels, using either 8-bit or 24-bit colors. The format of the image must be one of PNG (a W3C standard), GIF, or ICO.


1 w3c.org: How to Add a Favicon to your Site (Draft in development).

PowerShell: Store Entire Text File Contents in Variable

Powershell 2.0:

(see detailed explanation here)

$text = Get-Content $filePath | Out-String

The IO.File.ReadAllText didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath instead of the current directory (when running from Powershell ISE at least):

$text = [IO.File]::ReadAllText($filePath)

Powershell 3+:

$text = Get-Content $filePath -Raw

Import error: No module name urllib2

The above didn't work for me in 3.3. Try this instead (YMMV, etc)

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

How do I read a resource file from a Java jar file?

I'd like to point out that one issues is what if the same resources are in multiple jar files. Let's say you want to read /org/node/foo.txt, but not from one file, but from each and every jar file.

I have run into this same issue several times before. I was hoping in JDK 7 that someone would write a classpath filesystem, but alas not yet.

Spring has the Resource class which allows you to load classpath resources quite nicely.

I wrote a little prototype to solve this very problem of reading resources form multiple jar files. The prototype does not handle every edge case, but it does handle looking for resources in directories that are in the jar files.

I have used Stack Overflow for quite sometime. This is the second answer that I remember answering a question so forgive me if I go too long (it is my nature).

This is a prototype resource reader. The prototype is devoid of robust error checking.

I have two prototype jar files that I have setup.

 &lt;pre>
         &lt;dependency>
              &lt;groupId>invoke&lt;/groupId>
              &lt;artifactId>invoke&lt;/artifactId>
              &lt;version>1.0-SNAPSHOT&lt;/version>
          &lt;/dependency>

          &lt;dependency>
               &lt;groupId>node&lt;/groupId>
               &lt;artifactId>node&lt;/artifactId>
               &lt;version>1.0-SNAPSHOT&lt;/version>
          &lt;/dependency>

The jar files each have a file under /org/node/ called resource.txt.

This is just a prototype of what a handler would look like with classpath:// I also have a resource.foo.txt in my local resources for this project.

It picks them all up and prints them out.

   

    package com.foo;

    import java.io.File;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.URI;
    import java.net.URL;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;

    /**
    * Prototype resource reader.
    * This prototype is devoid of error checking.
    *
    *
    * I have two prototype jar files that I have setup.
    * <pre>
    *             <dependency>
    *                  <groupId>invoke</groupId>
    *                  <artifactId>invoke</artifactId>
    *                  <version>1.0-SNAPSHOT</version>
    *              </dependency>
    *
    *              <dependency>
    *                   <groupId>node</groupId>
    *                   <artifactId>node</artifactId>
    *                   <version>1.0-SNAPSHOT</version>
    *              </dependency>
    * </pre>
    * The jar files each have a file under /org/node/ called resource.txt.
    * <br />
    * This is just a prototype of what a handler would look like with classpath://
    * I also have a resource.foo.txt in my local resources for this project.
    * <br />
    */
    public class ClasspathReader {

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

            /* This project includes two jar files that each have a resource located
               in /org/node/ called resource.txt.
             */


            /* 
              Name space is just a device I am using to see if a file in a dir
              starts with a name space. Think of namespace like a file extension 
              but it is the start of the file not the end.
            */
            String namespace = "resource";

            //someResource is classpath.
            String someResource = args.length > 0 ? args[0] :
                    //"classpath:///org/node/resource.txt";   It works with files
                    "classpath:///org/node/";                 //It also works with directories

            URI someResourceURI = URI.create(someResource);

            System.out.println("URI of resource = " + someResourceURI);

            someResource = someResourceURI.getPath();

            System.out.println("PATH of resource =" + someResource);

            boolean isDir = !someResource.endsWith(".txt");


            /** Classpath resource can never really start with a starting slash.
             * Logically they do, but in reality you have to strip it.
             * This is a known behavior of classpath resources.
             * It works with a slash unless the resource is in a jar file.
             * Bottom line, by stripping it, it always works.
             */
            if (someResource.startsWith("/")) {
                someResource = someResource.substring(1);
            }

              /* Use the ClassLoader to lookup all resources that have this name.
                 Look for all resources that match the location we are looking for. */
            Enumeration resources = null;

            /* Check the context classloader first. Always use this if available. */
            try {
                resources = 
                    Thread.currentThread().getContextClassLoader().getResources(someResource);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (resources == null || !resources.hasMoreElements()) {
                resources = ClasspathReader.class.getClassLoader().getResources(someResource);
            }

            //Now iterate over the URLs of the resources from the classpath
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();


                /* if the resource is a file, it just means that we can use normal mechanism
                    to scan the directory.
                */
                if (resource.getProtocol().equals("file")) {
                    //if it is a file then we can handle it the normal way.
                    handleFile(resource, namespace);
                    continue;
                }

                System.out.println("Resource " + resource);

               /*

                 Split up the string that looks like this:
                 jar:file:/Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar!/org/node/
                 into
                    this /Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar
                 and this
                     /org/node/
                */
                String[] split = resource.toString().split(":");
                String[] split2 = split[2].split("!");
                String zipFileName = split2[0];
                String sresource = split2[1];

                System.out.printf("After split zip file name = %s," +
                        " \nresource in zip %s \n", zipFileName, sresource);


                /* Open up the zip file. */
                ZipFile zipFile = new ZipFile(zipFileName);


                /*  Iterate through the entries.  */
                Enumeration entries = zipFile.entries();

                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    /* If it is a directory, then skip it. */
                    if (entry.isDirectory()) {
                        continue;
                    }

                    String entryName = entry.getName();
                    System.out.printf("zip entry name %s \n", entryName);

                    /* If it does not start with our someResource String
                       then it is not our resource so continue.
                    */
                    if (!entryName.startsWith(someResource)) {
                        continue;
                    }


                    /* the fileName part from the entry name.
                     * where /foo/bar/foo/bee/bar.txt, bar.txt is the file
                     */
                    String fileName = entryName.substring(entryName.lastIndexOf("/") + 1);
                    System.out.printf("fileName %s \n", fileName);

                    /* See if the file starts with our namespace and ends with our extension.        
                     */
                    if (fileName.startsWith(namespace) && fileName.endsWith(".txt")) {


                        /* If you found the file, print out 
                           the contents fo the file to System.out.*/
                        try (Reader reader = new InputStreamReader(zipFile.getInputStream(entry))) {
                            StringBuilder builder = new StringBuilder();
                            int ch = 0;
                            while ((ch = reader.read()) != -1) {
                                builder.append((char) ch);

                            }
                            System.out.printf("zip fileName = %s\n\n####\n contents of file %s\n###\n", entryName, builder);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    //use the entry to see if it's the file '1.txt'
                    //Read from the byte using file.getInputStream(entry)
                }

            }


        }

        /**
         * The file was on the file system not a zip file,
         * this is here for completeness for this example.
         * otherwise.
         *
         * @param resource
         * @param namespace
         * @throws Exception
         */
        private static void handleFile(URL resource, String namespace) throws Exception {
            System.out.println("Handle this resource as a file " + resource);
            URI uri = resource.toURI();
            File file = new File(uri.getPath());


            if (file.isDirectory()) {
                for (File childFile : file.listFiles()) {
                    if (childFile.isDirectory()) {
                        continue;
                    }
                    String fileName = childFile.getName();
                    if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {

                        try (FileReader reader = new FileReader(childFile)) {
                            StringBuilder builder = new StringBuilder();
                            int ch = 0;
                            while ((ch = reader.read()) != -1) {
                                builder.append((char) ch);

                            }
                            System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", childFile, builder);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }

                }
            } else {
                String fileName = file.getName();
                if (fileName.startsWith(namespace) && fileName.endsWith("txt")) {

                    try (FileReader reader = new FileReader(file)) {
                        StringBuilder builder = new StringBuilder();
                        int ch = 0;
                        while ((ch = reader.read()) != -1) {
                            builder.append((char) ch);

                        }
                        System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", fileName, builder);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

            }
        }

    }


   

You can see a fuller example here with the sample output.

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

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

What is this date format? 2011-08-12T20:17:46.384Z

This technique translates java.util.Date to UTC format (or any other) and back again.

Define a class like so:

import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class UtcUtility {

public static DateTimeFormatter UTC = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC();


public static Date parse(DateTimeFormatter dateTimeFormatter, String date) {
    return dateTimeFormatter.parseDateTime(date).toDate();
}

public static String format(DateTimeFormatter dateTimeFormatter, Date date) {
    return format(dateTimeFormatter, date.getTime());
}

private static String format(DateTimeFormatter dateTimeFormatter, long timeInMillis) {
    DateTime dateTime = new DateTime(timeInMillis);
    String formattedString = dateTimeFormatter.print(dateTime);
    return formattedString;
}

}

Then use it like this:

Date date = format(UTC, "2020-04-19T00:30:07.000Z")

or

String date = parse(UTC, new Date())

You can also define other date formats if you require (not just UTC)

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

How to get html to print return value of javascript function?

<script type="text/javascript">
    document.write("<p>" + Date() + "</p>");
</script>

Is a good example.

Background color not showing in print preview

I double load my external css source file and change the media="screen" to media="print" and all the borders for my table were shown

Try this :

<link rel="stylesheet" media="print" href="bootstrap.css" />

<link rel="stylesheet" media="screen" href="bootstrap.css" />

How can I pass a parameter in Action?

You're looking for Action<T>, which takes a parameter.

Generating random number between 1 and 10 in Bash Shell Script

To generate in the range: {0,..,9}

r=$(( $RANDOM % 10 )); echo $r

To generate in the range: {40,..,49}

r=$(( $RANDOM % 10 + 40 )); echo $r

RegExp matching string not starting with my

Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?

/^my/

React - How to pass HTML tags in props?

Set the text prop type to any and do this:

<MyComponent text={
    <React.Fragment>
        <div> Hello, World!</div>
    </React.Fragment>
    } 
/>

Example

slashes in url variables

You could easily replace the forward slashes / with something like an underscore _ such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.

How to convert hex string to Java string?

byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);

How to Customize a Progress Bar In Android

If you want to do this in code, here is a sample:

pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
TextView tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
tv.setText("Waiting...");
pd.setCustomTitle(tv);
pd.setIndeterminate(true);
pd.show();

Using TextView gives you an option to change color, size, and font of your text. Otherwise you can just call setMessage(), as usual.

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

You need to add { useNewUrlParser: true } in the mongoose.connect() method.

mongoose.connect('mongodb://localhost:27017/Notification',{ useNewUrlParser: true });

How do you check "if not null" with Eloquent?

We can use

Model::whereNotNull('sent_at');

Or

Model::whereRaw('sent_at is not null');

React: Expected an assignment or function call and instead saw an expression

Expected an assignment or function call and instead saw an expression.

I had this similar error with this code:

const mapStateToProps = (state) => {
    players: state
}

To correct all I needed to do was add parenthesis around the curved brackets

const mapStateToProps = (state) => ({
    players: state
});

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

On npm install: Unhandled rejection Error: EACCES: permission denied

Above answer didn't work for me. Just try to run your command with --unsafe-perm.

e.g

npm install -g node@latest --unsafe-perm

This seems to solve the problem.

How do you test that a Python function throws an exception?

How do you test that a Python function throws an exception?

How does one write a test that fails only if a function doesn't throw an expected exception?

Short Answer:

Use the self.assertRaises method as a context manager:

    def test_1_cannot_add_int_and_str(self):
        with self.assertRaises(TypeError):
            1 + '1'

Demonstration

The best practice approach is fairly easy to demonstrate in a Python shell.

The unittest library

In Python 2.7 or 3:

import unittest

In Python 2.6, you can install a backport of 2.7's unittest library, called unittest2, and just alias that as unittest:

import unittest2 as unittest

Example tests

Now, paste into your Python shell the following test of Python's type-safety:

class MyTestCase(unittest.TestCase):
    def test_1_cannot_add_int_and_str(self):
        with self.assertRaises(TypeError):
            1 + '1'
    def test_2_cannot_add_int_and_str(self):
        import operator
        self.assertRaises(TypeError, operator.add, 1, '1')

Test one uses assertRaises as a context manager, which ensures that the error is properly caught and cleaned up, while recorded.

We could also write it without the context manager, see test two. The first argument would be the error type you expect to raise, the second argument, the function you are testing, and the remaining args and keyword args will be passed to that function.

I think it's far more simple, readable, and maintainable to just to use the context manager.

Running the tests

To run the tests:

unittest.main(exit=False)

In Python 2.6, you'll probably need the following:

unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))

And your terminal should output the following:

..
----------------------------------------------------------------------
Ran 2 tests in 0.007s

OK
<unittest2.runner.TextTestResult run=2 errors=0 failures=0>

And we see that as we expect, attempting to add a 1 and a '1' result in a TypeError.


For more verbose output, try this:

unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))

How do I get the old value of a changed cell in Excel VBA?

Let's first see how to detect and save the value of a single cell of interest. Suppose Worksheets(1).Range("B1") is your cell of interest. In a normal module, use this:

Option Explicit

Public StorageArray(0 to 1) As Variant 
    ' Declare a module-level variable, which will not lose its scope as 
      ' long as the codes are running, thus performing as a storage place.
    ' This is a one-dimensional array. 
      ' The first element stores the "old value", and 
      ' the second element stores the "new value"

Sub SaveToStorageArray()
' ACTION
    StorageArray(0) = StorageArray(1)
        ' Transfer the previous new value to the "old value"

    StorageArray(1) = Worksheets(1).Range("B1").value 
        ' Store the latest new value in Range("B1") to the "new value"

' OUTPUT DEMONSTRATION (Optional)
    ' Results are presented in the Immediate Window.
    Debug.Print "Old value:" & vbTab & StorageArray(0)
    Debug.Print "New value:" & vbTab & StorageArray(1) & vbCrLf

End Sub

Then in the module of Worksheets(1):

Option Explicit

Private HasBeenActivatedBefore as Boolean
    ' Boolean variables have the default value of False.
    ' This is a module-level variable, which will not lose its scope as 
      ' long as the codes are running.

Private Sub Worksheet_Activate()        
    If HasBeenActivatedBefore = False then
        ' If the Worksheet has not been activated before, initialize the
          ' StorageArray as follows.

        StorageArray(1) = Me.Range("B1")
            ' When the Worksheets(1) is activated, store the current value
              ' of Range("B1") to the "new value", before the 
              ' Worksheet_Change event occurs.

        HasBeenActivatedBefore = True
            ' Set this parameter to True, so that the contents
              ' of this if block won't be evaluated again. Therefore, 
              ' the initialization process above will only be executed 
              ' once.
    End If
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("B1")) Is Nothing then
        Call SaveToStorageArray
            ' Only perform the transfer of old and new values when 
              ' the cell of interest is being changed.
    End If
End Sub

This will capture the change of the Worksheets(1).Range("B1"), whether the change is due to the user actively selecting that cell on the Worksheet and changing the value, or due to other VBA codes that change the value of Worksheets(1).Range("B1").

Since we have declared the variable StorageArray as public, you can reference its latest value in other modules in the same VBA project.

To expand our scope to the detection and saving the values of multiple cells of interest, you need to:

  • Declare the StorageArray as a two-dimensional array, with the number of rows equal to the number of cells you are monitoring.
  • Modify the Sub SaveToStorageArray procedure to a more general Sub SaveToStorageArray(TargetSingleCell as Range) and change the relevant codes.
  • Modify the Private Sub Worksheet_Change procedure to accommodate the monitoring of those multiple cells.

Appendix: For more information on the lifetime of variables, please refer to: https://msdn.microsoft.com/en-us/library/office/gg278427.aspx

datetimepicker is not a function jquery

For some reason this link solved my problem...I don't know why tho..

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Then this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

NOTE: I am using Bootstrap 3 and Jquery 1.11.3

Android: Create a toggle button with image and no text

ToggleButton inherits from TextView so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_info_details"
    android:gravity="center"
    android:textOff=""
    android:textOn=""
    android:textSize="0dp" />

The result compared to regular ToggleButton looks like

enter image description here

The seconds option is to use an ImageSpan to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.

You create a plain ToggleButton

<ToggleButton
    android:id="@+id/toggleButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false" />

Then set the "text" programmatially

ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);

The result here in the middle - icon is placed slightly lower since it takes the place of the text.

enter image description here

Matplotlib figure facecolor (background color)

If you want to change background color, try this:

plt.rcParams['figure.facecolor'] = 'white'

Enforcing the type of the indexed members of a Typescript object?

You can pass a name to the unknown key and then write your types:

type StuffBody = {
  [key: string]: string;
};

Now you can use it in your type checking:

let stuff: StuffBody = {};

But for FlowType there is no need to have name:

type StuffBody = {
  [string]: string,
};

Traverse a list in reverse order in Python

If you need the index and your list is small, the most readable way is to do reversed(list(enumerate(your_list))) like the accepted answer says. But this creates a copy of your list, so if your list is taking up a large portion of your memory you'll have to subtract the index returned by enumerate(reversed()) from len()-1.

If you just need to do it once:

a = ['b', 'd', 'c', 'a']

for index, value in enumerate(reversed(a)):
    index = len(a)-1 - index

    do_something(index, value)

or if you need to do this multiple times you should use a generator:

def enumerate_reversed(lyst):
    for index, value in enumerate(reversed(lyst)):
        index = len(lyst)-1 - index
        yield index, value

for index, value in enumerate_reversed(a):
    do_something(index, value)

Cannot ping AWS EC2 instance

1.Go to EC2 Dashboard and click "Running Instances" on "Security Groups"
2.select the group of your instance which you need to add security.  
3.click on the "Inbound" tab
4.Click "Edit" Button (It will open an popup window)
5.click "Add Rule"
6.Select the "Custom ICMP rule - IPv4" as Type
7.Enter the "0.0.0.0/0" as Source or your public IP

7.Click "Save"

How can I Convert HTML to Text in C#?

This is another solution to convert HTML to Text or RTF in C#:

    SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
    h.OutputFormat = HtmlToRtf.eOutputFormat.TextUnicode;
    string text = h.ConvertString(htmlString);

This library is not free, this is commercial product and it is my own product.

how to implement login auth in node.js

To add to Farid's pseudo-answer,

Consider using Passport.js over everyauth.

The answers to this question provide some insight to the differences.


There are plenty of benefits to offloading your user authentication to Google, Facebook or another website. If your application's requirements are such that you could use Passport as your sole authentication provider or alongside traditional login, it can make the experience easier for your users.

How to import Google Web Font in CSS file?

Use the @import method:

@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');

Obviously, "Open Sans" (Open+Sans) is the font that is imported. So replace it with yours. If the font's name has multiple words, URL-encode it by adding a + sign between each word, as I did.

Make sure to place the @import at the very top of your CSS, before any rules.

Google Fonts can automatically generate the @import directive for you. Once you have chosen a font, click the (+) icon next to it. In bottom-left corner, a container titled "1 Family Selected" will appear. Click it, and it will expand. Use the "Customize" tab to select options, and then switch back to "Embed" and click "@import" under "Embed Font". Copy the CSS between the <style> tags into your stylesheet.

Angular update object in object array

updateValue(data){    
     // retriving index from array
     let indexValue = this.items.indexOf(data);
    // changing specific element in array
     this.items[indexValue].isShow =  !this.items[indexValue].isShow;
}

How do I pass options to the Selenium Chrome driver using Python?

Found the chrome Options class in the Selenium source code.

Usage to create a Chrome driver instance:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

Adding yet another answer here. If you'r eon Windows 2016 Server running IIS 10.0, it may be because IIS is not installed properly. Here's what I'd suggest if you find yourself here.

  1. In Visual Studio, verify the .NET framework version that you used to develop the app. Right click the project, properties page, application tab. Target Framework. In my case it was 4.6.1.

  2. On the web server, Google 'download .net framework 4.6.1' and go to the MS download page which should properly determine the version you need by your browser user agent. In my case it was X64.

  3. Run the installer. Note that it is safe to do so even if you think it may already be there. It will say 'already installed' if it is.

Note: Now you have to ensure that it is properly 'enabled' as a Windows feature. You also have to verify that ASP.NET IIS components are properly installed and enabled too.

  1. Again on the web server, Go to Server Manager, Add roles and features, then choose role based or feature based. Then click Next.

  2. Ensure that the local server is selected on the destination server tab and click next.

  3. On the server roles tab, expand Web Server IIS and Application Development. I neabled everything but server side includes and Websocket protocols.

  4. Under Management Tools, I chose to enable everything (which includes IIS 6 MMC) because of certain legacy features I wanted, but that's another post.

No reboot was required in my case. Hope this helps somebody.

Dynamic variable names in Bash

Use an associative array, with command names as keys.

# Requires bash 4, though
declare -A magic_variable=()

function grep_search() {
    magic_variable[$1]=$( ls | tail -1 )
    echo ${magic_variable[$1]}
}

If you can't use associative arrays (e.g., you must support bash 3), you can use declare to create dynamic variable names:

declare "magic_variable_$1=$(ls | tail -1)"

and use indirect parameter expansion to access the value.

var="magic_variable_$1"
echo "${!var}"

See BashFAQ: Indirection - Evaluating indirect/reference variables.

Retrieve a Fragment from a ViewPager

Another simple solution:

    public class MyPagerAdapter extends FragmentPagerAdapter {
        private Fragment mCurrentFragment;

        public Fragment getCurrentFragment() {
            return mCurrentFragment;
        }
//...    
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            if (getCurrentFragment() != object) {
                mCurrentFragment = ((Fragment) object);
            }
            super.setPrimaryItem(container, position, object);
        }
    }

Declaring a boolean in JavaScript using just var

How about something like this:

var MyNamespace = {
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'undefined' || value === null) return false;

        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
                case 'true':
                case 'yes':
                case '1':
                    return true;
                case 'false':
                case 'no':
                case '0':
                    return false;
            }
        }

        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
};

Then you can use it like this:

MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false

I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

Implementing a Custom Error page on an ASP.Net website

<customErrors defaultRedirect="~/404.aspx" mode="On">
    <error statusCode="404" redirect="~/404.aspx"/>
</customErrors>

Code above is only for "Page Not Found Error-404" if file extension is known(.html,.aspx etc)

Beside it you also have set Customer Errors for extension not known or not correct as

.aspwx or .vivaldo. You have to add httperrors settings in web.config

<httpErrors  errorMode="Custom"> 
       <error statusCode="404" prefixLanguageFilePath="" path="/404.aspx"         responseMode="Redirect" />
</httpErrors>
<modules runAllManagedModulesForAllRequests="true"/>

it must be inside the <system.webServer> </system.webServer>

How to run a script as root on Mac OS X?

In order for sudo to work the way everyone suggest, you need to be in the admin group.

How to get all elements which name starts with some string?

You can try using jQuery with the Attribute Contains Prefix Selector.

$('[id|=q1_]')

Haven't tested it though.

Convert Python dictionary to JSON array

One possible solution that I use is to use python3. It seems to solve many utf issues.

Sorry for the late answer, but it may help people in the future.

For example,

#!/usr/bin/env python3
import json
# your code follows

How do I add python3 kernel to jupyter (IPython)

  1. Got ipython notebook with Python2 (on Windows7)
  2. upgrade to Jupyter with pip install -U jupyter
  3. install Python3
  4. install Jupyter again using pip3 install jupyter
  5. install Python3 kernel using ipython3 kernelspec install-self
  6. I finally got 2 working kernels.

great results

How to negate a method reference predicate

If you're using Spring Boot (2.0.0+) you can use:

import org.springframework.util.StringUtils;

...
.filter(StringUtils::hasLength)
...

Which does: return (str != null && !str.isEmpty());

So it will have the required negation effect for isEmpty

Can a website detect when you are using Selenium with chromedriver?

It works for some websites, remove property webdriver from navigator

from selenium import webdriver
driver = webdriver.Chrome()
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source":
        "const newProto = navigator.__proto__;"
        "delete newProto.webdriver;"
        "navigator.__proto__ = newProto;"
    })

Display all post meta keys and meta values of the same post ID in wordpress

I use it in form of a meta box. Here is a function that dumps values of all the meta data for post.

    function dump_all_meta(){

        echo "<h3>All Post Meta</h3>";

        // Get all the data.
        $getPostCustom=get_post_custom();


        foreach( $getPostCustom as $name=>$value ) {

            echo "<strong>".$name."</strong>"."  =>  ";

            foreach($getPostCustom as $name=>$value) {

        echo "<strong>".$name."</strong>"."  =>  ";

        foreach($value as $nameAr=>$valueAr) {
                echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                echo $nameAr."  =>  ";
                echo var_dump($valueAr);
        }

        echo "<br /><br />";

        }
    } // Callback funtion ended.

Hope it helps. You can use it inside a meta box or at the front-end.

How to check Spark Version

According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.

Possible reason for NGINX 499 error codes

HTTP 499 in Nginx means that the client closed the connection before the server answered the request. In my experience is usually caused by client side timeout. As I know it's an Nginx specific error code.

Drop rows with all zeros in pandas data frame

import pandas as pd

df = pd.DataFrame({'a' : [0,0,1], 'b' : [0,0,-1]})

temp = df.abs().sum(axis=1) == 0      
df = df.drop(temp)

Result:

>>> df
   a  b
2  1 -1

How to use <DllImport> in VB.NET?

You have to add Imports System.Runtime.InteropServices to the top of your source file.

Alternatively, you can fully qualify attribute name:

<System.Runtime.InteropService.DllImport("user32.dll", _
    SetLastError:=True, CharSet:=CharSet.Auto)> _

DateTime fields from SQL Server display incorrectly in Excel

I also had an issue with this problem simply copy and pasting DATETIME fields from SQL Management Studio to Excel for manipulation. Excel has the correct value of the DATETIME (even if the formatting is applied after the paste), but by default doesn't have a built in format to show the SQL DATETIME. Here's the fix:

Right click the cell, and choose Format Cells. Choose Custom. In the Type: input field enter

yyyy-mm-dd hh:mm:ss.000

Reference: http://office.microsoft.com/en-us/excel-help/create-a-custom-number-format-HP010342372.aspx

Given URL is not allowed by the Application configuration

The above answers are right, but you have to make sure you input right URL.

You have to go to: https://developers.facebook.com/apps

  1. Select your app
  2. Click settings
  3. Enter contact email (for publishing)
  4. Click on +add platform
  5. Add your platform (probably WEB)
  6. Enter site URL

You have two choices to enter: http://www.example.com or http://example.com

Your app will work only with one of them. In order to make sure your visitors will use your desired url, use .htaccess on your domain.

Here's good tutorial on that: http://eppand.com/redirect-www-to-non-www-with-htaccess-file/

Enjoy!

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

For Bootstrup 3.2 + FontAwesome

$(document).ready(function(){    
    $('#accordProfile').on('shown.bs.collapse', function () {
       $(".fa-chevron-down").removeClass("fa-chevron-down").addClass("fa-chevron-up");
    });

    $('#accordProfile').on('hidden.bs.collapse', function () {
       $(".fa-chevron-up").removeClass("fa-chevron-up").addClass("fa-chevron-down");
    });
});

Sometimes you have to write so. If so

$('.collapsed span').removeClass('fa-minus').addClass('fa-plus');

Automatically generated (class="collapsed"), when you press the hide menu.

ps when you need to create a tree menu

How to get a microtime in Node.js?

Node.js nanotimer

I wrote a wrapper library/object for node.js on top of the process.hrtime function call. It has useful functions, like timing synchronous and asynchronous tasks, specified in seconds, milliseconds, micro, or even nano, and follows the syntax of the built in javascript timer so as to be familiar.

Timer objects are also discrete, so you can have as many as you'd like, each with their own setTimeout or setInterval process running.

It's called nanotimer. Check it out!

How to edit CSS style of a div using C# in .NET

If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.

Overflow:hidden dots at the end

You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.

Here's a demo on jsbin.

_x000D_
_x000D_
.cut-text { 
  text-overflow: ellipsis;
  overflow: hidden; 
  width: 160px; 
  height: 1.2em; 
  white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
_x000D_
_x000D_

How to make PyCharm always show line numbers

v. community 5.0.4 (linux): File -> Settings -> Editor -> General -> Appearance -> now check 'Show line numbers', confirm w. OK an voila :)

Print time in a batch file (milliseconds)

Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.

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!"

jQuery autoComplete view all on click?

try this:

    $('#autocomplete').focus(function(){
        $(this).val('');
        $(this).keydown();
    }); 

and minLength set to 0

works every time :)

Linux / Bash, using ps -o to get process by specific name?

ps -fC PROCESSNAME

ps and grep is a dangerous combination -- grep tries to match everything on each line (thus the all too common: grep -v grep hack). ps -C doesn't use grep, it uses the process table for an exact match. Thus, you'll get an accurate list with: ps -fC sh rather finding every process with sh somewhere on the line.

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.

Set attribute without value

The accepted answer doesn't create a name-only attribute anymore (as of September 2017).

You should use JQuery prop() method to create name-only attributes.

$(body).prop('data-body', true)

How do I obtain a list of all schemas in a Sql Server database

Try this query here:

SELECT * FROM sys.schemas

This will give you the name and schema_id for all defines schemas in the database you execute this in.

I don't really know what you mean by querying the "schema API" - these sys. catalog views (in the sys schema) are your best bet for any system information about databases and objects in those databases.

Getting first and last day of the current month

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

What is the difference between DAO and Repository patterns?

DAO and Repository pattern are ways of implementing Data Access Layer (DAL). So, let's start with DAL, first.

Object-oriented applications that access a database, must have some logic to handle database access. In order to keep the code clean and modular, it is recommended that database access logic should be isolated into a separate module. In layered architecture, this module is DAL.

So far, we haven't talked about any particular implementation: only a general principle that putting database access logic in a separate module.

Now, how we can implement this principle? Well, one know way of implementing this, in particular with frameworks like Hibernate, is the DAO pattern.

DAO pattern is a way of generating DAL, where typically, each domain entity has its own DAO. For example, User and UserDao, Appointment and AppointmentDao, etc. An example of DAO with Hibernate: http://gochev.blogspot.ca/2009/08/hibernate-generic-dao.html.

Then what is Repository pattern? Like DAO, Repository pattern is also a way achieving DAL. The main point in Repository pattern is that, from the client/user perspective, it should look or behave as a collection. What is meant by behaving like a collection is not that it has to be instantiated like Collection collection = new SomeCollection(). Instead, it means that it should support operations such as add, remove, contains, etc. This is the essence of Repository pattern.

In practice, for example in the case of using Hibernate, Repository pattern is realized with DAO. That is an instance of DAL can be both at the same an instance of DAO pattern and Repository pattern.

Repository pattern is not necessarily something that one builds on top of DAO (as some may suggest). If DAOs are designed with an interface that supports the above-mentioned operations, then it is an instance of Repository pattern. Think about it, If DAOs already provide a collection-like set of operations, then what is the need for an extra layer on top of it?

TypeError: a bytes-like object is required, not 'str'

Whenever you encounter an error with this message use my_string.encode().

(where my_string is the string you're passing to a function/method).

The encode method of str objects returns the encoded version of the string as a bytes object which you can then use. In this specific instance, socket methods such as .send expect a bytes object as the data to be sent, not a string object.

Since you have an object of type str and you're passing it to a function/method that expects an object of type bytes, an error is raised that clearly explains that:

TypeError: a bytes-like object is required, not 'str'

So the encode method of strings is needed, applied on a str value and returning a bytes value:

>>> s = "Hello world"
>>> print(type(s))
<class 'str'>
>>> byte_s = s.encode()
>>> print(type(byte_s))
<class 'bytes'>
>>> print(byte_s)
b"Hello world"

Here the prefix b in b'Hello world' denotes that this is indeed a bytes object. You can then pass it to whatever function is expecting it in order for it to run smoothly.

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Automatically running a batch file as an administrator

You can use PowerShell to run b.bat as administrator from a.bat:

set mydir=%~dp0

Powershell -Command "& { Start-Process \"%mydir%b.bat\" -verb RunAs}"

It will prompt the user with a confirmation dialog. The user chooses YES, and then b.bat will be run as administrator.

Python: CSV write by column rather than row

wr.writerow(item)  #column by column
wr.writerows(item) #row by row

This is quite simple if your goal is just to write the output column by column.

If your item is a list:

yourList = []

with open('yourNewFileName.csv', 'w', ) as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for word in yourList:
        wr.writerow([word])

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

C# haven't static variables at all. You can declare static field in the particular type definition via C#. Static field is a state, shared with all instances of particular type. Hence, the scope of the static field is entire type. That's why you can't declare static field within a method - method is a scope itself, and items declared in a method must be inaccessible over the method's border.

global variable for all controller and views

In Laravel, 5+ you can create a file in the config folder and create variables in that and use that across the app. For instance, I want to store some information based on the site. I create a file called site_vars.php, which looks like this

<?php
return [
    'supportEmail' => '[email protected]',
    'adminEmail' => '[email protected]'
];

Now in the routes, controller, views you can access it using

Config::get('site_vars.supportEmail')

In the views if I this

{{ Config::get('site_vars.supportEmail') }}

It will give [email protected]

Hope this helps.

EDiT- You can also define vars in .env file and use them here. That is the best way in my opinion as it gives you the flexibility to use values that you want on your local machine.

So, you can do something this in the array

'supportEmail' => env('SUPPORT_EMAIL', '[email protected]')

Important - After you do this, don't forget to do

php artisan config:cache

In case, there's still some problem, then you can do this (usually it would never happen but still if it ever happens)

php artisan cache:clear
php artisan config:cache

What are .iml files in Android Studio?

Those files are created and used by Android Studio editor.

You don't need to check in those files to version control.

Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.

Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.

Copy Image from Remote Server Over HTTP

It's extremely simple using file_get_contents. Just provide the url as the first parameter.

Java, reading a file from current directory?

Try

System.getProperty("user.dir")

It returns the current working directory.

Maven: How to include jars, which are not available in reps into a J2EE project?

Continue to use them as a system dependency and copy them over to target/.../WEB-INF/lib ... using the Maven dependency plugin:

http://maven.apache.org/plugins/maven-dependency-plugin/examples/copying-artifacts.html

Installing MySQL Python on Mac OS X

Another option is to use pymysql it is a pure Python client connection to MySQL so you don't have to mess around with compiling, a good exercise, but it can be frustrating if you are just trying to get something done. pymysql follows the same API as MySQLdb, it can essentially be used as a drop in replacement.

Also, it used to be that MySQLdb, did not work with Python 3, but this may have changed, pymysql didn't have that problem which also induced me to switch, this may have changed though. pymysql can be slower than MySQLdb but you'll have to see if you notice that, it is also under a different license (MIT for pymysql, GPL for MySQLdb)

How do you determine what technology a website is built on?

Most ASP.NET sites are easy to identify from the .aspx in the URLs. There are also telltale signs in the HTML source, like a hidden form field named __VIEWSTATE or the WebResource.axd JavaScript. HTML elements will often have id attributes starting with something like _ctl0.

Rails sites will usually include stylesheets from /stylesheets and JavaScript files from /javascripts and each URL will usually have a query string containing a timestamp to thwart caching. Form fields will often follow the naming convention of model_name[attribute_name].

jquery - How to determine if a div changes its height or any css attribute?

Another simple example.

For this sample we can use 100x100 DIV-box:

<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
 // Red box contents here...
</div>

And small jQuery trick:

<script type="text/javascript">
  jQuery("#box").bind("resize", function() {
    alert("Box was resized from 100x100 to 200x200");
  });
  jQuery("#box").width(200).height(200).trigger("resize");
</script>

Steps:

  1. We created DIV block element for resizing operatios
  2. Add simple JavaScript code with:
    • jQuery bind
    • jQuery resizer with trigger action "resize" - trigger is most important thing in my example
  3. After resize you can check the browser alert information

That's all. ;-)

What does 'low in coupling and high in cohesion' mean

In software design high cohesion means that class should do one thing and one thing very well. High cohesion is closely related to Single responsibility principle.

Low coupling suggest that class should have least possible dependencies. Also, dependencies that must exist should be weak dependencies - prefer dependency on interface rather than dependency on concrete class, or prefer composition over inheritance .

High Cohesion and low coupling give us better designed code that is easier to maintain.

How are iloc and loc different?

.loc and .iloc are used for indexing, i.e., to pull out portions of data. In essence, the difference is that .loc allows label-based indexing, while .iloc allows position-based indexing.

If you get confused by .loc and .iloc, keep in mind that .iloc is based on the index (starting with i) position, while .loc is based on the label (starting with l).

.loc

.loc is supposed to be based on the index labels and not the positions, so it is analogous to Python dictionary-based indexing. However, it can accept boolean arrays, slices, and a list of labels (none of which work with a Python dictionary).

iloc

.iloc does the lookup based on index position, i.e., pandas behaves similarly to a Python list. pandas will raise an IndexError if there is no index at that location.

Examples

The following examples are presented to illustrate the differences between .iloc and .loc. Let's consider the following series:

>>> s = pd.Series([11, 9], index=["1990", "1993"], name="Magic Numbers")
>>> s
1990    11
1993     9
Name: Magic Numbers , dtype: int64

.iloc Examples

>>> s.iloc[0]
11
>>> s.iloc[-1]
9
>>> s.iloc[4]
Traceback (most recent call last):
    ...
IndexError: single positional indexer is out-of-bounds
>>> s.iloc[0:3] # slice
1990 11
1993  9
Name: Magic Numbers , dtype: int64
>>> s.iloc[[0,1]] # list
1990 11
1993  9
Name: Magic Numbers , dtype: int64

.loc Examples

>>> s.loc['1990']
11
>>> s.loc['1970']
Traceback (most recent call last):
    ...
KeyError: ’the label [1970] is not in the [index]’
>>> mask = s > 9
>>> s.loc[mask]
1990 11
Name: Magic Numbers , dtype: int64
>>> s.loc['1990':] # slice
1990    11
1993     9
Name: Magic Numbers, dtype: int64

Because s has string index values, .loc will fail when indexing with an integer:

>>> s.loc[0]
Traceback (most recent call last):
    ...
KeyError: 0

Using json_encode on objects in PHP (regardless of scope)

for an array of objects, I used something like this, while following the custom method for php < 5.4:

$jsArray=array();

//transaction is an array of the class transaction
//which implements the method to_json

foreach($transactions as $tran)
{
    $jsArray[]=$tran->to_json();
}

echo json_encode($jsArray);

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

How to implement "confirmation" dialog in Jquery UI dialog?

How about this:

$("ul li a").click(function() {

el = $(this);
$("#confirmDialog").dialog({ autoOpen: false, resizable:false,
                             draggable:true,
                             modal: true,
                             buttons: { "Ok": function() {
                                el.parent().remove();
                                $(this).dialog("close"); } }
                           });
$("#confirmDialog").dialog("open");

return false;
});

I have tested it at this html:

<ul>
<li><a href="#">Hi 1</a></li>
<li><a href="#">Hi 2</a></li>
<li><a href="#">Hi 3</a></li>
<li><a href="#">Hi 4</a></li>
</ul>

It removes the whole li element, you can adapt it at your needs.

How do you use "git --bare init" repository?

This should be enough:

git remote add origin <url-of-bare-repo>
git push --all origin

See for more details "GIT: How do I update my bare repo?".
Notes:

  • you can use a different name than 'origin' for the bare repo remote reference.
  • this won't push your tags, you need a separate git push --tags origin for that.

PHP Warning: Division by zero

try this

if(isset($itemCost) != '' && isset($itemQty) != '')
{
    $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}
else
{
    echo "either of itemCost or itemQty are null";
}

R: "Unary operator error" from multiline ggplot2 command

Try to consolidate the syntax in a single line. this will clear the error

Determine which element the mouse pointer is on top of in JavaScript

Here's a solution for those that may still be struggling. You want to add a mouseover event on the 'parent' element of the child element(s) you want detected. The below code shows you how to go about it.

const wrapper = document.getElementById('wrapper') //parent element
const position = document.getElementById("displaySelection")

wrapper.addEventListener('mousemove', function(e) {
  let elementPointed = document.elementFromPoint(e.clientX, e.clientY)

  console.log(elementPointed)
});

Demo on CodePen

How to watch for a route change in AngularJS?

If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        // handle route changes     
    });
});

Convert Object to JSON string

You can use the excellent jquery-Json plugin:

http://code.google.com/p/jquery-json/

Makes it easy to convert to and from Json objects.

Declare variable in SQLite and use it

I appreciate that the other solutions do not depend on any other software tool, but why not just use another programming language that can interface to SQLite such as C#, C++, Go, Haskell, Java, Lua, Python, or Rust?

Open text file and program shortcut in a Windows batch file

Don't put quotes around the name of the file that you are trying to open; start "myfile.txt" opens a new command prompt with the title myfile.txt, while start myfile.txt opens myfile.txt in Notepad. There's no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start "" "my file.txt" works.

Check If only numeric values were entered in input. (jQuery)

for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/

$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
 var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
 text = window.getSelection().toString();
 } if(index>=0&text.length>0){
  }else if(index>=0&longeur<10){
    }else {return false;} });

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

_x000D_
_x000D_
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();

dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);

document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>

</body>
</html>
_x000D_
_x000D_
_x000D_

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

Where in memory are my variables stored in C?

pointers(ex:char *arr,int *arr) -------> heap

Nope, they can be on the stack or in the data segment. They can point anywhere.

How to read and write into file using JavaScript?

No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled

How to take character input in java

I had the same struggle and I this is what I used:

} public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
System.out.print("Please enter the string: ");
String input = scan.next();
System.out.print("Please enter the required symbol: ");
String symbol = scan.next();        
char symbolChar = symbol.charAt(0);

This works just fine. The idea is to get from the string the only char in it.

How to compare different branches in Visual Studio Code

If you just want to view the changes to a particular file between the working copy and a particular commit using GitLens, the currently accepted answer can make it difficult to find the file you're interested in if many files have changed between the versions.

Instead, go to the file explorer in the side bar and right click on the file, go to Open Changes > Open Changes with Revision... (or Open Changes with Branch or Tag...).

How to implement history.back() in angular.js

In AngularJS2 I found a new way, maybe is just the same thing but in this new version :

import {Router, RouteConfig, ROUTER_DIRECTIVES, Location} from 'angular2/router'; 

(...)

constructor(private _router: Router, private _location: Location) {}

onSubmit() {
    (...)
    self._location.back();
}

After my function, I can see that my application is going to the previous page usgin location from angular2/router.

https://angular.io/docs/ts/latest/api/common/index/Location-class.html

JavaScript push to array

Use the push() function to append to an array:

// initialize array
var arr = [
    "Hi",
    "Hello",
    "Bonjour"
];

// append new value to the array
arr.push("Hola");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
];

// append multiple values to the array
arr.push("Salut", "Hey");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
    "Salut"
    "Hey"
];

// display all values
for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

Will print:

Hi
Hello
Bonjour
Hola 
Salut
Hey

Update

If you want to add the items of one array to another array, you can use Array.concat:

var arr = [
    "apple",
    "banana",
    "cherry"
];

arr = arr.concat([
    "dragonfruit",
    "elderberry",
    "fig"
]);

console.log(arr);

Will print

["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

Failed to install Python Cryptography package with PIP and setup.py

Had same issue in Cygwin, this is what helped me

sudo apt-get install python-pip python-dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev zlib1g-dev

but instead of sudo apt-get install, I installed those packages via Cygwin Source of this code

How to pass credentials to the Send-MailMessage command for sending emails

I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:

$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test" 
$Body = "Test Body" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($SMTPMessage)

Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailFrom="[email protected]",  #This gives a default value to the $EmailFrom command
        [Parameter(`
            mandatory=$false)]
        [String]$attachment,
        [Parameter(`
            mandatory=$true)]
        [String]$Password
    )

        $SMTPServer = "smtp.gmail.com" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        if ($attachment -ne $null) {
            $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
            $SMTPMessage.Attachments.Add($SMTPattachment)
        }
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail

To call it, just use this command:

Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"

I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!

Edit: Added $EmailFrom based on JuanPablo's comment

Edit: SMTP was spelled STMP in the attachments.

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

Convert hex string (char []) to int?

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

unsigned hexdec (const char *hex, const int s_hex);

Before the first conversion intialize the array used for conversion with :

void init_hexdec ();

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

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

Change Screen Orientation programmatically using a Button

Yes, you can set the screen orientation programatically anytime you want using:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.

And this is how you can get the current screen orientation and set it adequatly depending on its current state:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation(); 
 // OR: orientation = getRequestedOrientation(); // inside an Activity

// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {

              switch(orientation) {
                   case Configuration.ORIENTATION_PORTRAIT:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                       break;
                   case Configuration.ORIENTATION_LANDSCAPE:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                       break;                   
               }
          }
   });

Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/

EDIT

Also, you can get the screen orientation using the Configuration:

Activity.getResources().getConfiguration().orientation

Why does Maven have such a bad rep?

Some of my pet peeves with Maven:

  • The XML definition is super clumsy and verbose. Have they never heard of attributes?

  • In its default configuration, it always scours the 'net on every operation. Regardless of whether this is useful for anything, it looks extremely silly to need Internet access for "clean".

  • Again in the default, if I'm not careful to specify exact version numbers, it will pull the very latest updates off the 'net, regardless of whether these newest versions introduce dependency errors. In other words, you're placed at the mercy of other peoples' dependency management.

  • The solution to all this network access is to turn it off by adding the -o option. But you have to remember to turn it off if you really want to do dependency updating!

  • Another solution is to install your own "source control" server for dependencies. Surprise: Most projects already have source control, only that works with no additional setup!

  • Maven builds are incredibly slow. Fiddling with network updates alleviates this, but Maven builds are still slow. And horribly verbose.

  • The Maven plugin (M2Eclipse) integrates most poorly with Eclipse. Eclipse integrates reasonably smoothly with version control software and with Ant. Maven integration is very clunky and ugly by comparison. Did I mention slow?

  • Maven continues to be buggy. Error messages are unhelpful. Too many developers are suffering from this.

Using getResources() in non-activity class

We can use context Like this try now Where the parent is the ViewGroup.

Context context = parent.getContext();

If input field is empty, disable submit button

For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.

$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
    $('#new_post button').prop 'disabled', if @value == '' then true else false
    return

comparing two strings in ruby

var1 is a regular string, whereas var2 is an array, this is how you should compare (in this case):

puts var1 == var2[0]

MySQL create stored procedure syntax with delimiter

MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;

"Items collection must be empty before using ItemsSource."

I had this same error for a while in a slightly different scenario. I had

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGridTextColumn 
        Header="Account Name" 
        Binding="{Binding Path=AccountName}" />
</wpftoolkit:DataGrid>

which I fixed to be

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGrid.Columns>
        <wpftoolkit:DataGridTextColumn 
            Header="Account Name" 
            Binding="{Binding Path=AccountName}" />
    </wpftoolkit:DataGrid.Columns>
</wpftoolkit:DataGrid>

Add borders to cells in POI generated Excel File

Setting up borders in the style used in the cells will accomplish this. Example:

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

How to disable logging on the standard error stream in Python?

You could also:

handlers = app.logger.handlers
# detach console handler
app.logger.handlers = []
# attach
app.logger.handlers = handlers

How to create an android app using HTML 5

You can write complete apps for almost any smartphone platform (Android, iOS,...) using Phonegap. (http://www.phonegap.com)

It is an open source framework that exposes native capabilities to a web view, so that you can do anything a native app can do.

This is very suitable for cross platform development if you're not building something that has to be pixel perfect in every way, or is very hardware intensive.

If you are looking for UI Frameworks that can be used to build such apps, there is a wide range of different libraries. (Like Sencha, jQuery mobile, ...)

And to be a little biased, there is something I built as well: http://www.m-gwt.com

jquery select element by xpath

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

If you are a student and new to Java there might be some issue going on with your web.xml file.

  1. Try removing the web.xml file.
  2. Secondly check that your path variables are properly set or not.
  3. Restart tomcat server Or your PC.

Your problem will be surely solved.

Conditionally formatting cells if their value equals any value of another column

All you need to do for that is a simple loop.
This doesn't handle testing for lower case, upper-case mismatch. If this isn't exactly what you are looking for, comment, and I can revise.

If you are planning to learn VBA. This is a great start.

TESTED:

Sub MatchAndColor()

Dim lastRow As Long
Dim sheetName As String

    sheetName = "Sheet1"            'Insert your sheet name here
    lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row

    For lRow = 2 To lastRow         'Loop through all rows

        If Sheets(sheetName).Cells(lRow, "A") = Sheets(sheetName).Cells(lRow, "B") Then
            Sheets(sheetName).Cells(lRow, "A").Interior.ColorIndex = 3  'Set Color to RED
        End If

    Next lRow

End Sub

EXAMPLE

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

.htaccess file to allow access to images folder to view pictures?

<Directory /uploads>
   Options +Indexes
</Directory>

How to fix corrupt HDFS FIles

If you just want to get your HDFS back to normal state and don't worry much about the data, then

This will list the corrupt HDFS blocks:

hdfs fsck -list-corruptfileblocks

This will delete the corrupted HDFS blocks:

hdfs fsck / -delete

Note that, you might have to use sudo -u hdfs if you are not the sudo user (assuming "hdfs" is name of the sudo user)

Missing styles. Is the correct theme chosen for this layout?

This is very late but i like to share my experience this same issue. i face the same issue in Android studio i tried to some other solution that i found in internet but nothing works for me unless i REBUILD THE PROJECT and it solve my issue.

Hope this will works for you too.

Happy coding.

Bulk Record Update with SQL

You can do this through a regular UPDATE with a JOIN

UPDATE T1
SET Description = T2.Description
   FROM Table1 T1
      JOIN Table2 T2
         ON T2.ID = T1.DescriptionId

How to save an HTML5 Canvas as an image on a server?

Send canvas image to PHP:

var photo = canvas.toDataURL('image/jpeg');                
$.ajax({
  method: 'POST',
  url: 'photo_upload.php',
  data: {
    photo: photo
  }
});

Here's PHP script:
photo_upload.php

<?php

    $data = $_POST['photo'];
    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);

    mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");

    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
    die;
?>

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

I had this problem with chrome when I was working on a WordPress site. I added this code

$_SERVER['HTTPS'] = false;

into the theme's functions.php file - it asks you to log in again when you save the file but once it's logged in it works straight away.

Typescript - multidimensional array initialization

You can do the following (which I find trivial, but its actually correct). For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).

Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following

const myArray: any[][] = [];

And later, when you want to populate it, you can do the following:

myArray.push([<your value goes here>]);

A short example of the above can be the following:

const myArray: string[][] = [];
myArray.push(["value1", "value2"]);