Programs & Examples On #Point in polygon

Algorithm for determining whether a point is inside a polygon. Normally calculated by counting the number of polygon line segments that a ray from the point intersects.

How can I determine whether a 2D Point is within a Polygon?

This question is so interesting. I have another workable idea different from other answers to this post. The idea is to use the sum of angles to decide whether the target is inside or outside. Better known as winding number.

Let x be the target point. Let array [0, 1, .... n] be the all the points of the area. Connect the target point with every border point with a line. If the target point is inside of this area. The sum of all angles will be 360 degrees. If not the angles will be less than 360.

Refer to this image to get a basic understanding of the idea: enter image description here

My algorithm assumes the clockwise is the positive direction. Here is a potential input:

[[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]

The following is the python code that implements the idea:

def isInside(self, border, target):
degree = 0
for i in range(len(border) - 1):
    a = border[i]
    b = border[i + 1]

    # calculate distance of vector
    A = getDistance(a[0], a[1], b[0], b[1]);
    B = getDistance(target[0], target[1], a[0], a[1])
    C = getDistance(target[0], target[1], b[0], b[1])

    # calculate direction of vector
    ta_x = a[0] - target[0]
    ta_y = a[1] - target[1]
    tb_x = b[0] - target[0]
    tb_y = b[1] - target[1]

    cross = tb_y * ta_x - tb_x * ta_y
    clockwise = cross < 0

    # calculate sum of angles
    if(clockwise):
        degree = degree + math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))
    else:
        degree = degree - math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))

if(abs(round(degree) - 360) <= 3):
    return True
return False

What is cURL in PHP?

cURL

  • cURL is a way you can hit a URL from your code to get a HTML response from it.
  • It's used for command line cURL from the PHP language.
  • cURL is a library that lets you make HTTP requests in PHP.

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().

Sample Code

// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);

//setting url
$url = 'http://example.com/api';

//data
$data = array("message" => "Hello World!!!");

try {
    $ch = curl_init($url);
    $data_string = json_encode($data);

    if (FALSE === $ch)
        throw new Exception('failed to initialize');

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

        $output = curl_exec($ch);

    if (FALSE === $output)
        throw new Exception(curl_error($ch), curl_errno($ch));

    // ...process $output now
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);
}

For more information, please check -

Bootstrap navbar Active State not working

Bootstrap 4 requires you to target the li item for active classes. In order to do that you have to find the parent of the a. The 'hitbox' of the a is as big as the li but due to bubbeling of event in JS it will give you back the a event. So you have to manually add it to its parent.

  //set active navigation after click
  $(".nav-link").on("click", (event) => {
    $(".navbar-nav").find(".active").removeClass('active');
    $(event.target).parent().addClass('active');
  });

XPath with multiple conditions

Use:

/category[@name='Sport' and author/text()[1]='James Small']

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]]

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename

is equivalent to:

somename

so it is recommended to use the latter.

How to convert a time string to seconds?

There is always parsing by hand

>>> import re
>>> ts = ['00:00:00,000', '00:00:10,000', '00:01:04,000', '01:01:09,000']
>>> for t in ts:
...     times = map(int, re.split(r"[:,]", t))
...     print t, times[0]*3600+times[1]*60+times[2]+times[3]/1000.
... 
00:00:00,000 0.0
00:00:10,000 10.0
00:01:04,000 64.0
01:01:09,000 3669.0
>>> 

Remove CSS class from element with JavaScript (no jQuery)

function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }

OSError [Errno 22] invalid argument when use open() in Python

import pandas as pd
df = pd.read_excel ('C:/Users/yourlogin/new folder/file.xlsx')
print (df)

How to change the color of progressbar in C# .NET 3.5?

Modificaton to dustyburwell's answer. (I don't have enough rep to edit it myself.) Like his answer, it works with "Visual Styles" enabled. You can just set the progressbar's ForeColor property in whatever form's design view.

using System;
using System.Windows.Forms;
using System.Drawing;

public class ProgressBarEx : ProgressBar
{
    private SolidBrush brush = null;

    public ProgressBarEx()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (brush == null || brush.Color != this.ForeColor)
            brush = new SolidBrush(this.ForeColor);

        Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
        if (ProgressBarRenderer.IsSupported)
            ProgressBarRenderer.DrawHorizontalBar(e.Graphics, rec);
        rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
        rec.Height = rec.Height - 4;
        e.Graphics.FillRectangle(brush, 2, 2, rec.Width, rec.Height);
    }
}

Counting number of characters in a file through shell script

Credits to user.py et al.


echo "ää" > /tmp/your_file.txt
cat /tmp/your_file.txt | wc -m

results in 3.

In my example the result is expected to be 2 (twice the letter ä). However, echo (or vi) adds a line break \n to the end of the output (or file). So two ä and one Linux line break \n are counted. That's three together.

Working with pipes | is not the shortest variant, but so I have to know less wc parameters by heart. In addition, cat is bullet-proof in my experience.

Tested on Ubuntu 18.04.1 LTS (Bionic Beaver).

python date of the previous month

Building off the comment of @J.F. Sebastian, you can chain the replace() function to go back one "month". Since a month is not a constant time period, this solution tries to go back to the same date the previous month, which of course does not work for all months. In such a case, this algorithm defaults to the last day of the prior month.

from datetime import datetime, timedelta

d = datetime(2012, 3, 31) # A problem date as an example

# last day of last month
one_month_ago = (d.replace(day=1) - timedelta(days=1))
try:
    # try to go back to same day last month
    one_month_ago = one_month_ago.replace(day=d.day)
except ValueError:
    pass
print("one_month_ago: {0}".format(one_month_ago))

Output:

one_month_ago: 2012-02-29 00:00:00

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You should add the pipe to the interpolation and not to the ngFor

ul
  li(*ngFor='let movie of (movies)') ///////////removed here///////////////////
    | {{ movie.title | async }}

Reference docs

Sort divs in jQuery based on attribute 'data-sort'?

Answered the same question here:

To repost:

After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...

  1. select all object via jquery selector
  2. convert to actual array (not array-like jquery object)
  3. sort the array of objects
  4. convert back to jquery object with the array of dom objects

Html

<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>

Plain jquery selector

$('.item');
[<div class="item" data-order="2">2</div>,
 <div class="item" data-order="1">1</div>,
 <div class="item" data-order="4">4</div>,
 <div class="item" data-order="3">3</div>
]

Lets sort this by data-order

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>,
 <div class="item" data-order="2">2</div>,
 <div class="item" data-order="3">3</div>,
 <div class="item" data-order="4">4</div>
]

See how getSorted() works.

Hope this helps!

Unsetting array values in a foreach loop

One solution would be to use the key of your items to remove them -- you can both the keys and the values, when looping using foreach.

For instance :

$arr = array(
    'a' => 123,
    'b' => 456,
    'c' => 789, 
);

foreach ($arr as $key => $item) {
    if ($item == 456) {
        unset($arr[$key]);
    }
}

var_dump($arr);

Will give you this array, in the end :

array
  'a' => int 123
  'c' => int 789


Which means that, in your case, something like this should do the trick :

foreach($images as $key => $image)
{
    if($image == 'http://i27.tinypic.com/29yk345.gif' ||
    $image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
    $image == 'http://i42.tinypic.com/9pp2456x.gif')
    {
        unset($images[$key]);
    }
}

Access elements of parent window from iframe

I think the problem may be that you are not finding your element because of the "#" in your call to get it:

window.parent.document.getElementById('#target'); 

You only need the # if you are using jquery. Here it should be:

window.parent.document.getElementById('target'); 

Using Laravel Homestead: 'no input file specified'

If you renamed the folder containing your Homestead project, you'll get this error. Visit your Homestead.yaml file and update any references to point to the renamed folder, then do vagrant up (etc.) again

How to set default value to the input[type="date"]

Use Microsoft Visual Studio

Date separator '-'

@{string dateValue = request.Date.ToString("yyyy'-'MM'-'ddTHH:mm:ss");}

< input type="datetime-local" class="form-control" name="date1" value="@dateValue" >

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

SSIS Excel Connection Manager failed to Connect to the Source

My answer is very similar to the one from @biscoop, but I am going to elaborate a bit as it may apply to the question or to other people.

I had a .xls that was an extraction from one of our webapps. The Excel connection would not work (error message: "no tables or views could be loaded"). As a side note, when opening the file, there would be a warning stating that the file was from an online source and that the content needed activation.

I tried to save the same file as an .xlsx and it worked. I tried to save the same file with another name as an .xls and it worked too. So as a last test I only opened the source .xls file, clicking save and the connection worked.

Short answer: just try and see if opening the file and saving does the trick.

Check if option is selected with jQuery, if not select a default

While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length) {
    $("#mySelect option[value='3']").attr('selected', 'selected');
  }
});
</script>

Printing with sed or awk a line following a matching pattern

Actually sed -n '/pattern/{n;p}' filename will fail if the pattern match continuous lines:

$ seq 15 |sed -n '/1/{n;p}'
2
11
13
15

The expected answers should be:

2
11
12
13
14
15

My solution is:

$ sed -n -r 'x;/_/{x;p;x};x;/pattern/!s/.*//;/pattern/s/.*/_/;h' filename

For example:

$ seq 15 |sed -n -r 'x;/_/{x;p;x};x;/1/!s/.*//;/1/s/.*/_/;h'
2
11
12
13
14
15

Explains:

  1. x;: at the beginning of each line from input, use x command to exchange the contents in pattern space & hold space.
  2. /_/{x;p;x};: if pattern space, which is the hold space actually, contains _ (this is just a indicator indicating if last line matched the pattern or not), then use x to exchange the actual content of current line to pattern space, use p to print current line, and x to recover this operation.
  3. x: recover the contents in pattern space and hold space.
  4. /pattern/!s/.*//: if current line does NOT match pattern, which means we should NOT print the NEXT following line, then use s/.*// command to delete all contents in pattern space.
  5. /pattern/s/.*/_/: if current line matches pattern, which means we should print the NEXT following line, then we need to set a indicator to tell sed to print NEXT line, so use s/.*/_/ to substitute all contents in pattern space to a _(the second command will use it to judge if last line matched the pattern or not).
  6. h: overwrite the hold space with the contents in pattern space; then, the content in hold space is ^_$ which means current line matches the pattern, or ^$, which means current line does NOT match the pattern.
  7. the fifth step and sixth step can NOT exchange, because after s/.*/_/, the pattern space can NOT match /pattern/, so the s/.*// MUST be executed!

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

How do I get the XML root node with C#?

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;

How to subtract X day from a Date object in Java?

With Java 8 it's really simple now:

 LocalDate date = LocalDate.now().minusDays(300);

A great guide to the new api can be found here.

How do I use Maven through a proxy?

Those are caused most likely by 2 issues:

  1. You need to add proxy configuration to your settings.xml. Here's a trick in your username field. Make sure it looks like domain\username. Setting domain there and putting this exact slash is important '\'. You might want to use <![CDATA[]]> tag if your password contains non xml-friendly characters.
  2. I've noticed maven 2.2.0 does not work sometimes through a proxy at all, where 2.2.1 works perfectly fine.

If some of those are omitted - maven could fail with random error messages.

Just hope I've saved somebody from googling around this issue for 6 hours, like I did.

How do I fetch lines before/after the grep result in bash?

This prints 10 lines of trailing context after matching lines

grep -i "my_regex" -A 10

If you need to print 10 lines of leading context before matching lines,

grep -i "my_regex" -B 10

And if you need to print 10 lines of leading and trailing output context.

grep -i "my_regex" -C 10

Example

user@box:~$ cat out 
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
user@box:~$

Normal grep

user@box:~$ grep my_regex out 
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines after

user@box:~$ grep -A 2 my_regex out   
line 5 my_regex
line 6
line 7
user@box:~$ 

Grep exact matching lines and 2 lines before

user@box:~$ grep -B 2 my_regex out  
line 3
line 4
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines before and after

user@box:~$ grep -C 2 my_regex out  
line 3
line 4
line 5 my_regex
line 6
line 7
user@box:~$ 

Reference: manpage grep

-A num
--after-context=num

    Print num lines of trailing context after matching lines.
-B num
--before-context=num

    Print num lines of leading context before matching lines.
-C num
-num
--context=num

    Print num lines of leading and trailing output context.

Why is json_encode adding backslashes?

Can anyone tell me why json_encode adds slashes?

Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.

Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.

It doesn't. In JSON "/" and "\/" are equivalent.

The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.

How to convert current date to epoch timestamp?

enter image description hereI think this answer needs an update and the solution would go better this way.

from datetime import datetime

datetime.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S").strftime("%s")

or you may use datetime object and format the time using %s to convert it into epoch time.

How to refresh an access form

You can repaint and / or requery:

On the close event of form B:

Forms!FormA.Requery

Is this what you mean?

UITableView with fixed section headers

Swift 3.0

Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.

lazy var tableView: UITableView = {
    let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
    view.delegate = self
    view.dataSource = self
    view.separatorStyle = .none
    return view
}()

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

Authentication plugin 'caching_sha2_password' is not supported

pip3 install mysql-connector-python did solve my problem as well. Ignore using mysql-connector module.

Touch move getting stuck Ignored attempt to cancel a touchmove

I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.

My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this

function onTouchStart() {
  window.addEventListener("touchmove", handleTouchMove, {
    passive: false
  });
}

function onTouchEnd() {
  window.removeEventListener("touchmove", handleTouchMove, {
    passive: true
  });
}

function handleTouchMove(e) {
  e.preventDefault();
}

For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:

let stopScrolling = false;

window.addEventListener("touchmove", handleTouchMove, {
  passive: false
});

function handleTouchMove(e) {
  if (!stopScrolling) {
    return;
  }
  e.preventDefault();
}

function onTouchStart() {
  stopScrolling = true;
}

function onTouchEnd() {
  stopScrolling = false;
}

I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!

Database corruption with MariaDB : Table doesn't exist in engine

You may try to:

  • backup your database folder from C:\xampp\mysql\data (.frm & .ibd files only corresponding your table names)
  • reinstall xampp and recopy DB folder at C:\xampp\mysql\data
  • modify my.ini add

    [mysqld]
    innodb_file_per_table = on
    
  • then open phpmyadmin (or any other DB viewer as Navicat or MYSQL Workbench) and run

    ALTER TABLE tbl_name IMPORT TABLESPACE 
    

    for each table

  • Once you can open your tables make a full mysql dump

  • delete everything and make a clean install

I know, a lot of work to do that you don't need it.

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

How to bring back "Browser mode" in IE11?

[UPDATE]

The original question, and the answer below applied specifically to the IE11 preview releases.

The final release version of IE11 does in fact provide the ability to switch browser modes from the Emulation tab in the dev tools:

Screenshot showing browser mode selection in the emulation tab

Having said that, the advice I've given here (and elsewhere) to avoid using compatibility modes for testing is still valid: If you want to test your site for compatibility with older IE versions, you should always do your testing in a real copy of those IE version.

However, this does mean that the registry hack described in @EugeneXa's answer to bring back the old dev tools is no longer necessary, since the new dev tools do now have the feature he was missing.


[ORIGINAL ANSWER]

The IE devs have deliberately deprecated the ability to switch browser mode.

There are not many reasons why people would be switching modes in the dev tools, but one of the main reasons is because they want to test their site in old IE versions. Unfortunately, the various compatibility modes that IE supplies have never really been fully compatible with old versions of IE, and testing using compat mode is simply not a good enough substitute for testing in real copies of IE8, IE9, etc.

The IE devs have recognised this and are deliberately making it harder for devs to make this mistake.

The best practice is to use real copies of each IE version to test your site instead.

The various compatiblity modes are still available inside IE11, but can only be accessed if a site explicitly states that it wants to run in compat mode. You would do this by including an X-UA-Compatible header on your page.

And the Document Mode drop-box is still available, but will only ever offer the options of "Edge" (that is, the best mode available to the current IE version, so IE11 mode in IE11) or the mode that the page is running in.

So if you go to a page that is loaded in compat mode, you will have the option to switch between the specific compat mode that the page was loaded in or IE11 "Edge" mode.

And if you go to a page that loads in IE11 mode, then you will only be offered the 'edge' mode and nothing else.

This means that it does still allow you to test how a compat mode page reacts to being updated to work in Edge mode, which is about the only really legitimate use-case for the document mode drop-box anyway.

The IE11 Document Mode drop box has an i icon next to it which takes you to the modern.ie website. The point of this is to encourage you to download the VMs that MS are supplying for us to test our sites using real copies of each version of IE. This will give you a much more accurate testing experience, and is strongly enouraged as a much better practice than testing by switching the mode in dev tools.

Hope that explains things a bit for you.

Can you get the column names from a SqlDataReader?

var reader = cmd.ExecuteReader();

var columns = new List<string>();

for(int i=0;i<reader.FieldCount;i++)
{
   columns.Add(reader.GetName(i));
}

or

var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();

Removing viewcontrollers from navigation stack

You can first get all the view controllers in the array and then after checking with the corresponding view controller class, you can delete the one you want.

Here is small piece of code:

NSArray* tempVCA = [self.navigationController viewControllers];

for(UIViewController *tempVC in tempVCA)
{
    if([tempVC isKindOfClass:[urViewControllerClass class]])
    {
        [tempVC removeFromParentViewController];
    }
}

I think this will make your work easier.

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

window.onload vs document.onload

window.onload however they are often the same thing. Similarly body.onload becomes window.onload in IE.

not finding android sdk (Unity)

1- Just open https://developer.android.com/studio/index.html

2- scroll down to the bottom of that page

3- download last version of tools for your OS (for example tools_r25.2.3-windows.zip)

4- Unzip it

5- Delete folder tools from previous Android Sdk folder

6- Copy new folder tools to Android SDK Folder like this image:

enter image description here

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

You could also use an extra function like:

    function checkFileType(filename, typeRegEx) {
        if (filename.length < 4 || typeRegEx.length < 1) return false;
        var filenameParts = filename.split('.');
        if (filenameParts.length < 2) return false;
        var fileExtension = filenameParts[filenameParts.length - 1];
        return typeRegEx.test('.' + fileExtension);
    }

Add inline style using Javascript

Try something like this

document.getElementById("vid-holder").style.width=300 + "px";

Check if a number has a decimal place/is a whole number

Number.isInteger() is probably the most concise. It returns true if it is an integer, and false if it isn't.

Increase heap size in Java

It is possible to increase heap size allocated by the JVM by using command line options Here we have 3 options

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

java -Xms16m -Xmx64m ClassName

In the above line we can set minimum heap to 16mb and maximum heap 64mb

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

On Windows 10 - This happened for me after the latest update in 2020.

What solved this issue for me was running the following in PowerShell

C:\>Install-Module -Name MicrosoftPowerBIMgmt

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

You can use the below to navigate back in 2017.3.4

Alt + Left

How do I programmatically set the value of a select box element using JavaScript?

Most of the code mentioned here didn't worked for me!

At last, this worked

window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options

    window.addEventListener("load", function () {
            // Selecting Element with ID - leaveCode  //
            var formObj = document.getElementById('leaveCode');

            // Setting option as selected
            let len;
            for (let i = 0, len = formObj.length; i < len; i++){
                if (formObj[i].value == '<value to show in Select>') 
                 formObj.options[i].selected = true;
            }
    });

Hope, this helps!

How to determine the encoding of text?

This site has python code for recognizing ascii, encoding with boms, and utf8 no bom: https://unicodebook.readthedocs.io/guess_encoding.html. Read file into byte array (data): http://www.codecodex.com/wiki/Read_a_file_into_a_byte_array. Here's an example. I'm in osx.

#!/usr/bin/python                                                                                                  

import sys

def isUTF8(data):
    try:
        decoded = data.decode('UTF-8')
    except UnicodeDecodeError:
        return False
    else:
        for ch in decoded:
            if 0xD800 <= ord(ch) <= 0xDFFF:
                return False
        return True

def get_bytes_from_file(filename):
    return open(filename, "rb").read()

filename = sys.argv[1]
data = get_bytes_from_file(filename)
result = isUTF8(data)
print(result)


PS /Users/js> ./isutf8.py hi.txt                                                                                     
True

What's the -practical- difference between a Bare and non-Bare repository?

This is not a new answer, but it helped me to understand the different aspects of the answers above (and it is too much for a comment).

Using Git Bash just try:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init
Initialized empty Git repository in C:/Test/.git/

me@pc MINGW64 /c/Test (master)
$ ls -al
total 20
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 .git/

me@pc MINGW64 /c/Test (master)
$ cd .git

me@pc MINGW64 /c/Test/.git (GIT_DIR!)
$ ls -al
total 15
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ../
-rw-r--r-- 1 myid 1049089 130 Apr  1 11:35 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:35 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:35 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 objects/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 refs/

Same with git --bare:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init --bare
Initialized empty Git repository in C:/Test/

me@pc MINGW64 /c/Test (BARE:master)
$ ls -al
total 23
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:11 ../
-rw-r--r-- 1 myid 1049089 104 Apr  1 11:36 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:36 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:36 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 objects/

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

From David Morgan-Mar's Esoteric Algorithms page: Intelligent Design Sort

Introduction

Intelligent design sort is a sorting algorithm based on the theory of intelligent design.

Algorithm Description

The probability of the original input list being in the exact order it's in is 1/(n!). There is such a small likelihood of this that it's clearly absurd to say that this happened by chance, so it must have been consciously put in that order by an intelligent Sorter. Therefore it's safe to assume that it's already optimally Sorted in some way that transcends our naïve mortal understanding of "ascending order". Any attempt to change that order to conform to our own preconceptions would actually make it less sorted.

Analysis

This algorithm is constant in time, and sorts the list in-place, requiring no additional memory at all. In fact, it doesn't even require any of that suspicious technological computer stuff. Praise the Sorter!

Feedback

Gary Rogers writes:

Making the sort constant in time denies the power of The Sorter. The Sorter exists outside of time, thus the sort is timeless. To require time to validate the sort dimishes the role of the Sorter. Thus... this particular sort is flawed, and can not be attributed to 'The Sorter'.

Heresy!

updating Google play services in Emulator

My answer is not to update the Google play service but work around. Get the play service version of the emulator by using the following code

getPackageManager().getPackageInfo("com.google.android.gms", 0 ).versionName);

For example if the value is "9.8.79" then use the nearest lesser version available com.google.android.gms:play-services:9.8.0'

This will resolve your problem. Get the release history from https://developers.google.com/android/guides/releases#november_2016_-_v100

Passing parameters on button action:@selector

You can sub-class a UIButton named MyButton, and pass the parameter by MyButton's properties.

Then, get the parameter back from (id)sender.

How do you dynamically allocate a matrix?

arr = new int[cols*rows];

If you either don't mind syntax

arr[row * cols + col] = Aij;

or use operator[] overaloading somewhere. This may be more cache-friendly than array of arrays, or may be not, more probably you shouldn't care about it. I just want to point out that a) array of arrays is not only solution, b) some operations are more easier to implement if matrix located in one block of memory. E.g.

for(int i=0;i < rows*cols;++i)
   matrix[i]=someOtherMatrix[i];

one line shorter than

for(int r=0;i < rows;++r)
  for(int c=0;i < cols;++s)
     matrix[r][c]=someOtherMatrix[r][c];

though adding rows to such matrix is more painful

Difference between jar and war in Java

You add web components to a J2EE application in a package called a web application archive (WAR), which is a JAR similar to the package used for Java class libraries. A WAR usually contains other resources besides web components, including:

  • Server-side utility classes (database beans, shopping carts, and so on).
  • Static web resources (HTML, image, and sound files, and so on)
  • Client-side classes (applets and utility classes)

A WAR has a specific hierarchical directory structure. The top-level directory of a WAR is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources are stored.

(source)

So a .war is a .jar, but it contains web application components and is laid out according to a specific structure. A .war is designed to be deployed to a web application server such as Tomcat or Jetty or a Java EE server such as JBoss or Glassfish.

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

Access maven properties defined in the pom

Maven already has a solution to do what you want:

Get MavenProject from just the POM.xml - pom parser?

btw: first hit at google search ;)

Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();

try {
     reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
     model = mavenreader.read(reader);
     model.setPomFile(pomfile);
}catch(Exception ex){
     // do something better here
     ex.printStackTrace()
}

MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need

What is monkey patching?

What is monkey patching? Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time.

Why use monkey patching? It allows us to modify or extend the behavior of libraries, modules, classes or methods at runtime without actually modifying the source code

Conclusion Monkey patching is a cool technique and now we have learned how to do that in Python. However, as we discussed, it has its own drawbacks and should be used carefully.

For more info Please refer [1]: https://medium.com/@nagillavenkatesh1234/monkey-patching-in-python-explained-with-examples-25eed0aea505

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

How to get the current time in milliseconds from C in Linux?

Derived from Dan Moulding's POSIX answer, this should work :

#include <time.h>
#include <math.h>

long millis(){
    struct timespec _t;
    clock_gettime(CLOCK_REALTIME, &_t);
    return _t.tv_sec*1000 + lround(_t.tv_nsec/1.0e6);
}

Also as pointed out by David Guyon: compile with -lm

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

What does the regex \S mean in JavaScript?

I believe it means 'anything but a whitespace character'.

Constructors in JavaScript objects

So what is the point of "constructor" property? Cannot figure out where it could be useful, any ideas?

The point of the constructor property is to provide some way of pretending JavaScript has classes. One of the things you cannot usefully do is change an object's constructor after it's been created. It's complicated.

I wrote a fairly comprehensive piece on it a few years ago: http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

jquery select element by xpath

First create an xpath selector function.

function _x(STR_XPATH) {
    var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
    var xnodes = [];
    var xres;
    while (xres = xresult.iterateNext()) {
        xnodes.push(xres);
    }

    return xnodes;
}

To use the xpath selector with jquery, you can do like this:

$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');

Hope this can help.

How do I get a button to open another activity?

Using an OnClickListener

Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

Button yourButton = (Button) findViewById(R.id.your_buttons_id);

yourButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v){                        
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
});

This is probably most developers preferred method. However, there is a common alternative.

Using onClick in XML

Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

public void yourMethodName(View v){
    startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}

Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

References;

Tab separated values in awk

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -v var="test" 'BEGIN { FS = "[ \t]+" } ; { print $1 "\t" var "\t" $3 }'

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

To fix this install the specific typescript version 3.1.6

npm i [email protected] --save-dev --save-exact

How to create module-wide variables in Python?

You are falling for a subtle quirk. You cannot re-assign module-level variables inside a python function. I think this is there to stop people re-assigning stuff inside a function by accident.

You can access the module namespace, you just shouldn't try to re-assign. If your function assigns something, it automatically becomes a function variable - and python won't look in the module namespace.

You can do:

__DB_NAME__ = None

def func():
    if __DB_NAME__:
        connect(__DB_NAME__)
    else:
        connect(Default_value)

but you cannot re-assign __DB_NAME__ inside a function.

One workaround:

__DB_NAME__ = [None]

def func():
    if __DB_NAME__[0]:
        connect(__DB_NAME__[0])
    else:
        __DB_NAME__[0] = Default_value

Note, I'm not re-assigning __DB_NAME__, I'm just modifying its contents.

iReport not starting using JRE 8

There's another way if you don't want to have older Java versions installed you can do the following:

1) Download the iReport-5.6.0.zip from https://sourceforge.net/projects/ireport/files/iReport/iReport-5.6.0/

2) Download jre-7u67-windows-x64.tar.gz (the one packed in a tar) from https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

3) Extract the iReport and in the extracted folder that contains the bin and etc folders throw in the jre. For example if you unpack twice the jre-7u67-windows-x64.tar.gz you end up with a folder named jre1.7.0_67. Put that folder in the iReport-5.6.0 directory:

enter image description here

and then go into the etc folder and edit the file ireport.conf and add the following line into it:

For Windows jdkhome=".\jre1.7.0_67"

For Linux jdkhome="./jre1.7.0_67"

Note : jre version may change! according to your download of 1.7

enter image description here

now if you run the ireport_w.exe from the bin folder in the iReport directory it should load just fine.

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

how to execute php code within javascript

Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below

<script type="text/javascript">
    var1 = "<?php echo 'Hello';?>";
</script>

Then in the .js file, you can use the variable

alert(var1);

If you try to evaluate php declaration in the .js file, it will NOT work

:not(:empty) CSS selector is not working?

You could try using :placeholder-shown...

_x000D_
_x000D_
input {
  padding: 10px 15px;
  font-size: 16px;
  border-radius: 5px;
  border: 2px solid lightblue;
  outline: 0;
  font-weight:bold;
  transition: border-color 200ms;
  font-family: sans-serif;
}

.validation {
  opacity: 0;
  font-size: 12px;
  font-family: sans-serif;
  color: crimson;
  transition: opacity;
}

input:required:valid {
  border-color: forestgreen;
}

input:required:invalid:not(:placeholder-shown) {
  border-color: crimson;
}

input:required:invalid:not(:placeholder-shown) + .validation {
  opacity: 1;
}

  
_x000D_
<input type="email" placeholder="e-mail" required>
<div class="validation">Not valid</span>
_x000D_
_x000D_
_x000D_

no great support though... caniuse

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

Bluetooth pairing without user confirmation

This need is exactly why createInsecureRfcommSocketToServiceRecord() was added to BluetoothDevice starting in Android 2.3.3 (API Level 10) (SDK Docs)...before that there was no SDK support for this. It was designed to allow Android to connect to devices without user interfaces for entering a PIN code (like an embedded device), but it just as usable for setting up a connection between two devices without user PIN entry.

The corollary method listenUsingInsecureRfcommWithServiceRecord() in BluetoothAdapter is used to accept these types of connections. It's not a security breach because the methods must be used as a pair. You cannot use this to simply attempt to pair with any old Bluetooth device.

You can also do short range communications over NFC, but that hardware is less prominent on Android devices. Definitely pick one, and don't try to create a solution that uses both.

Hope that Helps!

P.S. There are also ways to do this on many devices prior to 2.3 using reflection, because the code did exist...but I wouldn't necessarily recommend this for mass-distributed production applications. See this StackOverflow.

Databound drop down list - initial value

What I do is set the text property of the drop down list AFTER I databind it. Something like this:

   protected void LoadPersonComboBox()
    {
        var p = new PeopleBLL();

        rcmbboxEditPerson.DataSource = p.GetPeople();
        rcmbboxEditPerson.DataBind();
        rcmbboxEditPerson.Text = "Please select an existing person to edit...";
    }

This makes the initial visible value of this dropdown show up, but not actually be a part of the drop down, nor is it a selectable.

How to install Ruby 2.1.4 on Ubuntu 14.04

Best is to install it using rvm(ruby version manager).
Run following commands in a terminal:

sudo apt-get update
sudo apt-get install build-essential make curl
\curl -L https://get.rvm.io | bash -s stable
source ~/.bash_profile
rvm install ruby-2.1.4

Then check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

Also you can directly add ruby bin path to PATH variable. Ruby is installed in

$HOME/.rvm/rubies export PATH=$PATH:$HOME/.rvm/rubies/ruby-2.1.4/bin

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

A more general answer would be to import java.util.Date, then when you need to set a timestamp equal to the current date, simply set it equal to new Date().

Find Facebook user (url to profile page) by known email address

Maybe things changed, but I recall rapleaf had a service where you enter an email address and you could receive a facebook id.
https://www.rapleaf.com/

If something was not in there, one could "sign up" with the email, and it should have a chance to get the data after a while.

I came across this when using a search tool called Maltego a few years back.
The app uses many types of "transforms", and a few where related to facebook and twitter etc..

..or find some new sqli's on fb and fb apps, hehe. :)

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:

HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))

Format..., select formatting, OK, OK.

SO22487695 example

where I have filled yellow the cells that are triggering the red fill result.

Trying to load local JSON file to show data in a html page using JQuery

Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.

According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        
<script type="text/javascript" language="javascript" src="priorities.json"></script> 

<script type="text/javascript">
   $(document).ready(function(e) {
         alert(jsonObject.start.count);
   });
</script>

Your priorities.json file:

var jsonObject = {
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

Or declare a callback function on your page and wrap it like jsonp technique:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js">    </script> 
     <script type="text/javascript">
           $(document).ready(function(e) {

           });

           function jsonCallback(jsonObject){
               alert(jsonObject.start.count);
           }
        </script>

 <script type="text/javascript" language="javascript" src="priorities.json"></script> 

Your priorities.json file:

jsonCallback({
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    })

Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.

With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

make arrayList.toArray() return more specific types

Like this:

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

String[] a = list.toArray(new String[0]);

Before Java6 it was recommended to write:

String[] a = list.toArray(new String[list.size()]);

because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?

If your list is not properly typed you need to do a cast before calling toArray. Like this:

    List l = new ArrayList<String>();

    String[] a = ((List<String>)l).toArray(new String[l.size()]);

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

your file is named Main.java where it should be

WeatherArray.java

How to change the port number for Asp.Net core app?

Yes this will be accesible from other machines if you bind on any external IP address. For example binding to http://*:80 . Note that binding to http://localhost:80 will only bind on 127.0.0.1 interface and therefore will not be accesible from other machines.

Visual Studio is overriding your port. You can change VS port editing this file Properties\launchSettings.json or else set it by code:

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://*:80") // <-----
            .Build();

        host.Run();

A step by step guide using an external config file is available here.

Multiple arguments to function called by pthread_create()?

Because you say

struct arg_struct *args = (struct arg_struct *)args;

instead of

struct arg_struct *args = arguments;

Double quotes within php script echo

Just escape your quotes:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Padding a table row

In CSS 1 and CSS 2 specifications, padding was available for all elements including <tr>. Yet support of padding for table-row (<tr>) has been removed in CSS 2.1 and CSS 3 specifications. I have never found the reason behind this annoying change which also affect margin property and a few other table elements (header, footer, and columns).

Update: in Feb 2015, this thread on the [email protected] mailing list discussed about adding support of padding and border for table-row. This would apply the standard box model also to table-row and table-column elements. It would permit such examples. The thread seems to suggest that table-row padding support never existed in CSS standards because it would have complicated layout engines. In the 30 September 2014 Editor's Draft of CSS basic box model, padding and border properties exist for all elements including table-row and table-column elements. If it eventually becomes a W3C recommendation, your html+css example may work as intended in browsers at last.

Command to list all files in a folder as well as sub-folders in windows

Following commands we can use for Linux or Mac. For Windows we can use below on git bash.

List all files, first level folders, and their contents

ls * -r

List all first-level subdirectories and files

file */*

Save file list to text

file */* *>> ../files.txt
file */* -r *>> ../files-recursive.txt

Get everything

find . -type f

Save everything to file

find . -type f > ../files-all.txt

Pointers in Python?

This is a python pointer (different of c/c++)

>>> a = lambda : print('Hello')
>>> a
<function <lambda> at 0x0000018D192B9DC0>
>>> id(a) == int(0x0000018D192B9DC0)
True
>>> from ctypes import cast, py_object
>>> cast(id(a), py_object).value == cast(int(0x0000018D192B9DC0), py_object).value
True
>>> cast(id(a), py_object).value
<function <lambda> at 0x0000018D192B9DC0>
>>> cast(id(a), py_object).value()
Hello

How to stick text to the bottom of the page?

Try:

.bottom {
    position: fixed;
    bottom: 0;
}

How to include scripts located inside the node_modules folder?

As mentioned by jfriend00 you should not expose your server structure. You could copy your project dependency files to something like public/scripts. You can do this very easily with dep-linker like this:

var DepLinker = require('dep-linker');
DepLinker.copyDependenciesTo('./public/scripts')
// Done

How to import a SQL Server .bak file into MySQL?

The method I used included part of Richard Harrison's method:

So, install SQL Server 2008 Express edition,

This requires the download of the Web Platform Installer "wpilauncher_n.exe" Once you have this installed click on the database selection ( you are also required to download Frameworks and Runtimes)

After instalation go to the windows command prompt and:

use sqlcmd -S \SQLExpress (whilst logged in as administrator)

then issue the following command.

restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak'; GO This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.

RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak' WITH MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf'; GO

I fired up Web Platform Installer and from the what's new tab I installed SQL Server Management Studio and browsed the db to make sure the data was there...

At that point i tried the tool included with MSSQL "SQL Import and Export Wizard" but the result of the csv dump only included the column names...

So instead I just exported results of queries like "select * from users" from the SQL Server Management Studio

Syntax error: Illegal return statement in JavaScript

return only makes sense inside a function. There is no function in your code.

Also, your code is worthy if the Department of Redundancy Department. Assuming you move it to a proper function, this would be better:

return confirm(".json_encode($message).");

EDIT much much later: Changed code to use json_encode to ensure the message contents don't break just because of an apostrophe in the message.

How to delete empty folders using windows command prompt?

Adding to corroded answer from the same referenced page is a PowerShell version http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx#8408736

Get-ChildItem -Recurse . | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

or, more tersely,

gci -R . | where { $_.PSISContainer -and @( $_ | gci ).Count -eq 0 } | ri

credit goes to the posting author

Flutter - Layout a Grid

A simple example loading images into the tiles.

import 'package:flutter/material.dart';

void main() {
  runApp( MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(

      color: Colors.white30,
      child: GridView.count(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
          padding: const EdgeInsets.all(4.0),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
          children: <String>[
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
            'http://www.for-example.org/img/main/forexamplelogo.png',
          ].map((String url) {
            return GridTile(
                child: Image.network(url, fit: BoxFit.cover));
          }).toList()),
    );
  }
}

The Flutter Gallery app contains a real world example, which can be found here.

enter image description here

base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

_x000D_
_x000D_
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
_x000D_
_x000D_

To decode, you can use the atob() function:

_x000D_
_x000D_
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
_x000D_
_x000D_

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

PHP Fatal error: Cannot redeclare class

Just adding;

This error can also occur if you by mistake put a function inside another function.

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Getting All Variables In Scope

The Simplest Way to Get Access to Vars in a Particular Scope

  1. Open Developer Tools > Resources (in Chrome)
  2. Open file with a function that has access to that scope (tip cmd/ctrl+p to find file)
  3. Set breakpoint inside that function and run your code
  4. When it stops at your breakpoint, you can access the scope var through console (or scope var window)

Note: You want to do this against un-minified js.

The Simplest Way to Show All Non-Private Vars

  1. Open Console (in Chrome)
  2. Type: this.window
  3. Hit Enter

Now you will see an object tree you can expand with all declared objects.

How do I read all classes from a Java package in the classpath?

use dependency maven:

groupId: net.sf.extcos
artifactId: extcos
version: 0.4b

then use this code :

ComponentScanner scanner = new ComponentScanner();
        Set classes = scanner.getClasses(new ComponentQuery() {
            @Override
            protected void query() {
                select().from("com.leyton").returning(allExtending(DynamicForm.class));
            }
        });

What's the difference between JavaScript and Java?

Like everybody's saying, they're pretty much entirely different.

However, if you need a scripting language for your Java application, Javascript is actually a really good choice. There are ways to get Javascript running in the JVM and you can access and manipulate Java classes pretty seamlessly once you do.

The controller for path was not found or does not implement IController

in my case, the problem was that the controller class has not been publicly announced.

class WorkPlaceController : Controller

the solution was

public class WorkPlaceController : Controller

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }

    #endregion

    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
    {
        Binding = new Binding(path);
    }

    public ConverterBindableParameter(Binding binding)
    {
        Binding = binding;
    }

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        multiBinding.Bindings.Add(Binding);
        if (ConverterParameter != null)
        {
            ConverterParameter.Mode = BindingMode.OneWay;
            multiBinding.Bindings.Add(ConverterParameter);
        }
        var adapter = new MultiValueConverterAdapter
        {
            Converter = Converter
        };
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);
    }

    #endregion

    [ContentProperty(nameof(Converter))]
    private class MultiValueConverterAdapter : IMultiValueConverter
    {
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
        }
    }
}

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
    <Setter.Value>
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          
    </Setter.Value>
</Setter>

Which looks almost like your initial proposal.

Media Player called in state 0, error (-38,0)

It was every much frustrated. So, I got solution which works for me.

try {
                        if (mediaPlayer != null) {
                            mediaPlayer.release();
                            mediaPlayer = null;

                        }
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(file.getAbsolutePath());
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mediaPlayer) {
                                mediaPlayer.start();
                                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mediaPlayer) {
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });
                            }
                        });
                        mediaPlayer.prepare();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

Does Python have a ternary conditional operator?

Python has a ternary form for assignments; however there may be even a shorter form that people should be aware of.

It's very common to need to assign to a variable one value or another depending on a condition.

>>> li1 = None
>>> li2 = [1, 2, 3]
>>> 
>>> if li1:
...     a = li1
... else:
...     a = li2
...     
>>> a
[1, 2, 3]

^ This is the long form for doing such assignments.

Below is the ternary form. But this isn't most succinct way - see last example.

>>> a = li1 if li1 else li2
>>> 
>>> a
[1, 2, 3]
>>> 

With Python, you can simply use or for alternative assignments.

>>> a = li1 or li2
>>> 
>>> a
[1, 2, 3]
>>> 

The above works since li1 is None and the interp treats that as False in logic expressions. The interp then moves on and evaluates the second expression, which is not None and it's not an empty list - so it gets assigned to a.

This also works with empty lists. For instance, if you want to assign a whichever list has items.

>>> li1 = []
>>> li2 = [1, 2, 3]
>>> 
>>> a = li1 or li2
>>> 
>>> a
[1, 2, 3]
>>> 

Knowing this, you can simply such assignments whenever you encounter them. This also works with strings and other iterables. You could assign a whichever string isn't empty.

>>> s1 = ''
>>> s2 = 'hello world'
>>> 
>>> a = s1 or s2
>>> 
>>> a
'hello world'
>>> 

I always liked the C ternary syntax, but Python takes it a step further!

I understand that some may say this isn't a good stylistic choice because it relies on mechanics that aren't immediately apparent to all developers. I personally disagree with that viewpoint. Python is a syntax rich language with lots of idiomatic tricks that aren't immediately apparent to the dabler. But the more you learn and understand the mechanics of the underlying system, the more you appreciate it.

Run certain code every n seconds

Save yourself a schizophrenic episode and use the Advanced Python scheduler: http://pythonhosted.org/APScheduler

The code is so simple:

from apscheduler.scheduler import Scheduler

sched = Scheduler()
sched.start()

def some_job():
    print "Every 10 seconds"

sched.add_interval_job(some_job, seconds = 10)

....
sched.shutdown()

How to effectively work with multiple files in Vim

When using multiple files in vim, I use these commands mostly (with ~350 files open):

  • :b <partial filename><tab> (jump to a buffer)
  • :bw (buffer wipe, remove a buffer)
  • :e <file path> (edit, open a new buffer>
  • pltags - enable jumping to subroutine/method definitions

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

It's just common stuff for making cin input work faster.

For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.

The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

Read data from a text file using Java

    File file = new File("Path");

    FileReader reader = new FileReader(file);  

    while((ch=reader.read())!=-1)
    {
        System.out.print((char)ch);
    }

This worked for me

How can I make directory writable?

Execute at Admin privilege using sudo in order to avoid permission denied (Unable to change file mode) error.

sudo chmod 777 <directory location>

How to change workspace and build record Root Directory on Jenkins?

EDIT: Per other comments, the "Advanced..." button appears to have been removed in more recent versions of Jenkins. If your version doesn't have it, see knorx's answer.

I had the same problem, and even after finding this old pull request I still had trouble finding where to specify the Workspace Root Directory or Build Record Root Directory at the system level, versus specifying a custom workspace for each job.

To set these:

  1. Navigate to Jenkins -> Manage Jenkins -> Configure System
  2. Right at the top, under Home directory, click the Advanced... button: advanced button under Home directory
  3. Now the fields for Workspace Root Directory and Build Record Root Directory appear: additional directory options
  4. The information that appears if you click the help bubbles to the left of each option is very instructive. In particular (from the Workspace Root Directory help):

    This value may include the following variables:

    • ${JENKINS_HOME} — Absolute path of the Jenkins home directory
    • ${ITEM_ROOTDIR} — Absolute path of the directory where Jenkins stores the configuration and related metadata for a given job
    • ${ITEM_FULL_NAME} — The full name of a given job, which may be slash-separated, e.g. foo/bar for the job bar in folder foo


    The value should normally include ${ITEM_ROOTDIR} or ${ITEM_FULL_NAME}, otherwise different jobs will end up sharing the same workspace.

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

What are the options for storing hierarchical data in a relational database?

I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:

CREATE FUNCTION nomen_tree() RETURNS trigger
    LANGUAGE plpgsql
    AS $_$
DECLARE
  old_parent INTEGER;
  new_parent INTEGER;
  id_nom INTEGER;
  txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
    IF TG_OP = 'INSERT' THEN
    EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT $1.id,$1.id,0 UNION ALL
      SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
    ELSE                                                           
    -- EXECUTE does not support conditional statements inside
    EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
    IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
      EXECUTE '
      -- prevent cycles in the tree
      UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
        || ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
        || TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
      -- first remove edges between all old parents of node and its descendants
      DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
        (SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
        AND ancestor_id IN
        (SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
      -- then add edges for all new parents ...
      INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT child_id,ancestor_id,d_c+d_a FROM
        (SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
        CROSS JOIN
        (SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.' 
        || TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
    END IF;
  END IF;
  RETURN NULL;
END;
$_$;

Then for each table where I have a hierarchy, I create a trigger

CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');

For populating a closure table from existing hierarchy I use this stored procedure:

CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    EXECUTE 'TRUNCATE ' || tbl_closure || ';
    INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth) 
        WITH RECURSIVE tree AS
      (
        SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
        UNION ALL 
        SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
        JOIN tree ON child_id = ' || fld_parent || '
      )
      SELECT * FROM tree;';
END;
$$;

Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:

-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;

How to delete a localStorage item when the browser window/tab is closed?

should be done like that and not with delete operator:

localStorage.removeItem(key);

JavaScript data grid for millions of rows

I would highly recommend Open rico. It is difficult to implement in the the beginning, but once you grab it you will never look back.

Improve subplot size/spacing with many subplots in matplotlib

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )

The plt.subplots_adjust method:

def subplots_adjust(*args, **kwargs):
    """
    call signature::

      subplots_adjust(left=None, bottom=None, right=None, top=None,
                      wspace=None, hspace=None)

    Tune the subplot layout via the
    :class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
    meanings (and suggested defaults) are::

      left  = 0.125  # the left side of the subplots of the figure
      right = 0.9    # the right side of the subplots of the figure
      bottom = 0.1   # the bottom of the subplots of the figure
      top = 0.9      # the top of the subplots of the figure
      wspace = 0.2   # the amount of width reserved for blank space between subplots
      hspace = 0.2   # the amount of height reserved for white space between subplots

    The actual defaults are controlled by the rc file
    """
    fig = gcf()
    fig.subplots_adjust(*args, **kwargs)
    draw_if_interactive()

or

fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )

The size of the picture matters.

"I've tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem."

Thus to make more white space and keep the sub plot size the total image needs to be bigger.

What is the use of <<<EOD in PHP?

there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings

you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.

nowdoc strings will not expand variables just like single quotes.

ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

How do you send a Firebase Notification to all devices via CURL?

EDIT: It appears that this method is not supported anymore (thx to @FernandoZamperin). Please take a look at the other answers!

Instead of subscribing to a topic you could instead make use of the condition key and send messages to instances, that are not in a group. Your data might look something like this:

{
    "data": {
        "foo": "bar"
    },
    "condition": "!('anytopicyoudontwanttouse' in topics)"
}

See https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics_2

What is the purpose of the "final" keyword in C++11 for functions?

The final keyword allows you to declare a virtual method, override it N times, and then mandate that 'this can no longer be overridden'. It would be useful in restricting use of your derived class, so that you can say "I know my super class lets you override this, but if you want to derive from me, you can't!".

struct Foo
{
   virtual void DoStuff();
}

struct Bar : public Foo
{
   void DoStuff() final;
}

struct Babar : public Bar
{
   void DoStuff(); // error!
}

As other posters pointed out, it cannot be applied to non-virtual functions.

One purpose of the final keyword is to prevent accidental overriding of a method. In my example, DoStuff() may have been a helper function that the derived class simply needs to rename to get correct behavior. Without final, the error would not be discovered until testing.

javascript: Disable Text Select

Simple Copy this text and put on the before </body>

function disableselect(e) {
  return false
}

function reEnable() {
  return true
}

document.onselectstart = new Function ("return false")

if (window.sidebar) {
  document.onmousedown = disableselect
  document.onclick = reEnable
}

How to debug Javascript with IE 8

I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?


Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:

myLog = function() {

    var _div = null;

    this.toJson = function(obj) {

        if (typeof window.uneval == 'function') { return uneval(obj); }
        if (typeof obj == 'object') {
            if (!obj) { return 'null'; }
            var list = [];
            if (obj instanceof Array) {
                    for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
                    return '[' + list.join(',') + ']';
            } else {
                    for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
                    return '{' + list.join(',') + '}';
            }
        } else if (typeof obj == 'string') {
            return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
        } else {
            return new String(obj);
        }

    };

    this.createDiv = function() {

        myLog._div = document.body.appendChild(document.createElement('div'));

        var props = {
            position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
            color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
            fontSize: '11px', whiteSpace: 'nowrap'
        }

        for (var key in props) { myLog._div.style[key] = props[key]; }

    };


    if (!myLog._div) { this.createDiv(); }

    var logEntry = document.createElement('span');

    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
    }

    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);

    // Scroll automatically to the bottom
    myLog._div.scrollTop = myLog._div.scrollHeight;

}

How to copy marked text in notepad++

This is similar to https://superuser.com/questions/477628/export-all-regular-expression-matches-in-textpad-or-notepad-as-a-list.

I hope you are trying to extract :
"Performance"
"Maintenance"
"System Stability"

Here is the way - Step 1/3: Open Search->Find->Replace Tab , select Regular Expression Radio button. Enter in Find what : (\"[a-zA-Z0-9\s]+\") and in Replace with : \n\1 and click Replace All buttton. Before Clicking Replace All

Step 2/3: After first step your keywords will be in next lines.(as shown in next image). Now go to Mark tab and enter the same regex expression in Find what: Field. Put check mark on Bookmark Line. Then Click Mark All. Bookmark the lines

Step 3/3 : Goto Search -> Bookmarks -> Remove unmarked lines.Remove Unmarked lines

So you have the final result as belowFinal Result

Initialize array of strings

Its fine to just do char **strings;, char **strings = NULL, or char **strings = {NULL}

but to initialize it you'd have to use malloc:

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

int main(){
    // allocate space for 5 pointers to strings
    char **strings = (char**)malloc(5*sizeof(char*));
    int i = 0;
    //allocate space for each string
    // here allocate 50 bytes, which is more than enough for the strings
    for(i = 0; i < 5; i++){
        printf("%d\n", i);
        strings[i] = (char*)malloc(50*sizeof(char));
    }
    //assign them all something
    sprintf(strings[0], "bird goes tweet");
    sprintf(strings[1], "mouse goes squeak");
    sprintf(strings[2], "cow goes moo");
    sprintf(strings[3], "frog goes croak");
    sprintf(strings[4], "what does the fox say?");
    // Print it out
    for(i = 0; i < 5; i++){
        printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
    } 
    //Free each string
    for(i = 0; i < 5; i++){
        free(strings[i]);
    }
    //finally release the first string
    free(strings);
    return 0;
}

How do I subscribe to all topics of a MQTT broker

Subscribing to # gives you a subscription to everything except for topics that start with a $ (these are normally control topics anyway).

It is better to know what you are subscribing to first though, of course, and note that some broker configurations may disallow subscribing to # explicitly.

How to annotate MYSQL autoincrement field with JPA annotations

To use a MySQL AUTO_INCREMENT column, you are supposed to use an IDENTITY strategy:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

Which is what you'd get when using AUTO with MySQL:

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

Which is actually equivalent to

@Id @GeneratedValue
private Long id;

In other words, your mapping should work. But Hibernate should omit the id column in the SQL insert statement, and it is not. There must be a kind of mismatch somewhere.

Did you specify a MySQL dialect in your Hibernate configuration (probably MySQL5InnoDBDialect or MySQL5Dialect depending on the engine you're using)?

Also, who created the table? Can you show the corresponding DDL?

Follow-up: I can't reproduce your problem. Using the code of your entity and your DDL, Hibernate generates the following (expected) SQL with MySQL:

insert 
into
    Operator
    (active, password, username) 
values
    (?, ?, ?)

Note that the id column is absent from the above statement, as expected.

To sum up, your code, the table definition and the dialect are correct and coherent, it should work. If it doesn't for you, maybe something is out of sync (do a clean build, double check the build directory, etc) or something else is just wrong (check the logs for anything suspicious).

Regarding the dialect, the only difference between MySQL5Dialect or MySQL5InnoDBDialect is that the later adds ENGINE=InnoDB to the table objects when generating the DDL. Using one or the other doesn't change the generated SQL.

Turn off iPhone/Safari input element rounding

In order to render the buttons properly on Safari and other browsers, you'll need to give a specific style for the buttons in addition to setting webkit-appearance to none, e.g.:

border-radius: 0;
-webkit-appearance: none;
background-image: linear-gradient(to bottom, #e4e4e4, #f7f7f7);
border: 1px solid #afafaf

Escaping special characters in Java Regular Expressions

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

Array Length in Java

To find length of an array A you should use the length property. It is as A.length, do not use A.length() its mainly used for size of string related objects.

enter image description here

The length property will always show the total allocated space to the array during initialization.

If you ever have any of these kind of problems the simple way is to run it. Happy Programming!

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

What are the differences between a clustered and a non-clustered index?

Pros:

Clustered indexes work great for ranges (e.g. select * from my_table where my_key between @min and @max)

In some conditions, the DBMS will not have to do work to sort if you use an orderby statement.

Cons:

Clustered indexes are can slow down inserts because the physical layouts of the records have to be modified as records are put in if the new keys are not in sequential order.

How to change Vagrant 'default' machine name?

This is the way I've assigned names to individual VMs. Change YOURNAMEHERE to your desired name.

Contents of Vagrantfile:

Vagrant.configure("2") do |config|

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "precise32"

  # The url from where the 'config.vm.box' box will be fetched if it
  # doesn't already exist on the user's system.
  config.vm.box_url = "http://files.vagrantup.com/precise32.box"

  config.vm.define :YOURNAMEHERE do |t|
  end

end

Terminal output:

$ vagrant status
Current machine states:

YOURNAMEHERE             not created (virtualbox)

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

Convert int to char in java

My answer is similar to jh314's answer but I'll explain a little deeper.

What you should do in this case is:

int a = 1;
char b = (char)(a + '0');
System.out.println(b);

Here, we used '0' because chars are actually represented by ASCII values. '0' is a char and represented by the value of 48.

We typed (a + '0') and in order to add these up, Java converted '0' to its ASCII value which is 48 and a is 1 so the sum is 49. Then what we did is:

(char)(49)

We casted int to char. ASCII equivalent of 49 is '1'. You can convert any digit to char this way and is smarter and better way than using .toString() method and then subtracting the digit by .charAt() method.

select unique rows based on single distinct column

Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try

;WITH ue(id)
 AS
 (
   SELECT MAX(id)
   FROM table
   GROUP BY email
 )
 SELECT * FROM table t
 INNER JOIN ue ON ue.id = t.id

Xcode 10, Command CodeSign failed with a nonzero exit code

In my case, some special marks in the png files output by Paint.app causes this happen.

I try all answers, but none works for me.

My solution is

step 1. drag the png files(if you do not know which png, please drag all png files in your project resource folder/group) caused the error happens to Preview.app

enter image description here

step 2. adjust image size,

enter image description here

step 3. enlarge 2 times for width and height, click 'Ok' button

enter image description here

step 4. set back to original width and height, click 'Ok' button

enter image description here

step 5. repeat step 3 and step 4 for all png images

step 6. clean project and build again

Done! good luck

How do you update a DateTime field in T-SQL?

Is there maybe a trigger on the table setting it back?

How to parse JSON in Java

jsoniter (jsoniterator) is a relatively new and simple json library, designed to be simple and fast. All you need to do to deserialize json data is

JsonIterator.deserialize(jsonData, int[].class);

where jsonData is a string of json data.

Check out the official website for more information.

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

My fix was to create Platform in configuration manager in visual studio, and set to x64

How to save CSS changes of Styles panel of Chrome Developer Tools?

To answer the last part of your question about any extensions that can save changes, there is hotfix

It allows you to save changes from Chrome Dev Tools directly to GitHub. From there you can set up a post-receive hook on GitHub to automatically update your website.

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Use the Post/Redirect/Get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get

With my website, I will store a message in a cookie or session, redirect after the post, read the cookie/session, and then clear the value of that session or cookie variable.

How can you integrate a custom file browser/uploader with CKEditor?

Start by registering your custom browser/uploader when you instantiate CKEditor. You can designate different URLs for an image browser vs. a general file browser.

<script type="text/javascript">
CKEDITOR.replace('content', {
    filebrowserBrowseUrl : '/browser/browse/type/all',
    filebrowserUploadUrl : '/browser/upload/type/all',
    filebrowserImageBrowseUrl : '/browser/browse/type/image',
filebrowserImageUploadUrl : '/browser/upload/type/image',
    filebrowserWindowWidth  : 800,
    filebrowserWindowHeight : 500
});
</script>

Your custom code will receive a GET parameter called CKEditorFuncNum. Save it - that's your callback function. Let's say you put it into $callback.

When someone selects a file, run this JavaScript to inform CKEditor which file was selected:

window.opener.CKEDITOR.tools.callFunction(<?php echo $callback; ?>,url)

Where "url" is the URL of the file they picked. An optional third parameter can be text that you want displayed in a standard alert dialog, such as "illegal file" or something. Set url to an empty string if the third parameter is an error message.

CKEditor's "upload" tab will submit a file in the field "upload" - in PHP, that goes to $_FILES['upload']. What CKEditor wants your server to output is a complete JavaScript block:

$output = '<html><body><script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$url.'","'.$msg.'");</script></body></html>';
echo $output;

Again, you need to give it that callback parameter, the URL of the file, and optionally a message. If the message is an empty string, nothing will display; if the message is an error, then url should be an empty string.

The official CKEditor documentation is incomplete on all this, but if you follow the above it'll work like a champ.

Bootstrap modal appearing under background

Add this to your style sheet:

.modal-backdrop {
    background-color: #000;
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
    z-index: 0 !important;
}

Importing text file into excel sheet

I think my answer to my own question here is the simplest solution to what you are trying to do:

  1. Select the cell where the first line of text from the file should be.

  2. Use the Data/Get External Data/From File dialog to select the text file to import.

  3. Format the imported text as required.

  4. In the Import Data dialog that opens, click on Properties...

  5. Uncheck the Prompt for file name on refresh box.

  6. Whenever the external file changes, click the Data/Get External Data/Refresh All button.

Note: in your case, you should probably want to skip step #5.

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

Converting Integer to Long

If the Integer is not null

Integer i;
Long long = Long.valueOf(i);

i will be automatically typecast to a long.

Using valueOf instead of new allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.

How do I make a transparent canvas in html5?

Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:

#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas

I'm not sure but it looks like that the background-color is inherited as transparent from the body.

Cannot GET / Nodejs Error

I think you're missing your routes, you need to define at least one route for example '/' to index.

e.g.

app.get('/', function (req, res) {
  res.render('index', {});
});

How do I capture response of form.submit

You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the submit() function doesn't actually return anything, it just sends the form data to the server.

If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll need to use a library. jQuery is by far the most popular, and my personal favourite. There's a great plugin for jQuery called Form which will do exactly what it sounds like you want.

Here's how you'd use jQuery and that plugin:

$('#myForm')
    .ajaxForm({
        url : 'myscript.php', // or whatever
        dataType : 'json',
        success : function (response) {
            alert("The server says: " + response);
        }
    })
;

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

SQLite Query in Android to count rows

Another way would be using:

myCursor.getCount();

on a Cursor like:

Cursor myCursor = db.query(table_Name, new String[] { row_Username }, 
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password }, 
null, null, null);

If you can think of getting away from the raw query.

How to update the value of a key in a dictionary in Python?

n = eval(input('Num books: '))
books = {}
for i in range(n):
    titlez = input("Enter Title: ")
    copy = eval(input("Num of copies: "))
    books[titlez] = copy

prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
    choice = input('Enter book title: ')
    if choice in books:
        init_num = books[choice]
        init_num -= 1
        books[choice] = init_num
        print(books)

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

undefined reference to boost::system::system_category() when compiling

The above error is a linker error... the linker a program that takes one or more objects generated by a compiler and combines them into a single executable program.

You must add -lboost_system to you linker flags which indicates to the linker that it must look for symbols like boost::system::system_category() in the library libboost_system.so.

If you have main.cpp, either:

g++ main.cpp -o main -lboost_system

OR

g++ -c -o main.o main.cpp
g++ main.o -lboost_system

What do I use for a max-heap implementation in Python?

This is a simple MaxHeap implementation based on heapq. Though it only works with numeric values.

import heapq
from typing import List


class MaxHeap:
    def __init__(self):
        self.data = []

    def top(self):
        return -self.data[0]

    def push(self, val):
        heapq.heappush(self.data, -val)

    def pop(self):
        return -heapq.heappop(self.data)

Usage:

max_heap = MaxHeap()
max_heap.push(3)
max_heap.push(5)
max_heap.push(1)
print(max_heap.top())  # 5

adding css file with jquery

This is how I add css using jQuery ajax. Hope it helps someone..

$.ajax({
            url:"site/test/style.css",
            success:function(data){
                 $("<style></style>").appendTo("head").html(data);
            }
        })

Angular - Use pipes in services and components

If you don't want do 'new myPipe()' because you're injecting dependencies to pipe, you can inject in component like provider and use without new.

Example:

    // In your component...

    import { Component, OnInit } from '@angular/core';
    import { myPipe} from './pipes';

    @Component({
      selector: 'my-component',
      template: '{{ data }}',
      providers: [ myPipe ]
    })
    export class MyComponent() implements OnInit {
      data = 'some data';
      constructor(private myPipe: myPipe) {}

      ngOnInit() {
        this.data = this.myPipe.transform(this.data);
      }
    }

Merge trunk to branch in Subversion

It is “old-fashioned” way to specify ranges of revisions you wish to merge. With 1.5+ you can use:

svn merge HEAD url/of/trunk path/to/branch/wc

Validate SSL certificates with Python

pyOpenSSL is an interface to the OpenSSL library. It should provide everything you need.

Can't update data-attribute value

I had the same problem of the html data tag not updating when i was using jquery But changing the code that does the actual work from jquery to javascript worked.

Try using this when the button is clicked: (Note that the main code is Javascripts setAttribute() function.)

function increment(q) {

    //increment current num by adding with 1
    q = q+1;

    //change data attribute using JS setAttribute function
    div.setAttribute('data-num',q);

    //refresh data-num value (get data-num value again using JS getAttribute function)
    num = parseInt(div.getAttribute('data-num'));

    //show values
    console.log("(After Increment) Current Num: "+num);

}

//get variables, set as global vars
var div = document.getElementById('foo');
var num = parseInt(div.getAttribute('data-num'));

//increment values using click
$("#changeData").on('click',function(){

    //pass current data-num as parameter
    increment(num);

});

what happens when you type in a URL in browser

Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/

Install Qt on Ubuntu

Install Qt

sudo apt-get install build-essential

sudo apt-get install qtcreator

sudo apt-get install qt5-default

Install documentation and examples If Qt Creator is installed thanks to the Ubuntu Sofware Center or thanks to the synaptic package manager, documentation for Qt Creator is not installed. Hitting the F1 key will show you the following message : "No documentation available". This can easily be solved by installing the Qt documentation:

sudo apt-get install qt5-doc

sudo apt-get install qt5-doc-html qtbase5-doc-html

sudo apt-get install qtbase5-examples

Restart Qt Creator to make the documentation available.

Error while loading shared libraries

Problem:

radiusd: error while loading shared libraries: libfreeradius-radius-2.1.10.so: cannot open shared object file: No such file or directory

Reason:

Actually, the libraries have been installed in a place where dynamic linker cannot find it.

Solution:

While this is not a guarantee but using the following command may help you solve the “cannot open shared object file” error:

sudo /sbin/ldconfig -v

http://www.lucidarme.me/how-install-documentation-for-qt-creator/

https://ubuntuforums.org/showthread.php?t=2199929

https://itsfoss.com/error-while-loading-shared-libraries/

ModelSim-Altera error

Cannot open output file, permission denied

Try restarting your IDE. It worked for me. Although I tried to end the process in the task manager, the process never got killed.

Java equivalent to #region in C#

Jet Brains IDEA has this feature. You can use hotkey surround with for that (ctrl + alt + T). It's just IDEA feature.

Regions there look like this:

//region Description

Some code

//endregion

sending email via php mail function goes to spam

What we usually do with e-mail, preventing spam-folders as the end destination, is using either Gmail as the smtp server or Mandrill as the smtp server.

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

From commons-lang3

org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)

MySql export schema without data

You can use the -d option with mysqldump command

mysqldump -u root -p -d databasename > database.sql

Append text to input field

_x000D_
_x000D_
 // Define appendVal by extending JQuery_x000D_
 $.fn.appendVal = function( TextToAppend ) {_x000D_
  return $(this).val(_x000D_
   $(this).val() + TextToAppend_x000D_
  );_x000D_
 };_x000D_
//______________________________________________x000D_
_x000D_
 // And that's how to use it:_x000D_
 $('#SomeID')_x000D_
  .appendVal( 'This text was just added' )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<textarea _x000D_
          id    =  "SomeID"_x000D_
          value =  "ValueText"_x000D_
          type  =  "text"_x000D_
>Current NodeText_x000D_
</textarea>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

Well when creating this example I somehow got a little confused. "ValueText" vs >Current NodeText< Isn't .val() supposed to run on the data of the value attribute? Anyway I and you me may clear up this sooner or later.

However the point for now is:

When working with form data use .val().

When dealing with the mostly read only data in between the tag use .text() or .append() to append text.

How to enable zoom controls and pinch zoom in a WebView?

Try this code, I get working fine.

 webSettings.setSupportZoom(true);
 webSettings.setBuiltInZoomControls(true);
 webSettings.setDisplayZoomControls(false);

jQuery If DIV Doesn't Have Class "x"

jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class

if (!$(this).hasClass("selected")) {
    //do stuff
}

Take a look at my example of use

  • If you hover over a div, it fades as normal speed to 100% opacity if the div does not contain the 'selected' class
  • If you hover out of a div, it fades at slow speed to 30% opacity if the div does not contain the 'selected' class
  • Clicking the button adds 'selected' class to the red div. The fading effects no longer work on the red div

Here is the code for it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>


<!-- jQuery code here -->
<script type="text/javascript">
$(function() {

$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});

$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );

$('.thumbs').hover(fadeItIn, fadeItOut);


});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}
</script>


</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>

EDIT:

this is just a guess, but are you trying to achieve something like this?

  • Both divs start at 30% opacity
  • Hovering over a div fades to 100% opacity, hovering out fades back to 30% opacity. Fade effects only work on elements that don't have the 'selected' class
  • Clicking a div adds/removes the 'selected' class

jQuery Code is here-

$(function() {

$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);

});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}

<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>

What does '<?=' mean in PHP?

It's a shorthand for <?php echo $a; ?>.

It's enabled by default since 5.4 regardless of php.ini settings.

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I was facing same error with Django Rest Framework, It was nothing to do with UI, still was getting this error. I applied below solution, worked for me.

  • Restarted Machine.
  • Restarted Virtual Environment.

Why is there no xrange function in Python3?

One way to fix up your python2 code is:

import sys

if sys.version_info >= (3, 0):
    def xrange(*args, **kwargs):
        return iter(range(*args, **kwargs))

SQL Server - SELECT FROM stored procedure

You can use a User-defined function or a view instead of a procedure.

A procedure can return multiple result sets, each with its own schema. It's not suitable for using in a SELECT statement.

How to sort an array of objects in Java?

Sometimes you want to sort an array of objects on an arbitrary value. Since compareTo() always uses the same information about the instance, you might want to use a different technique. One way is to use a standard sorting algorithm. Let's say you have an array of books and you want to sort them on their height, which is stored as an int and accessible through the method getHeight(). Here's how you could sort the books in your array. (If you don't want to change the original array, simply make a copy and sort that.)

`int tallest; // the index of tallest book found thus far
 Book temp; // used in the swap
 for(int a = 0; a < booksArray.length - 1; a++) {
   tallest = a; // reset tallest to current index
   // start inner loop at next index
   for(int b = a + 1; b < booksArray.length; b++)
     // check if the book at this index is taller than the
     // tallest found thus far
     if(booksArray[b].getHeight() > booksArray[tallest].getHeight())
       tallest = b;
   // once inner loop is complete, swap the tallest book found with
   // the one at the current index of the outer loop
   temp = booksArray[a];
   booksArray[a] = booksArray[tallest];
   booksArray[tallest] = temp;
 }`

When this code is done, the array of Book object will be sorted by height in descending order--an interior designer's dream!

Get current clipboard content?

You can use

window.clipboardData.getData('Text')

to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard

Bootstrap - How to add a logo to navbar class?

Use a image style width and height 100% . This will do the trick, because the image can be resized based on the container.

Example:

<a class="navbar-brand" href="#" style="padding: 4px;margin:auto"> <img src="images/logo.png" style="height:100%;width: auto;" title="mycompanylogo"></a>

How do I create a file AND any folders, if the folders don't exist?

Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions Sample code:

FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
    f2.Demand();
}
catch (SecurityException s)
{
    Console.WriteLine(s.Message);
}

Understanding .NET Code Access Security

Is “Code Access Security” of any real world use?

Exit from app when click button in android phonegap?

Try this code.

<!DOCTYPE HTML>
<html>
  <head>
    <title>PhoneGap</title>

        <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>      
        <script type="text/javascript" charset="utf-8">

            function onLoad()
            {
                  document.addEventListener("deviceready", onDeviceReady, true);
            }

            function exitFromApp()
             {
                navigator.app.exitApp();
             }

        </script>

    </head>

    <body onload="onLoad();">
       <button name="buttonClick" onclick="exitFromApp()">Click Me!</button>
    </body>
</html>

Replace src="cordova-1.5.0.js" with your phonegap js .

Left padding a String with Zeros

An old question, but I also have two methods.


For a fixed (predefined) length:

    public static String fill(String text) {
        if (text.length() >= 10)
            return text;
        else
            return "0000000000".substring(text.length()) + text;
    }

For a variable length:

    public static String fill(String text, int size) {
        StringBuilder builder = new StringBuilder(text);
        while (builder.length() < size) {
            builder.append('0');
        }
        return builder.toString();
    }

jQuery map vs. each

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

Another important thing to note is that the each function returns the original array while the map function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});
// newItems is [2,3,4,5]

You can also use the map function to remove an item from an array. For example:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5) 
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]

You'll also note that the this is not mapped in the map function. You will have to supply the first parameter in the callback (eg we used i above). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.

map(arr, function(elem, index) {});
// versus 
each(arr, function(index, elem) {});

Javascript/jQuery detect if input is focused

With pure javascript:

this === document.activeElement // where 'this' is a dom object

or with jquery's :focus pseudo selector.

$(this).is(':focus');

What is an index in SQL?

INDEXES - to find data easily

UNIQUE INDEX - duplicate values are not allowed

Syntax for INDEX

CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);

Syntax for UNIQUE INDEX

CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);

Variable not accessible when initialized outside function

Declare systemStatus in an outer scope and assign it in an onload handler.

systemStatus = null;

function onloadHandler(evt) {
    systemStatus = document.getElementById("....");
}

Or if you don't want the onload handler, put your script tag at the bottom of your HTML.

How do I set a VB.Net ComboBox default value

because you have set index is 0 it shows always 1st value from combobox as input.

Try this :

With Me.ComboBox1
    .DropDownStyle = ComboBoxStyle.DropDown
    .Text = " "
End With

How to set a CheckBox by default Checked in ASP.Net MVC

An alternative solution is using jQuery:

    <script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            PrepareCheckbox();
        });
        function PrepareCheckbox(){
            document.getElementById("checkbox").checked = true;
        }
    </script>

String.equals versus ==

The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.

AttributeError: 'module' object has no attribute 'urlretrieve'

A Python 2+3 compatible solution is:

import sys

if sys.version_info[0] >= 3:
    from urllib.request import urlretrieve
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlretrieve

# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")

How can I get a JavaScript stack trace when I throw an exception?

at least in Edge 2021 :

console.groupCollapsed('jjjjjjjjjjjjjjjjj')
    console.trace()
    try {
        throw "kuku"
    } catch(e) {
        console.log(e.stack)
    }
console.groupEnd()
traceUntillMe()

and you are done my friend

How do I programmatically click a link with javascript?

For me, I managed to make it work that way. I deployed the automatic click in 5000 milliseconds and then closed the loop after 1000 milliseconds. Then there was only 1 automatic click.

<script> var myVar = setInterval(function ({document.getElementById("test").click();}, 500)); setInterval(function () {clearInterval(myVar)}, 1000));</script>

How to select a value in dropdown javascript?

function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

Where s is the dropdown and v is the value

How to extract Month from date in R

Without the need of an external package:

if your date is in the following format:

myDate = as.POSIXct("2013-01-01")

Then to get the month number:

format(myDate,"%m")

And to get the month string:

format(myDate,"%B")

Xcode - Warning: Implicit declaration of function is invalid in C99

The compiler wants to know the function before it can use it

just declare the function before you call it

#include <stdio.h>

int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now

int main(int argc, const char * argv[])
{
    int input;
    printf("Please give me a number : ");
    scanf("%d", &input);
    getchar();
    printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!

}/* main */

int Fibonacci(int number)
{
//…

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I faced a similar issue during work with Ubuntu 16.04 by using Docker. In my case that was a problem with Composer, but error message (and thus the problem) was the same.

Because of minimalist Docker-oriented base image I had missing ca-certificates package and simple apt-get install ca-certificates helped me.

Why does visual studio 2012 not find my tests?

For Me the solution was just a little bit less complicated.

I had just brought an existing solution on to my machine (cloned from gitHub) and we do not track the auto-generated .cs files that Visual Studio created. (For each feature file there is a .cs file with the same name)

Opening the solution without having the associated .cs files actually allow me to navigate to the bound methods, so it appeared as if specflow was wired up properly, but I was not able to view the test names in the Test Explorer.

For this problem simply excluding the feature files from the project and then re-including them, forced VS to regenerate these auto generated codebehind files.

After that, I was able to view the tests in the test explorer.

Determine the data types of a data frame's columns

Since it wasn't stated clearly, I just add this:

I was looking for a way to create a table which holds the number of occurrences of all the data types.

Say we have a data.frame with two numeric and one logical column

dta <- data.frame(a = c(1,2,3), 
                  b = c(4,5,6), 
                  c = c(TRUE, FALSE, TRUE))

You can summarize the number of columns of each data type with that

table(unlist(lapply(dta, class)))
# logical numeric 
#       1       2 

This comes extremely handy, if you have a lot of columns and want to get a quick overview.

To give credit: This solution was inspired by the answer of @Cybernetic.

Disable arrow key scrolling in users browser

Summary

Simply prevent the default browser action:

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
        e.preventDefault();
    }
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated.

Original answer

I used the following function in my own game:

var keys = {};
window.addEventListener("keydown",
    function(e){
        keys[e.code] = true;
        switch(e.code){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    },
false);
window.addEventListener('keyup',
    function(e){
        keys[e.code] = false;
    },
false);

The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

var arrow_keys_handler = function(e) {
    switch(e.code){
        case 37: case 39: case 38:  case 40: // Arrow keys
        case 32: e.preventDefault(); break; // Space
        default: break; // do not block other keys
    }
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

window.removeEventListener("keydown", arrow_keys_handler, false);

References