Programs & Examples On #Windows media player

Windows Media Player (abbreviated WMP) is a media player and media library application developed by Microsoft that is used for playing audio, video and viewing images on personal computers running the Microsoft Windows operating system, as well as on Pocket PC and Windows Mobile-based devices. Editions of Windows Media Player were also released for Mac OS, Mac OS X and Solaris but development of these has since been discontinued.

How do I make this file.sh executable via double click?

Remove the extension altogether and then double-click it. Most system shell scripts are like this. As long as it has a shebang it will work.

PHP: Split a string in to an array foreach char

you can convert a string to array with str_split and use foreach

$chars = str_split($str);
foreach($chars as $char){
    // your code
}

Scrolling to element using webdriver?

Example:

driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))

This one always works for me for any type of selectors. There is also the Actions class, but for this case, it is not so reliable.

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

The performance impact of using instanceof in Java

InstanceOf is a warning of poor Object Oriented design.

Current JVMs do mean the instanceOf is not much of a performance worry in itself. If you are finding yourself using it a lot, especially for core functionality, it is probably time to look at the design. The performance (and simplicity/maintainability) gains of refactoring to a better design will greatly outweigh any actual processor cycles spent on the actual instanceOf call.

To give a very small simplistic programming example.

if (SomeObject instanceOf Integer) {
  [do something]
}
if (SomeObject instanceOf Double) {
  [do something different]
}

Is a poor architecture a better choice would have been to have SomeObject be the parent class of two child classes where each child class overrides a method (doSomething) so the code would look as such:

Someobject.doSomething();

Remove a fixed prefix/suffix from a string in Bash

Using the =~ operator:

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor

How do I turn a String into a InputStreamReader in java?

Same question as @Dan - why not StringReader ?

If it has to be InputStreamReader, then:

String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I would try to connect to your Sharepoint site with this tool here. If that works you can be sure that the problem is in your code / configuration. That maybe does not solve your problem immediately but it rules out that there is something wrong with the server. Assuming that it does not work I would investigate the following:

  • Does your user really have enough rights on the site?
  • Is there a proxy that interferes? (Your configuration looks a bit like there is a proxy. Can you bypass it?)

I think there is nothing wrong with using security mode Transport, but I am not so sure about the proxyCredentialType="Ntlm", maybe this should be set to None.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

select right(rtrim('94342KMR'),3)

This will fetch the last 3 right string.

select substring(rtrim('94342KMR'),1,len('94342KMR')-3)

This will fetch the remaining Characters.

Pipe subprocess standard output to a variable

To get the output of ls, use stdout=subprocess.PIPE.

>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo

The command cdrecord --help outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.

>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

As mentioned by Chris Morgan, you should be using proc.communicate() instead of proc.read().

>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout: 
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

Inline labels in Matplotlib

Nice question, a while ago I've experimented a bit with this, but haven't used it a lot because it's still not bulletproof. I divided the plot area into a 32x32 grid and calculated a 'potential field' for the best position of a label for each line according the following rules:

  • white space is a good place for a label
  • Label should be near corresponding line
  • Label should be away from the other lines

The code was something like this:

import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage


def my_legend(axis = None):

    if axis == None:
        axis = plt.gca()

    N = 32
    Nlines = len(axis.lines)
    print Nlines

    xmin, xmax = axis.get_xlim()
    ymin, ymax = axis.get_ylim()

    # the 'point of presence' matrix
    pop = np.zeros((Nlines, N, N), dtype=np.float)    

    for l in range(Nlines):
        # get xy data and scale it to the NxN squares
        xy = axis.lines[l].get_xydata()
        xy = (xy - [xmin,ymin]) / ([xmax-xmin, ymax-ymin]) * N
        xy = xy.astype(np.int32)
        # mask stuff outside plot        
        mask = (xy[:,0] >= 0) & (xy[:,0] < N) & (xy[:,1] >= 0) & (xy[:,1] < N)
        xy = xy[mask]
        # add to pop
        for p in xy:
            pop[l][tuple(p)] = 1.0

    # find whitespace, nice place for labels
    ws = 1.0 - (np.sum(pop, axis=0) > 0) * 1.0 
    # don't use the borders
    ws[:,0]   = 0
    ws[:,N-1] = 0
    ws[0,:]   = 0  
    ws[N-1,:] = 0  

    # blur the pop's
    for l in range(Nlines):
        pop[l] = ndimage.gaussian_filter(pop[l], sigma=N/5)

    for l in range(Nlines):
        # positive weights for current line, negative weight for others....
        w = -0.3 * np.ones(Nlines, dtype=np.float)
        w[l] = 0.5

        # calculate a field         
        p = ws + np.sum(w[:, np.newaxis, np.newaxis] * pop, axis=0)
        plt.figure()
        plt.imshow(p, interpolation='nearest')
        plt.title(axis.lines[l].get_label())

        pos = np.argmax(p)  # note, argmax flattens the array first 
        best_x, best_y =  (pos / N, pos % N) 
        x = xmin + (xmax-xmin) * best_x / N       
        y = ymin + (ymax-ymin) * best_y / N       


        axis.text(x, y, axis.lines[l].get_label(), 
                  horizontalalignment='center',
                  verticalalignment='center')


plt.close('all')

x = np.linspace(0, 1, 101)
y1 = np.sin(x * np.pi / 2)
y2 = np.cos(x * np.pi / 2)
y3 = x * x
plt.plot(x, y1, 'b', label='blue')
plt.plot(x, y2, 'r', label='red')
plt.plot(x, y3, 'g', label='green')
my_legend()
plt.show()

And the resulting plot: enter image description here

Navigation Controller Push View Controller

Using this code for Navigating next viewcontroller,if you are using storyboard means follow this below code,

UIStoryboard *board;

if (!self.storyboard)
{
    board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
}
else
{
    board = self.storyboard;
}

ViewController *View = [board instantiateViewControllerWithIdentifier:@"yourstoryboardname"];
[self.navigationController pushViewController:View animated:YES];

Smooth scroll to specific div on click

I played around with nico's answer a little and it felt jumpy. Did a bit of investigation and found window.requestAnimationFrame which is a function that is called on each repaint cycle. This allows for a more clean-looking animation. Still trying to hone in on good default values for step size but for my example things look pretty good using this implementation.

var smoothScroll = function(elementId) {
    var MIN_PIXELS_PER_STEP = 16;
    var MAX_SCROLL_STEPS = 30;
    var target = document.getElementById(elementId);
    var scrollContainer = target;
    do {
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do {
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
                                 (targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);

    var stepFunc = function() {
        scrollContainer.scrollTop =
            Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);

        if (scrollContainer.scrollTop >= targetY) {
            return;
        }

        window.requestAnimationFrame(stepFunc);
    };

    window.requestAnimationFrame(stepFunc);
}

Map over object preserving keys

You can use _.mapValues(users, function(o) { return o.age; }); in Lodash and _.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; }); in Underscore.

Check out the cross-documentation here: http://jonathanpchen.com/underdash-api/#mapvalues-object-iteratee-identity

Passing javascript variable to html textbox

<form name="input" action="some.php" method="post">
 <input type="text" name="user" id="mytext">
 <input type="submit" value="Submit">
</form>

<script>
  var w = someValue;
document.getElementById("mytext").value = w;

</script>

//php on some.php page

echo $_POST['user'];

How to style HTML5 range input to have different color before and after slider?

While the accepted answer is good in theory, it ignores the fact that the thumb then cannot be bigger than size of the track without being chopped off by the overflow: hidden. See this example of how to handle this with just a tiny bit of JS.

_x000D_
_x000D_
// .chrome styling Vanilla JS

document.getElementById("myinput").oninput = function() {
  var value = (this.value-this.min)/(this.max-this.min)*100
  this.style.background = 'linear-gradient(to right, #82CFD0 0%, #82CFD0 ' + value + '%, #fff ' + value + '%, white 100%)'
};
_x000D_
#myinput {
  background: linear-gradient(to right, #82CFD0 0%, #82CFD0 50%, #fff 50%, #fff 100%);
  border: solid 1px #82CFD0;
  border-radius: 8px;
  height: 7px;
  width: 356px;
  outline: none;
  transition: background 450ms ease-in;
  -webkit-appearance: none;
}
_x000D_
<div class="chrome">
  <input id="myinput" min="0" max="60" type="range" value="30" />
</div>
_x000D_
_x000D_
_x000D_

C++, What does the colon after a constructor mean?

It's called an initialization list. It initializes members before the body of the constructor executes.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Submit HTML form on self page

You can leave action attribute blank. The form will automatically submit itself in the same page.

<form action="">

According to the w3c specification, action attribute must be non-empty valid url in general. There is also an explanation for some situations in which the action attribute may be left empty.

The action of an element is the value of the element’s formaction attribute, if the element is a Submit Button and has such an attribute, or the value of its form owner’s action attribute, if it has one, or else the empty string.

So they both still valid and works:

<form action="">
<form action="FULL_URL_STRING_OF_CURRENT_PAGE">

If you are sure your audience is using html5 browsers, you can even omit the action attribute:

<form>

How to echo out table rows from the db (php)

$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
    echo "<tr>";
    foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
        echo "<td>" . $value . "</td>"; 
    }
    echo "</tr>";
}
echo "</table>";

In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.

javax.faces.application.ViewExpiredException: View could not be restored

First what you have to do, before changing web.xml is to make sure your ManagedBean implements Serializable:

@ManagedBean
@ViewScoped
public class Login implements Serializable {
}

Especially if you use MyFaces

Downloading an entire S3 bucket?

AWS CLI is the best option to download an entire S3 bucket locally.

  1. Install AWS CLI.

  2. Configure AWS CLI for using default security credentials and default AWS Region.

  3. To download the entire S3 bucket use command

    aws s3 sync s3://yourbucketname localpath

Reference to use AWS cli for different AWS services: https://docs.aws.amazon.com/cli/latest/reference/

Remove empty lines in a text file via grep

If removing empty lines means lines including any spaces, use:

grep '\S' FILE

For example:

$  printf "line1\n\nline2\n \nline3\n\t\nline4\n" > FILE
$  cat -v FILE
line1

line2

line3

line4
$  grep '\S' FILE
line1
line2
line3
line4
$  grep . FILE
line1
line2

line3

line4

See also:

When to use which design pattern?

I completely agree with @Peter Rasmussen.

Design patterns provide general solution to commonly occurring design problem.

I would like you to follow below approach.

  1. Understand intent of each pattern
  2. Understand checklist or use case of each pattern
  3. Think of solution to your problem and check if your solution falls into checklist of particular pattern
  4. If not, simply ignore the design-patterns and write your own solution.

Useful links:

sourcemaking : Explains intent, structure and checklist beautifully in multiple languages including C++ and Java

wikipedia : Explains structure, UML diagram and working examples in multiple languages including C# and Java .

Check list and Rules of thumb in each sourcemakding design-pattern provides alram bell you are looking for.

How do I clear a search box with an 'x' in bootstrap 3?

AngularJS / UI-Bootstrap Answer

  • Use Bootstrap's has-feedback class to show an icon inside the input field.
  • Make sure the icon has style="cursor: pointer; pointer-events: all;"
  • Use ng-click to clear the text.

JavaScript (app.js)

var app = angular.module('plunker', ['ui.bootstrap']);

app.controller('MainCtrl', function($scope) {

  $scope.params = {};

  $scope.clearText = function() {
    $scope.params.text = null;
  }

});

HTML (index.html snippet)

      <div class="form-group has-feedback">
        <label>text box</label>
        <input type="text"
               ng-model="params.text"
               class="form-control"
               placeholder="type something here...">
        <span ng-if="params.text"
              ng-click="clearText()"
              class="glyphicon glyphicon-remove form-control-feedback" 
              style="cursor: pointer; pointer-events: all;"
              uib-tooltip="clear">
        </span>
      </div>

Here's the plunker: http://plnkr.co/edit/av9VFw?p=preview

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

Try adding this:

$mail->SMTPAuth   = true;
$mail->SMTPSecure = "tls";

By looking at your debug logs, you can notice that the failing PhpMailer log shows this:

(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)

While your successful PEAR log shows this:

DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead

My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.

How to sum a variable by group

Since dplyr 1.0.0, the across() function could be used:

df %>%
 group_by(Category) %>%
 summarise(across(Frequency, sum))

  Category Frequency
  <chr>        <int>
1 First           30
2 Second           5
3 Third           34

If interested in multiple variables:

df %>%
 group_by(Category) %>%
 summarise(across(c(Frequency, Frequency2), sum))

  Category Frequency Frequency2
  <chr>        <int>      <int>
1 First           30         55
2 Second           5         29
3 Third           34        190

And the selection of variables using select helpers:

df %>%
 group_by(Category) %>%
 summarise(across(starts_with("Freq"), sum))

  Category Frequency Frequency2 Frequency3
  <chr>        <int>      <int>      <dbl>
1 First           30         55        110
2 Second           5         29         58
3 Third           34        190        380

Sample data:

df <- read.table(text = "Category Frequency Frequency2 Frequency3
                 1    First        10         10         20
                 2    First        15         30         60
                 3    First         5         15         30
                 4   Second         2          8         16
                 5    Third        14         70        140
                 6    Third        20        120        240
                 7   Second         3         21         42",
                 header = TRUE,
                 stringsAsFactors = FALSE)

How to perform mouseover function in Selenium WebDriver using Java?

This code works perfectly well:

 Actions builder = new Actions(driver);
 WebElement element = driver.findElement(By.linkText("Put your text here"));
 builder.moveToElement(element).build().perform();

After the mouse over, you can then go on to perform the next action you want on the revealed information

How to create PDF files in Python

I have done this quite a bit in PyQt and it works very well. Qt has extensive support for images, fonts, styles, etc and all of those can be written out to pdf documents.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

BEST solution if you ask me is this. This will save the file with the file name of your choice and automatically in HTML or in TXT at your choice with buttons.

Example:

_x000D_
_x000D_
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}

function addTextHTML()
{
    document.addtext.name.value = document.addtext.name.value + ".html"
}

function addTextTXT()
{
    document.addtext.name.value = document.addtext.name.value + ".txt"
}
_x000D_
<html>
  <head></head>
  <body>

    <form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">

    <textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
    <br>
    <input type="text" name="name" value="" placeholder="File Name">
    <input type="submit" onClick="addTextHTML();" value="Save As HTML">
    <input type="submit" onClick="addTexttxt();" value="Save As TXT">

    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

Java, return if trimmed String in List contains String

You can use your own code. You don't need to use the looping structure, if you don't want to use the looping structure as you said above. Only you have to focus to remove space or trim the String of the list.

If you are using java8 you can simply trim the String using the single line of the code:

myList = myList.stream().map(String :: trim).collect(Collectors.toList());

The importance of the above line is, in the future, you can use a List or set as well. Now you can use your own code:

if(myList.contains("A")){
    //true
}else{
    // false
}

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

HTML: how to force links to open in a new tab, not new window

The way the browser handles new windows vs new tab is set in the browser's options and can only be changed by the user.

Aggregate / summarize multiple variables per group (e.g. sum, mean)

With the dplyr package, you can use summarise_all, summarise_at or summarise_if functions to aggregate multiple variables simultaneously. For the example dataset you can do this as follows:

library(dplyr)
# summarising all non-grouping variables
df2 <- df1 %>% group_by(year, month) %>% summarise_all(sum)

# summarising a specific set of non-grouping variables
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(x1, x2), sum)
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(-date), sum)

# summarising a specific set of non-grouping variables using select_helpers
# see ?select_helpers for more options
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(starts_with('x')), sum)
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(matches('.*[0-9]')), sum)

# summarising a specific set of non-grouping variables based on condition (class)
df2 <- df1 %>% group_by(year, month) %>% summarise_if(is.numeric, sum)

The result of the latter two options:

    year month        x1         x2
   <dbl> <dbl>     <dbl>      <dbl>
1   2000     1 -73.58134  -92.78595
2   2000     2 -57.81334 -152.36983
3   2000     3 122.68758  153.55243
4   2000     4 450.24980  285.56374
5   2000     5 678.37867  384.42888
6   2000     6 792.68696  530.28694
7   2000     7 908.58795  452.31222
8   2000     8 710.69928  719.35225
9   2000     9 725.06079  914.93687
10  2000    10 770.60304  863.39337
# ... with 14 more rows

Note: summarise_each is deprecated in favor of summarise_all, summarise_at and summarise_if.


As mentioned in my comment above, you can also use the recast function from the reshape2-package:

library(reshape2)
recast(df1, year + month ~ variable, sum, id.var = c("date", "year", "month"))

which will give you the same result.

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

UITableViewCell Selected Background Color on Multiple Selection

By adding a custom view with the background color of your own you can have a custom selection style in table view.

let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView

Add this 3 line code in cellForRowAt method of TableView. I have used an extension in UIColor to add color with hexcode. Put this extension code at the end of any Class(Outside the class's body).

extension UIColor {    
convenience init(hexString: String) {
    let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt32()
    Scanner(string: hex).scanHexInt32(&int)
    let a, r, g, b: UInt32
    switch hex.characters.count {
    case 3: // RGB (12-bit)
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: // RGB (24-bit)
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: // ARGB (32-bit)
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
  }
}

Cannot connect to Database server (mysql workbench)

The issue is likely due to socket authentication being enabled for the root user by default when no password is set, during the upgrade to ubuntu 16.04.

The solution is to revert back to native password authentication. You can do this by logging in to MySQL using socket authentication by doing:

sudo mysql -u root

Once logged in:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

which will revert back to the native (old default) password authentication.

Now use password as the password whenever required by MySQL.

Inserting a text where cursor is using Javascript/jquery

This question's answer was posted so long ago and I stumbled upon it via a Google search. HTML5 provides the HTMLInputElement API that includes the setRangeText() method, which replaces a range of text in an <input> or <textarea> element with a new string:

element.setRangeText('abc');

The above would replace the selection made inside element with abc. You can also specify which part of the input value to replace:

element.setRangeText('abc', 3, 5);

The above would replace the 4th till 6th characters of the input value with abc. You can also specify how the selection should be set after the text has been replaced by providing one of the following strings as the 4th parameter:

  • 'preserve' attempts to preserve the selection. This is the default.
  • 'select' selects the newly inserted text.
  • 'start' moves the selection to just before the inserted text.
  • 'end' moves the selection to just after the inserted text.

Browser compatibility

The MDN page for setRangeText doesn't provide browser compatibility data, but I guess it'd be the same as HTMLInputElement.setSelectionRange(), which is basically all modern browsers, IE 9 and above, Edge 12 and above.

Getting the "real" Facebook profile picture URL from graph API

The first URL gives a HTTP 302 (temporary redirect) to the second. So, to find the second URL programatically, you could issue a HTTP request for the first URL and get the Location header of the response.

That said, don't rely on the second URL being pemanent. Reading a little in to the HTTP response code (of 302 as opposed to a permanent 301), it is possible Facebook changes those URLs on a regular basis to prevent people from—for example—using their servers to host images.


Edit: Notice that the CDN URL the OP posted is now a 404, so we know that we cannot rely on the URL being long-lived. Also, if you're linking to the Graph API from an <img> on a SSL-secured page, there's a parameter you have to add make sure you use https://graph.facebook.com.


Update: The API has added a parameterredirect=false – which causes JSON to be returned rather than a redirect. The retruned JSON includes the CDN URL:

{
   "data": {
      "url": "http://profile.ak.fbcdn.net/...",
      "is_silhouette": false
   }
}

Again, I wouldn't rely on this CDN URL being long-lived. The JSON response is sent with permissive CORS headers, so you're free to do this client-side with XHR requests.

How do I convert datetime.timedelta to minutes, hours in Python?

Do you want to print the date in that format? This is the Python documentation: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

>>> a = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366)
>>> print a.strftime('%Y %d %B, %M:%S%p')
>>> 2013 07 January, 31:34AM

For the timedelta:

>>> a =  datetime.timedelta(0,5,41038)
>>> print '%s seconds, %s microseconds' % (a.seconds, a.microseconds)

But please notice, you should make sure it has the related value. For the above cases, it doesn't have the hours and minute values, and you should calculate from the seconds.

SyntaxError: Unexpected token o in JSON at position 1

The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.

You can test this yourself, e.g. in Chrome's console:

new Object().toString()
// "[object Object]"

JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse("[object Object]")
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.

Try the following instead:

var newData = userData.data.userList;

Pass a password to ssh in pure bash

Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage

which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh "thought" that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

How to update a menu item shown in the ActionBar?

In Kotlin 1.2 simply call:

invalidateOptionsMenu()

and the onCreateOptionsMenu function will be called again.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

R command for setting working directory to source file location in Rstudio

This answer can help:

script.dir <- dirname(sys.frame(1)$ofile)

Note: script must be sourced in order to return correct path

I found it in: https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

The BumbleBee´s answer (with parent.frame instead sys.frame) didn´t work to me, I always get an error.

Deploying just HTML, CSS webpage to Tomcat

Here's my setup: I am on Ubuntu 9.10.

Now, Here's what I did.

  1. Create a folder named "tomcat6-myapp" in /usr/share.
  2. Create a folder "myapp" under /usr/share/tomcat6-myapp.
  3. Copy the HTML file (that I need to deploy) to /usr/share/tomcat6-myapp/myapp. It must be named index.html.
  4. Go to /etc/tomcat6/Catalina/localhost.
  5. Create an xml file "myapp.xml" (i guess it must have the same name as the name of the folder in step 2) inside /etc/tomcat6/Catalina/localhost with the following contents.

    < Context path="/myapp" docBase="/usr/share/tomcat6-myapp/myapp" />
    
  6. This xml is called the 'Deployment Descriptor' which Tomcat reads and automatically deploys your app named "myapp".

  7. Now go to http://localhost:8080/myapp in your browser - the index.html gets picked up by tomcat and is shown.

I hope this helps!

AngularJS 1.2 $injector:modulerr

Besides below answer, if you have this error in console ([$injector:nomod], MINERR_ASSET:22), but everything seems to work fine, make sure that you don't have duplicate includes in your index.html.

Because this error can also be raised if you have duplicate includes of the files, that use this module, and are included before the file with actual module declaration.

How to set the font size in Emacs?

Press Shift and the first mouse button. You can change the font size in the following way: This website has more detail.

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.columns WHERE table_name = '<name_of_table_or_view>'

Run SELECT * in the above statement to see what information_schema.columns returns.

This question has been previously answered - https://stackoverflow.com/a/11268456/6169225

How to check java bit version on Linux?

Go to this JVM online test and run it.

Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.

Call JavaScript function from C#

This may be helpful to you:

<script type="text/javascript">
    function Showalert() {
        alert('Profile not parsed!!');
        window.parent.parent.parent.location.reload();
    }
    function ImportingDone() {
        alert('Importing done successfull.!');
        window.parent.parent.parent.location.reload();
    }
</script>

if (SelectedRowCount == 0)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Request-scoped beans can be autowired with the request object.

private @Autowired HttpServletRequest request;

How to include a font .ttf using CSS?

Did you try format?

@font-face {
  font-family: 'The name of the Font Family Here';
  src: URL('font.ttf') format('truetype');
}

Read this article: http://css-tricks.com/snippets/css/using-font-face/

Also, might depend on browser as well.

How do you use the ? : (conditional) operator in JavaScript?

x = 9
y = 8

unary

++x
--x

Binary

z = x + y

Ternary

2>3 ? true : false;
2<3 ? true : false;
2<3 ? "2 is lesser than 3" : "2 is greater than 3";

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Your version does not support that character set, I believe it was 5.5.3 that introduced it. You should upgrade your mysql to the version you used to export this file.

The error is then quite clear: you set a certain character set in your code, but your mysql version does not support it, and therefore does not know about it.

According to https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html :

utf8mb4 is a superset of utf8

so maybe there is a chance you can just make it utf8, close your eyes and hope, but that would depend on your data, and I'd not recommend it.

How to break out of jQuery each Loop

"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.

use for loop if you have to stop the loop execution based on some condition and remain in to the same function.

Setting a width and height on an A tag

All these suggestions work unless you put the anchors inside an UL list.

<ul>
    <li>
        <a>click me</a>>
    </li>
</ul>

Then any cascade style sheet rules are overridden in the Chrome browser. The width becomes auto. Then you must use inline CSS rules directly on the anchor itself.

Why a function checking if a string is empty always returns true?

I always use a regular expression for checking for an empty string, dating back to CGI/Perl days, and also with Javascript, so why not with PHP as well, e.g. (albeit untested)

return preg_match('/\S/', $input);

Where \S represents any non-whitespace character

Markdown: continue numbered list

If you want to have text aligned to preceding list item but avoid having "big" line break, use two spaces at the end of a list item and indent the text with some spaces.

Source: (dots are spaces ;-) of course)

1.·item1··
····This is some text
2.item2

Result:

  1. item1
    This is some text
  2. item2

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

For those who encounter this when you just recently updated IntelliJ (In my case 2019.2).

I am using JBoss server so i tried to run standalone.bat in the command line and I saw the real issue on the console.

It can be different to yours, but in my case I saw:

failure description: "WFLYSRV0137: No deployment content with

And on that error I was able to fix this by removing the items (war or ear) inside the <deployments/> node in my standalone.xml

Hope this helps for those using JBoss+IntelliJ

Animate a custom Dialog

For right to left (entry animation) and left to right (exit animation):

styles.xml:

<style name="CustomDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>

<style name="CustomDialogAnimation">
    <item name="android:windowEnterAnimation">@anim/translate_left_side</item>
    <item name="android:windowExitAnimation">@anim/translate_right_side</item>
</style>

Create two files in res/anim/:

translate_right_side.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%" android:toXDelta="100%"
    android:fromYDelta="0%" android:toYDelta="0%"
    android:duration="600"/>

translate_left_side.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="600"
    android:fromXDelta="100%"
    android:toXDelta="0%"/>

In you Fragment/Activity:

Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);

Error inflating class android.support.v7.widget.Toolbar?

I know this is an old question, but I recently ran into this same issue. It ended up being a Proguard problem (when I set minifyEnabled to false it stopped happening.)

To stop it, with proguard enabled, I added the following to my proguard rules file, thanks to a solution I found elsewhere (after discovering that the problem was proguard)

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.** { *; }

Not sure if they're necessary, but I also added these lines:

-keep class com.google.** { *; }
-keep interface com.google.** { *; }

Creating InetAddress object in Java

This is a project for getting IP address of any website , it's usefull and so easy to make.

import java.net.InetAddress;
import java.net.UnkownHostExceptiin;

public class Main{
    public static void main(String[]args){
        try{
            InetAddress addr = InetAddresd.getByName("www.yahoo.com");
            System.out.println(addr.getHostAddress());

          }catch(UnknownHostException e){
             e.printStrackTrace();
        }
    }
}

Repair all tables in one go

The command is this:

mysqlcheck -u root -p --auto-repair --check --all-databases

You must supply the password when asked,

or you can run this one but it's not recommended because the password is written in clear text:

mysqlcheck -u root --password=THEPASSWORD --auto-repair --check --all-databases

How/When does Execute Shell mark a build as failure in Jenkins?

In my opinion, turning off the -e option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.

If you have a line in your script where failure is expected, like a grep or a find, then just add || true to the end of that line. That ensures that line will always return success.

If you need to use that exit code, you can either hoist the command into your if statement:

grep foo bar; if [ $? == 0 ]; then ...    -->   if grep foo bar; then ...

Or you can capture the return code in your || clause:

grep foo bar || ret=$?

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

jQuery $(this) keyword

Have a look at this code:

HTML:

<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>

JS:

$('.multiple-elements').each(
    function(index, element) {
        $(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
    }
);

this refers to the current element that the DOM engine is sort of working on, or referring to.

Another example:

<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>

Hope you understand now. The this keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

matching query does not exist Error in Django

In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:

user = UniversityDetails.objects.get(email=email)

is email a str, or a None? or an int?

How to revert a "git rm -r ."?

If you've committed and pushed the changes, you can do this to get the file back

// Replace 2 with the # of commits back before the file was deleted.
git checkout HEAD~2 path/to/file

How to force keyboard with numbers in mobile website in Android

input type = number

When you want to provide a number input, you can use the HTML5 input type="number" attribute value.

<input type="number" name="n" />

Here is the keyboard that comes up on iPhone 4:

iPhone Screenshot of HTML5 input type number Android 2.2 uses this keyboard for type=number:

Android Screenshot of HTML5 input type number

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:

http://mvnrepository.com

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.12</version>
</dependency>

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

Option 1: Have an index on a non-null column present that can be used for the scan. Or create a function-based index as:

create index idx on t(0);

this can then be scanned to give the count.

Option 2: If you have monitoring turned on then check the monitoring view USER_TAB_MODIFICATIONS and add/subtract the relevant values to the table statistics.

Option 3: For a quick estimate on large tables invoke the SAMPLE clause ... for example ...

SELECT 1000*COUNT(*) FROM sometable SAMPLE(0.1); 

Option 4: Use a materialized view to maintain the count(*). Powerful medicine though.

um ...

How can I get current date in Android?

This is nothing to do with android as it is java based so you could use

private String getDateTime() { 
   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
   Date date = new Date(); 
   return dateFormat.format(date); 
}

Find difference between timestamps in seconds in PostgreSQL

select age(timestamp_A, timestamp_B)

Answering to Igor's comment:

select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
              age              
-------------------------------
 1 year 1 mon 28 days 00:01:28

Java, How to implement a Shift Cipher (Caesar Cipher)

Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ceasarserver extends JFrame implements ActionListener {
    static String cs = "abcdefghijklmnopqrstuvwxyz";
    static JLabel l1, l2, l3, l5, l6;
    JTextField t1;
    JButton close, b1;
    static String en;
    int num = 0;
    JProgressBar progress;

    ceasarserver() {
        super("SERVER");
        JPanel p = new JPanel(new GridLayout(10, 1));
        l1 = new JLabel("");
        l2 = new JLabel("");
        l3 = new JLabel("");
        l5 = new JLabel("");
        l6 = new JLabel("Enter the Key...");
        t1 = new JTextField(30);
        progress = new JProgressBar(0, 20);
        progress.setValue(0);
        progress.setStringPainted(true);
        close = new JButton("Close");
        close.setMnemonic('C');
        close.setPreferredSize(new Dimension(300, 25));
        close.addActionListener(this);
        b1 = new JButton("Decrypt");
        b1.setMnemonic('D');
        b1.addActionListener(this);
        p.add(l1);
        p.add(l2);
        p.add(l3);
        p.add(l6);
        p.add(t1);
        p.add(b1);
        p.add(progress);
        p.add(l5);
        p.add(close);
        add(p);
        setVisible(true);
        pack();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == close)
            System.exit(0);
        else if (e.getSource() == b1) {
            int key = Integer.parseInt(t1.getText());
            String d = "";
            int i = 0, j, k;
            while (i < en.length()) {
                j = cs.indexOf(en.charAt(i));
                k = (j + (26 - key)) % 26;
                d = d + cs.charAt(k);
                i++;
            }
            while (num < 21) {
                progress.setValue(num);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                }
                progress.setValue(num);
                Rectangle progressRect = progress.getBounds();
                progressRect.x = 0;
                progressRect.y = 0;
                progress.paintImmediately(progressRect);
                num++;
            }
            l5.setText("Decrypted text: " + d);
        }
    }

    public static void main(String args[]) throws IOException {
        new ceasarserver();
        String strm = new String();
        ServerSocket ss = new ServerSocket(4321);
        l1.setText("Secure data transfer Server Started....");
        Socket s = ss.accept();
        l2.setText("Client Connected !");
        while (true) {
            Scanner br1 = new Scanner(s.getInputStream());
            en = br1.nextLine();
            l3.setText("Client:" + en);
        }
    }

The client class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ceasarclient extends JFrame {
    String cs = "abcdefghijklmnopqrstuvwxyz";
    static JLabel l1, l2, l3, l4, l5;
    JButton b1, b2, b3;
    JTextField t1, t2;
    JProgressBar progress;
    int num = 0;
    String en = "";

    ceasarclient(final Socket s) {
        super("CLIENT");
        JPanel p = new JPanel(new GridLayout(10, 1));
        setSize(500, 500);
        t1 = new JTextField(30);
        b1 = new JButton("Send");
        b1.setMnemonic('S');
        b2 = new JButton("Close");
        b2.setMnemonic('C');
        l1 = new JLabel("Welcome to Secure Data transfer!");
        l2 = new JLabel("Enter the word here...");
        l3 = new JLabel("");
        l4 = new JLabel("Enter the Key:");
        b3 = new JButton("Encrypt");
        b3.setMnemonic('E');
        t2 = new JTextField(30);
        progress = new JProgressBar(0, 20);
        progress.setValue(0);
        progress.setStringPainted(true);
        p.add(l1);
        p.add(l2);
        p.add(t1);
        p.add(l4);
        p.add(t2);
        p.add(b3);
        p.add(progress);
        p.add(b1);
        p.add(l3);
        p.add(b2);
        add(p);
        setVisible(true);
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
                    pw.println(en);
                } catch (Exception ex) {
                }
                ;
                l3.setText("Encrypted Text Sent.");
            }
        });
        b3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String strw = t1.getText();
                int key = Integer.parseInt(t2.getText());
                int i = 0, j, k;
                while (i < strw.length()) {
                    j = cs.indexOf(strw.charAt(i));
                    k = (j + key) % 26;
                    en = en + cs.charAt(k);
                    i++;
                }
                while (num < 21) {
                    progress.setValue(num);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException exe) {
                    }
                    progress.setValue(num);
                    Rectangle progressRect = progress.getBounds();
                    progressRect.x = 0;
                    progressRect.y = 0;
                    progress.paintImmediately(progressRect);
                    num++;
                }
            }
        });
        b2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        pack();
    }

    public static void main(String args[]) throws IOException {
        final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
        new ceasarclient(s);
    }
}

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

Just change from "loaders" to "rules" in "webpack.config.js"

Because loaders is used in Webpack 1, and rules in Webpack2. You can see there have differences.

Streaming video from Android camera to server

Here is complete article about streaming android camera video to a webpage.

Android Streaming Live Camera Video to Web Page

  1. Used libstreaming on android app
  2. On server side Wowza Media Engine is used to decode the video stream
  3. Finally jWplayer is used to play the video on a webpage.

How do I copy a 2 Dimensional array in Java?

I solved it writing a simple function to copy multidimensional int arrays using System.arraycopy

public static void arrayCopy(int[][] aSource, int[][] aDestination) {
    for (int i = 0; i < aSource.length; i++) {
        System.arraycopy(aSource[i], 0, aDestination[i], 0, aSource[i].length);
    }
}

or actually I improved it for for my use case:

/**
 * Clones the provided array
 * 
 * @param src
 * @return a new clone of the provided array
 */
public static int[][] cloneArray(int[][] src) {
    int length = src.length;
    int[][] target = new int[length][src[0].length];
    for (int i = 0; i < length; i++) {
        System.arraycopy(src[i], 0, target[i], 0, src[i].length);
    }
    return target;
}

How can I convert a comma-separated string to an array?

Pass your comma-separated string into this function and it will return an array, and if a comma-separated string is not found then it will return null.

function splitTheString(CommaSepStr) {
    var ResultArray = null;

    // Check if the string is null or so.
    if (CommaSepStr!= null) {

        var SplitChars = ',';

        // Check if the string has comma of not will go to else
        if (CommaSepStr.indexOf(SplitChars) >= 0) {
            ResultArray = CommaSepStr.split(SplitChars);

        }
        else {

            // The string has only one value, and we can also check
            // the length of the string or time and cross-check too.
            ResultArray = [CommaSepStr];
        }
    }
    return ResultArray;
}

Free c# QR-Code generator

You can look at Open Source QR Code Library or messagingtoolkit-qrcode. I have not used either of them so I can not speak of their ease to use.

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

DateTime to javascript date

I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.

From Javascript to Server:

Send out dates as epoch values with the timezone offset removed.

var d = new Date(2015,0,1) // Jan 1, 2015
// Ajax Request to server ...
$.ajax({
  url: '/target',
  params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
});

The server then recieves 1420070400000 as the date epoch.

On the Server side, convert that epoch value to a datetime object:

DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);

At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.

Going the other way:

When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):

long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

or

long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;

When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:

var epochValue = 1420070400000 // value pulled from server.
var utcDateVal = new Date(epochValue);
var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))

console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

As far as I know, this should work for any time zone where you need to display dates that are timezone independent.

How to link C++ program with Boost using CMake

The following is my configuration:

cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )

Dynamically load a JavaScript file

There is no import / include / require in javascript, but there are two main ways to achieve what you want:

1 - You can load it with an AJAX call then use eval.

This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks.

2 - Add a script tag with the script URL in the HTML.

Definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the tag in the head of the web page, or at the bottom of the body.

Both of these solutions are discussed and illustrated here.

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performances.

It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

E.G : my_lovely_script.js contains MySuperObject

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. E.G :

function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function :

var myPrettyCode = function() {
    // here, do what ever you want
};

Then you run all that :

loadScript("my_lovely_script.js", myPrettyCode);

Ok, I got it. But it's a pain to write all this stuff.

Well, in that case, you can use as always the fantastic free jQuery framework, which let you do the very same thing in one line :

$.getScript("my_lovely_script.js", function() {
    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script
});

Customize Bootstrap checkboxes

As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.

In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.

How do I pass along variables with XMLHTTPRequest

The correct format for passing variables in a GET request is

?variable1=value1&variable2=value2&variable3=value3...
                 ^ ---notice &--- ^

But essentially, you have the right idea.

How do I get values from a SQL database into textboxes using C#?

read = com.ExecuteReader()

SqlDataReader has a function Read() that reads the next row from your query's results and returns a bool whether it found a next row to read or not. So you need to check that before you actually get the columns from your reader (which always just gets the current row that Read() got). Or preferably make a loop while(read.Read()) if your query returns multiple rows.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

UIGestureRecognizer on UIImageView

Yes, a UIGestureRecognizer can be added to a UIImageView. As stated in the other answer, it is very important to remember to enable user interaction on the image view by setting its userInteractionEnabled property to YES. UIImageView inherits from UIView, whose user interaction property is set to YES by default, however, UIImageView's user interaction property is set to NO by default.

From the UIImageView docs:

New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object.

Anyway, on the the bulk of the answer. Here's an example of how to create a UIImageView with a UIPinchGestureRecognizer, a UIRotationGestureRecognizer, and a UIPanGestureRecognizer.

First, in viewDidLoad, or another method of your choice, create an image view, give it an image, a frame, and enable its user interaction. Then create the three gestures as follows. Be sure to utilize their delegate property (most likely set to self). This will be required to use multiple gestures at the same time.

- (void)viewDidLoad
{
    [super viewDidLoad];

    // set up the image view
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"someImage"]];
    [imageView setBounds:CGRectMake(0.0, 0.0, 120.0, 120.0)];
    [imageView setCenter:self.view.center];
    [imageView setUserInteractionEnabled:YES]; // <--- This is very important

    // create and configure the pinch gesture
    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureDetected:)];
    [pinchGestureRecognizer setDelegate:self];
    [imageView addGestureRecognizer:pinchGestureRecognizer];

    // create and configure the rotation gesture
    UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureDetected:)];
    [rotationGestureRecognizer setDelegate:self];
    [imageView addGestureRecognizer:rotationGestureRecognizer];

    // creat and configure the pan gesture
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureDetected:)];
    [panGestureRecognizer setDelegate:self];
    [imageView addGestureRecognizer:panGestureRecognizer];


    [self.view addSubview:imageView]; // add the image view as a subview of the view controllers view
}

Here are the three methods that will be called when the gestures on your view are detected. Inside them, we will check the current state of the gesture, and if it is in either the began or changed UIGestureRecognizerState we will read the gesture's scale/rotation/translation property, apply that data to an affine transform, apply the affine transform to the image view, and then reset the gestures scale/rotation/translation.

- (void)pinchGestureDetected:(UIPinchGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];

    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat scale = [recognizer scale];
        [recognizer.view setTransform:CGAffineTransformScale(recognizer.view.transform, scale, scale)];
        [recognizer setScale:1.0];
    }
}

- (void)rotationGestureDetected:(UIRotationGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];

    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat rotation = [recognizer rotation];
        [recognizer.view setTransform:CGAffineTransformRotate(recognizer.view.transform, rotation)];
        [recognizer setRotation:0];
    }
}

- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];

    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [recognizer translationInView:recognizer.view];
        [recognizer.view setTransform:CGAffineTransformTranslate(recognizer.view.transform, translation.x, translation.y)];
        [recognizer setTranslation:CGPointZero inView:recognizer.view];
    }
}

Finally and very importantly, you'll need to utilize the UIGestureRecognizerDelegate method gestureRecognizer: shouldRecognizeSimultaneouslyWithGestureRecognizer to allow the gestures to work at the same time. If these three gestures are the only three gestures that have this class assigned as their delegate, then you can simply return YES as shown below. However, if you have additional gestures that have this class assigned as their delegate, you may need to add logic to this method to determine which gesture is which before allowing them to all work together.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

Don't forget to make sure that your class conforms to the UIGestureRecognizerDelegate protocol. To do so, make sure that your interface looks something like this:

@interface MyClass : MySuperClass <UIGestureRecognizerDelegate>

If you prefer to play with the code in a working sample project yourself, the sample project I've created containing this code can be found here.

The Android emulator is not starting, showing "invalid command-line parameter"

I had this issue as well. The solution is (if you are on Windows as I am) to change the path to C:\PROGRA~1\Android\android-sdk-windows\.

Assuming Program Files is the first directory with the word PROGRAM in it which it should be. This worked.

How to get the filename without the extension from a path in Python?

The other methods don't remove multiple extensions. Some also have problems with filenames that don't have extensions. This snippet deals with both instances and works in both Python 2 and 3. It grabs the basename from the path, splits the value on dots, and returns the first one which is the initial part of the filename.

import os

def get_filename_without_extension(file_path):
    file_basename = os.path.basename(file_path)
    filename_without_extension = file_basename.split('.')[0]
    return filename_without_extension

Here's a set of examples to run:

example_paths = [
    "FileName", 
    "./FileName",
    "../../FileName",
    "FileName.txt", 
    "./FileName.txt.zip.asc",
    "/path/to/some/FileName",
    "/path/to/some/FileName.txt",
    "/path/to/some/FileName.txt.zip.asc"
]

for example_path in example_paths:
    print(get_filename_without_extension(example_path))

In every case, the value printed is:

FileName

How to configure Fiddler to listen to localhost?

And I just found out that on vista 'localhost.' will not work. In this case use '127.0.0.1.' (loopback address with a dot appended to it).

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

Remove first Item of the array (like popping from stack)

Plunker

$scope.remove = function(item) { 
    $scope.cards.splice(0, 1);     
  }

Made changes to .. now it will remove from the top

SELECT INTO using Oracle

If NEW_TABLE already exists then ...

insert into new_table 
select * from old_table
/

If you want to create NEW_TABLE based on the records in OLD_TABLE ...

create table new_table as 
select * from old_table
/

If the purpose is to create a new but empty table then use a WHERE clause with a condition which can never be true:

create table new_table as 
select * from old_table
where 1 = 2
/

Remember that CREATE TABLE ... AS SELECT creates only a table with the same projection as the source table. The new table does not have any constraints, triggers or indexes which the original table might have. Those still have to be added manually (if they are required).

Print the contents of a DIV

I authored a plugin to address this scenario. I was unhappy with the plugins out there, and set out to make something more extensive/configurable.

https://github.com/jasonday/printThis

Execute another jar in a Java program

If you are java 1.6 then the following can also be done:

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 

public class CompilerExample {

    public static void main(String[] args) {
        String fileToCompile = "/Users/rupas/VolatileExample.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}

Using comma as list separator with AngularJS

You could do it this way:

<b ng-repeat="email in friend.email">{{email}}{{$last ? '' : ', '}}</b>

..But I like Philipp's answer :-)

Load and execute external js file in node.js with access to local variables?

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context. 

What's an easy way to read random line from a file in Unix command line?

This is simple.

cat file.txt | shuf -n 1

Granted this is just a tad slower than the "shuf -n 1 file.txt" on its own.

How do I keep two side-by-side divs the same height?

I just wanted to add to the great Flexbox solution described by Pavlo, that, in my case, I had two lists/columns of data that I wanted to display side-by-side with just a little spacing between, horizontally-centered inside an enclosing div. By nesting another div within the first (leftmost) flex:1 div and floating it right, I got just what I wanted. I couldn't find any other way to do this with consistent success at all viewport widths:

<div style="display:flex">
    <div style="flex:1;padding-right:15px">
        <div style="float:right">
            [My Left-hand list of stuff]
        </div>
    </div>

    <div style="flex:1;padding-left:15px">
            [My Right-hand list of stuff]
    </div>
</div>

How to sum the values of a JavaScript object?

Now you can make use of reduce function and get the sum.

_x000D_
_x000D_
const object1 = { 'a': 1 , 'b': 2 , 'c':3 }_x000D_
_x000D_
console.log(Object.values(object1).reduce((a, b) => a + b, 0));
_x000D_
_x000D_
_x000D_

new Runnable() but no new thread?

A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.

Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.

In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.

Below a useless code is given, but it will suffice to do away with your some confusions about Runnable. It will print "Hello World".

class NamedRunnable implements Runnable {

    public void run() { // The run method prints a message to standard output.
        System.out.println("Hello World");
    }

    public static void main(String[]arg){ 
        NamedRunnable namedRunnable = new NamedRunnable( );
        namedRunnable.run();
    } 
}

mappedBy reference an unknown target entity property

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "USER_ID")
    Long userId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> receiver;
}

public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id

    @Column(name = "NOTIFICATION_ID")
    Long notificationId;

    @Column(name = "TEXT")
    String text;

    @Column(name = "ALERT_STATUS")
    @Enumerated(EnumType.STRING)
    AlertStatus alertStatus = AlertStatus.NEW;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SENDER_ID")
    @JsonIgnore
    User sender;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "RECEIVER_ID")
    @JsonIgnore
    User receiver;
}

What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..

User model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
    List<Notification> receiver;

Notification model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> **sender**;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> **receiver**;

I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.

how to prevent "directory already exists error" in a makefile when using mkdir

If you explicitly ignore the return code and dump the error stream then your make will ignore the error if it occurs:

mkdir 2>/dev/null || true

This should not cause a race hazard in a parallel make - but I haven't tested it to be sure.

Force overwrite of local file with what's in origin repo?

If you want to overwrite only one file:

git fetch
git checkout origin/master <filepath>

If you want to overwrite all changed files:

git fetch
git reset --hard origin/master

(This assumes that you're working on master locally and you want the changes on the origin's master - if you're on a branch, substitute that in instead.)

How exactly does <script defer="defer"> work?

UPDATED: 2/19/2016

Consider this answer outdated. Refer to other answers on this post for information relevant to newer browser version.


Basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4

The defer attribute is specific to internet explorer. In Internet Explorer 8, on Windows 7 the result I am seeing in your JS Fiddle test page is, 1 - 2 - 3.

The results may vary from browser to browser.

http://msdn.microsoft.com/en-us/library/ms533719(v=vs.85).aspx

Contrary to popular belief IE follows standards more often than people let on, in actuality the "defer" attribute is defined in the DOM Level 1 spec http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html

The W3C's definition of defer: http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer:

"When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering."

How to reload the current route with the angular 2 router

A solution is to pass a dummy parameter (i.e. the time in seconds), in this way the link is always reloaded:

this.router.navigate(["/url", {myRealData: RealData, dummyData: (new Date).getTime()}])

How do I check to see if my array includes an object?

#include? should work, it works for general objects, not only strings. Your problem in example code is this test:

unless @suggested_horses.exists?(horse.id)
  @suggested_horses<< horse
end

(even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

unless @suggested_horses.include?(horse)
  @suggested_horses << horse
end

ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

How to return a value from a Form in C#?

First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :

 public string Response { get; set; }

 private void OkButton_Click(object sender, EventArgs e)
 {
    Response = "ok";
 }

 private void CancelButton_Click(object sender, EventArgs e)
 {
    Response = "Cancel";
 }

Calling of form2(child) from form1(parent):

  using (Form2 formObject= new Form2() )
  {
     formObject.ShowDialog();

      string result = formObject.Response; 
      //to update response of form2 after saving in result
      formObject.Response="";

      // do what ever with result...
      MessageBox.Show("Response from form2: "+result); 
  }

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

The type or namespace name 'System' could not be found

You can check the framework on which system was created and developed, and then changes the framework of your current solution to the old framework. You can do this by right click on the solution and then choose properties. In Application section you can change the framework.

how to check if a file is a directory or regular file in python?

An educational example from the stat documentation:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname)[ST_MODE]
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)

NSRange from Swift Range?

Swift String ranges and NSString ranges are not "compatible". For example, an emoji like counts as one Swift character, but as two NSString characters (a so-called UTF-16 surrogate pair).

Therefore your suggested solution will produce unexpected results if the string contains such characters. Example:

let text = "Long paragraph saying!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)

text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
    let start = distance(text.startIndex, substringRange.startIndex)
    let length = distance(substringRange.startIndex, substringRange.endIndex)
    let range = NSMakeRange(start, length)

    if (substring == "saying") {
        attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
    }
})
println(attributedString)

Output:

Long paragra{
}ph say{
    NSColor = "NSCalibratedRGBColorSpace 1 0 0 1";
}ing!{
}

As you see, "ph say" has been marked with the attribute, not "saying".

Since NS(Mutable)AttributedString ultimately requires an NSString and an NSRange, it is actually better to convert the given string to NSString first. Then the substringRange is an NSRange and you don't have to convert the ranges anymore:

let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: nsText)

nsText.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in

    if (substring == "saying") {
        attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
    }
})
println(attributedString)

Output:

Long paragraph {
}saying{
    NSColor = "NSCalibratedRGBColorSpace 1 0 0 1";
}!{
}

Update for Swift 2:

let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)

nsText.enumerateSubstringsInRange(textRange, options: .ByWords, usingBlock: {
    (substring, substringRange, _, _) in

    if (substring == "saying") {
        attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
    }
})
print(attributedString)

Update for Swift 3:

let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)

nsText.enumerateSubstrings(in: textRange, options: .byWords, using: {
    (substring, substringRange, _, _) in

    if (substring == "saying") {
        attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.red, range: substringRange)
    }
})
print(attributedString)

Update for Swift 4:

As of Swift 4 (Xcode 9), the Swift standard library provides method to convert between Range<String.Index> and NSRange. Converting to NSString is no longer necessary:

let text = "Long paragraph saying!"
let attributedString = NSMutableAttributedString(string: text)

text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: .byWords) {
    (substring, substringRange, _, _) in
    if substring == "saying" {
        attributedString.addAttribute(.foregroundColor, value: NSColor.red,
                                      range: NSRange(substringRange, in: text))
    }
}
print(attributedString)

Here substringRange is a Range<String.Index>, and that is converted to the corresponding NSRange with

NSRange(substringRange, in: text)

Using the GET parameter of a URL in JavaScript

You can get the "search" part of the location object - and then parse it out.

var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];

'git status' shows changed files, but 'git diff' doesn't

TL;DR

Line ending issue:

  1. Change autocrlf setting to default true. I.e., checkout Windows-style line endings on Windows and commit Linux-style line endings on remote git repo:
    git config --global core.autocrlf true
    
  2. On a Windows mahcine, change all files in the repo to Windows-style:
    unix2dos **
    
  3. Git add all modified files and modified files will go:
    git add .
    git status
    

Background

  • Platform: Windows, WSL

I occassionally run into this issue that git status shows I have files modified while git diff shows nothing. This is most likely issue of line endings. I finally figured out how it always happen and share here to see if it can help others.

Root Cause

The reason I encounter this issue often is that I work on a Windows machine and interact with Git in WSL. Switching between linux and Windows setting can easily cause this end-of-line issue. Since line ending format used in OS differs:

  • Windows: \r\n
  • OSX / Linux: \n

Common Practice

When you install Git on your machine, it will ask you to choose line endings setting. Usually, the common practice is to use (commit) Linux-style line endings on your remote git repo and checkout Windows-style on your Windows machine. If you use default setting, this is what git do for you. enter image description here

This means if you have a shell script myScript.sh and bash script myScript.cmd in your repo, the scripts both exist with Linux-style ending in your remote git repo, and both exist with Windows-style ending on your Windows machine.

I used to checkout shell script file and use dos2unix to change the script line-ending in order to run the shell script in WSL. This is why I encounter the issue. Git keeps telling me my modification of line-ending has been changed and asks whether to commit the changes.

Solution

Use default line ending settings and if you change the line endings of some files (like use the dos2unix or dos2unix), drop the changings. If line-endings changes already exist and you would like to get rid of it, try git add them and the changes will go.

jQuery Validate - Enable validation for hidden fields

This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code

$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";

To enable validation for all elements of form use this one $("form").data("validator").settings.ignore = "";

Note that use them within $(document).ready(function() { })

Unable to set data attribute using jQuery Data() API

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();

Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

Setting Windows PowerShell environment variables

Like JeanT's answer, I wanted an abstraction around adding to the path. Unlike JeanT's answer I needed it to run without user interaction. Other behavior I was looking for:

  • Updates $env:Path so the change takes effect in the current session
  • Persists the environment variable change for future sessions
  • Doesn't add a duplicate path when the same path already exists

In case it's useful, here it is:

function Add-EnvPath {
    param(
        [Parameter(Mandatory=$true)]
        [string] $Path,

        [ValidateSet('Machine', 'User', 'Session')]
        [string] $Container = 'Session'
    )

    if ($Container -ne 'Session') {
        $containerMapping = @{
            Machine = [EnvironmentVariableTarget]::Machine
            User = [EnvironmentVariableTarget]::User
        }
        $containerType = $containerMapping[$Container]

        $persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
        if ($persistedPaths -notcontains $Path) {
            $persistedPaths = $persistedPaths + $Path | where { $_ }
            [Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
        }
    }

    $envPaths = $env:Path -split ';'
    if ($envPaths -notcontains $Path) {
        $envPaths = $envPaths + $Path | where { $_ }
        $env:Path = $envPaths -join ';'
    }
}

Check out my gist for the corresponding Remove-EnvPath function.

rawQuery(query, selectionArgs)

String mQuery = "SELECT Name,Family From tblName";
Cursor mCur = db.rawQuery(mQuery, new String[]{});
mCur.moveToFirst();
while ( !mCur.isAfterLast()) {
        String name= mCur.getString(mCur.getColumnIndex("Name"));
        String family= mCur.getString(mCur.getColumnIndex("Family"));
        mCur.moveToNext();
}

Name and family are your result

How do I add a newline to command output in PowerShell?

Give this a try:

PS> $nl = [Environment]::NewLine
PS> gci hklm:\software\microsoft\windows\currentversion\uninstall | 
        ForEach { $_.GetValue("DisplayName") } | Where {$_} | Sort |
        Foreach {"$_$nl"} | Out-File addrem.txt -Enc ascii

It yields the following text in my addrem.txt file:

Adobe AIR

Adobe Flash Player 10 ActiveX

...

Note: on my system, GetValue("DisplayName") returns null for some entries, so I filter those out. BTW, you were close with this:

ForEach-Object -Process { "$_.GetValue("DisplayName") `n" }

Except that within a string, if you need to access a property of a variable, that is, "evaluate an expression", then you need to use subexpression syntax like so:

Foreach-Object -Process { "$($_.GetValue('DisplayName'))`r`n" }

Essentially within a double quoted string PowerShell will expand variables like $_, but it won't evaluate expressions unless you put the expression within a subexpression using this syntax:

$(`<Multiple statements can go in here`>).

How do I reflect over the members of dynamic object?

Requires Newtonsoft Json.Net

A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:

public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
    JObject attributesAsJObject = dynamicToGetPropertiesFor;
    Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
    List<string> toReturn = new List<string>();
    foreach (string key in values.Keys)
    {
        toReturn.Add(key);                
    }
    return toReturn;
}

Then you simply foreach like this:

foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
    dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
    // And
    dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}

Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.

How to workaround 'FB is not defined'?

There is solution for you :)

You must run your script after window loaded

if you use jQuery, you can use simple way:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'your-app-id',
            xfbml      : true,
            status     : true,
            version    : 'v2.5'
        });
    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

<script>
$(window).load(function() {
    var comment_callback = function(response) {
        console.log("comment_callback");
        console.log(response);
    }
    FB.Event.subscribe('comment.create', comment_callback);
    FB.Event.subscribe('comment.remove', comment_callback);
});
</script>

Android Color Picker

Here's another library:

https://github.com/eltos/SimpleDialogFragments

Features color wheel and pallet picker dialogs

How to change Tkinter Button state from disabled to normal?

This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?

import tkinter

class App(object):
    def __init__(self):
        self.tree = None
        self._setup_widgets()

    def _setup_widgets(self):
        butts = tkinter.Button(text = "add line", state="disabled")
        butts.grid()

def main():  
    root = tkinter.Tk()
    app = App()
    root.mainloop()

if __name__ == "__main__":
    main()

How to check if smtp is working from commandline (Linux)

The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)

thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
>    1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$ 
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<-  220 dur.bounceme.net ESMTP Postfix (Ubuntu)
 -> EHLO dur.bounceme.net
<-  250-dur.bounceme.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<[email protected]>
<-  250 2.1.0 Ok
 -> RCPT TO:<[email protected]>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Mon, 30 Dec 2013 14:33:17 -0800
 -> To: [email protected]
 -> From: [email protected]
 -> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 -> 
 -> This is a test mailing
 -> 
 -> .
<-  250 2.0.0 Ok: queued as 52D162C3EFF
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
     1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
>N   5 [email protected]                   15/581   test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
    by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
    for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>

This is a test mailing

New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$ 

It's just one easy command.

Numpy Resize/Rescale Image

For people coming here from Google looking for a fast way to downsample images in numpy arrays for use in Machine Learning applications, here's a super fast method (adapted from here ). This method only works when the input dimensions are a multiple of the output dimensions.

The following examples downsample from 128x128 to 64x64 (this can be easily changed).

Channels last ordering

# large image is shape (128, 128, 3)
# small image is shape (64, 64, 3)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((output_size, bin_size, 
                                   output_size, bin_size, 3)).max(3).max(1)

Channels first ordering

# large image is shape (3, 128, 128)
# small image is shape (3, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((3, output_size, bin_size, 
                                      output_size, bin_size)).max(4).max(2)

For grayscale images just change the 3 to a 1 like this:

Channels first ordering

# large image is shape (1, 128, 128)
# small image is shape (1, 64, 64)
input_size = 128
output_size = 64
bin_size = input_size // output_size
small_image = large_image.reshape((1, output_size, bin_size,
                                      output_size, bin_size)).max(4).max(2)

This method uses the equivalent of max pooling. It's the fastest way to do this that I've found.

Convert seconds value to hours minutes seconds?

I prefer java's built in TimeUnit library

long seconds = TimeUnit.MINUTES.toSeconds(8);

Exporting functions from a DLL with dllexport

I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport) to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does

python numpy machine epsilon

Another easy way to get epsilon is:

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16

Nginx: Permission denied for nginx on Ubuntu

just because you don't have the right to acess the file , use

chmod -R 755 /var/log/nginx;

or you can change to sudo then it

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

What does "yield break;" do in C#?

Ends an iterator block (e.g. says there are no more elements in the IEnumerable).

Where do I put my php files to have Xampp parse them?

in XAMPP the default root is "htdocs" inside the XAMPP folder, if you followed the instructions on the xampp homepage it would be "/opt/lampp/htdocs"

Up, Down, Left and Right arrow keys do not trigger KeyDown event

In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey().

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //handle your keys here
}

Example :

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //capture up arrow key
    if (keyData == Keys.Up )
    {
        MessageBox.Show("You pressed Up arrow key");
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Full source...Arrow keys in C#

Vayne

Handling multiple IDs in jQuery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

MISCONF Redis is configured to save RDB snapshots

I hit this problem while working on a server with AFS disk space because my authentication token had expired, which yielded Permission Denied responses when the redis-server tried to save. I solved this by refreshing my token:

kinit USERNAME_HERE -l 30d && aklog

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

How to merge multiple dicts with same key or different key?

Assuming there are two dictionaries with exact same keys, below is the most succinct way of doing it (python3 should be used for both the solution).


d1 = {'a': 1, 'b': 2, 'c':3}
d2 = {'a': 5, 'b': 6, 'c':7} 

# get keys from one of the dictionary
ks = [k for k in d1.keys()]

print(ks)
['a', 'b', 'c']

# call values from each dictionary on available keys
d_merged = {k: (d1[k], d2[k]) for k in ks}

print(d_merged)
{'a': (1, 5), 'b': (2, 6), 'c': (3, 7)}

# to merge values as list
d_merged = {k: [d1[k], d2[k]] for k in ks}
print(d_merged)
{'a': [1, 5], 'b': [2, 6], 'c': [3, 7]}

If there are two dictionaries with some common keys, but a few different keys, a list of all the keys should be prepared.


d1 = {'a': 1, 'b': 2, 'c':3, 'd': 9}
d2 = {'a': 5, 'b': 6, 'c':7, 'e': 4} 

# get keys from one of the dictionary
d1_ks = [k for k in d1.keys()]
d2_ks = [k for k in d2.keys()]

all_ks = set(d1_ks + d2_ks)

print(all_ks)
['a', 'b', 'c', 'd', 'e']

# call values from each dictionary on available keys
d_merged = {k: [d1.get(k), d2.get(k)] for k in all_ks}

print(d_merged)
{'d': [9, None], 'a': [1, 5], 'b': [2, 6], 'c': [3, 7], 'e': [None, 4]}

Count number of occurrences of a pattern in a file (even on same line)

Try this:

grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c

Sample:

grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
  6  SMTP connect from unknown [188.190.118.90]
 54  SMTP connect from unknown [62.193.131.114]
  3  SMTP connect from unknown [91.222.51.253]

ld.exe: cannot open output file ... : Permission denied

I had a similar problem. Using a freeware utility called Unlocker (version 1.9.2), I found that my antivirus software (Panda free) had left a hanging lock on the executable file even though it didn't detect any threat. Unlocker was able to unlock it.

Getting a Request.Headers value

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

Maven plugins can not be found in IntelliJ

Here is what I tried to fix the issue and it worked:

  1. Manually deleted the existing plugin from the .m2 repo
  2. Enabled "use plugin registry" in IntelliJ
  3. Invalidated the cache and restarted IntelliJ
  4. Reimported the maven project in IntelliJ

After following above steps, the issue was fixed. Hopefully this helps you as well.

Convert Map to JSON using Jackson

Using jackson, you can do it as follows:

    ObjectMapper mapper = new ObjectMapper();
    String clientFilterJson = "";
    try {
        clientFilterJson = mapper.writeValueAsString(filterSaveModel);
    } catch (IOException e) {
        e.printStackTrace();
    }

How does functools partial do what it does?

This answer is more of an example code. All the above answers give good explanations regarding why one should use partial. I will give my observations and use cases about partial.

from functools import partial
 def adder(a,b,c):
    print('a:{},b:{},c:{}'.format(a,b,c))
    ans = a+b+c
    print(ans)
partial_adder = partial(adder,1,2)
partial_adder(3)  ## now partial_adder is a callable that can take only one argument

Output of the above code should be:

a:1,b:2,c:3
6

Notice that in the above example a new callable was returned that will take parameter (c) as it's argument. Note that it is also the last argument to the function.

args = [1,2]
partial_adder = partial(adder,*args)
partial_adder(3)

Output of the above code is also:

a:1,b:2,c:3
6

Notice that * was used to unpack the non-keyword arguments and the callable returned in terms of which argument it can take is same as above.

Another observation is: Below example demonstrates that partial returns a callable which will take the undeclared parameter (a) as an argument.

def adder(a,b=1,c=2,d=3,e=4):
    print('a:{},b:{},c:{},d:{},e:{}'.format(a,b,c,d,e))
    ans = a+b+c+d+e
    print(ans)
partial_adder = partial(adder,b=10,c=2)
partial_adder(20)

Output of the above code should be:

a:20,b:10,c:2,d:3,e:4
39

Similarly,

kwargs = {'b':10,'c':2}
partial_adder = partial(adder,**kwargs)
partial_adder(20)

Above code prints

a:20,b:10,c:2,d:3,e:4
39

I had to use it when I was using Pool.map_async method from multiprocessing module. You can pass only one argument to the worker function so I had to use partial to make my worker function look like a callable with only one input argument but in reality my worker function had multiple input arguments.

How do I sort a two-dimensional (rectangular) array in C#?

Can allso look at Array.Sort Method http://msdn.microsoft.com/en-us/library/aa311213(v=vs.71).aspx

e.g. Array.Sort(array, delegate(object[] x, object[] y){ return (x[ i ] as IComparable).CompareTo(y[ i ]);});

from http://channel9.msdn.com/forums/Coffeehouse/189171-Sorting-Two-Dimensional-Arrays-in-C/

Invariant Violation: _registerComponent(...): Target container is not a DOM element

By the time script is executed, document element is not available yet, because script itself is in the head. While it's a valid solution to keep script in head and render on DOMContentLoaded event, it's even better to put your script at the very bottom of the body and render root component to a div before it like this:

<html>
<head>
</head>
<body>
  <div id="root"></div>
  <script src="/bundle.js"></script>
</body>
</html>

and in the bundle.js, call:

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

You should always render to a nested div instead of body. Otherwise, all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.

The nice thing about putting script at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.


Update: (October 07, 2015 | v0.14)

React.render is deprecated, use ReactDOM.render instead.

Example:

import ReactDOM from 'react-dom';

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

How to override the [] operator in Python?

To fully overload it you also need to implement the __setitem__and __delitem__ methods.

edit

I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__.

There are all documented in http://docs.python.org/reference/datamodel.html

How to force input to only allow Alpha Letters?

Nice one-liner HTML only:

 <input type="text" id='nameInput' onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))'>

Switch statement fallthrough in C#?

To add to the answers here, I think it's worth considering the opposite question in conjunction with this, viz. why did C allow fall-through in the first place?

Any programming language of course serves two goals:

  1. Provide instructions to the computer.
  2. Leave a record of the intentions of the programmer.

The creation of any programming language is therefore a balance between how to best serve these two goals. On the one hand, the easier it is to turn into computer instructions (whether those are machine code, bytecode like IL, or the instructions are interpreted on execution) then more able that process of compilation or interpretation will be to be efficient, reliable and compact in output. Taken to its extreme, this goal results in our just writing in assembly, IL, or even raw op-codes, because the easiest compilation is where there is no compilation at all.

Conversely, the more the language expresses the intention of the programmer, rather than the means taken to that end, the more understandable the program both when writing and during maintenance.

Now, switch could always have been compiled by converting it into the equivalent chain of if-else blocks or similar, but it was designed as allowing compilation into a particular common assembly pattern where one takes a value, computes an offset from it (whether by looking up a table indexed by a perfect hash of the value, or by actual arithmetic on the value*). It's worth noting at this point that today, C# compilation will sometimes turn switch into the equivalent if-else, and sometimes use a hash-based jump approach (and likewise with C, C++, and other languages with comparable syntax).

In this case there are two good reasons for allowing fall-through:

  1. It just happens naturally anyway: if you build a jump table into a set of instructions, and one of the earlier batches of instructions doesn't contain some sort of jump or return, then execution will just naturally progress into the next batch. Allowing fall-through was what would "just happen" if you turned the switch-using C into jump-table–using machine code.

  2. Coders who wrote in assembly were already used to the equivalent: when writing a jump table by hand in assembly, they would have to consider whether a given block of code would end with a return, a jump outside of the table, or just continue on to the next block. As such, having the coder add an explicit break when necessary was "natural" for the coder too.

At the time therefore, it was a reasonable attempt to balance the two goals of a computer language as it relates to both the produced machine code, and the expressiveness of the source code.

Four decades later though, things are not quite the same, for a few reasons:

  1. Coders in C today may have little or no assembly experience. Coders in many other C-style languages are even less likely to (especially Javascript!). Any concept of "what people are used to from assembly" is no longer relevant.
  2. Improvements in optimisations mean that the likelihood of switch either being turned into if-else because it was deemed the approach likely to be most efficient, or else turned into a particularly esoteric variant of the jump-table approach are higher. The mapping between the higher- and lower-level approaches is not as strong as it once was.
  3. Experience has shown that fall-through tends to be the minority case rather than the norm (a study of Sun's compiler found 3% of switch blocks used a fall-through other than multiple labels on the same block, and it was thought that the use-case here meant that this 3% was in fact much higher than normal). So the language as studied make the unusual more readily catered-to than the common.
  4. Experience has shown that fall-through tends to be the source of problems both in cases where it is accidentally done, and also in cases where correct fall-through is missed by someone maintaining the code. This latter is a subtle addition to the bugs associated with fall-through, because even if your code is perfectly bug-free, your fall-through can still cause problems.

Related to those last two points, consider the following quote from the current edition of K&R:

Falling through from one case to another is not robust, being prone to disintegration when the program is modified. With the exception of multiple labels for a single computation, fall-throughs should be used sparingly, and commented.

As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.

So, from the horse's mouth, fall-through in C is problematic. It's considered good practice to always document fall-throughs with comments, which is an application of the general principle that one should document where one does something unusual, because that's what will trip later examination of the code and/or make your code look like it has a novice's bug in it when it is in fact correct.

And when you think about it, code like this:

switch(x)
{
  case 1:
   foo();
   /* FALLTHRU */
  case 2:
    bar();
    break;
}

Is adding something to make the fall-through explicit in the code, it's just not something that can be detected (or whose absence can be detected) by the compiler.

As such, the fact that on has to be explicit with fall-through in C# doesn't add any penalty to people who wrote well in other C-style languages anyway, since they would already be explicit in their fall-throughs.†

Finally, the use of goto here is already a norm from C and other such languages:

switch(x)
{
  case 0:
  case 1:
  case 2:
    foo();
    goto below_six;
  case 3:
    bar();
    goto below_six;
  case 4:
    baz();
    /* FALLTHRU */
  case 5:
  below_six:
    qux();
    break;
  default:
    quux();
}

In this sort of case where we want a block to be included in the code executed for a value other than just that which brings one to the preceding block, then we're already having to use goto. (Of course, there are means and ways of avoiding this with different conditionals but that's true of just about everything relating to this question). As such C# built on the already normal way to deal with one situation where we want to hit more than one block of code in a switch, and just generalised it to cover fall-through as well. It also made both cases more convenient and self-documenting, since we have to add a new label in C but can use the case as a label in C#. In C# we can get rid of the below_six label and use goto case 5 which is clearer as to what we are doing. (We'd also have to add break for the default, which I left out just to make the above C code clearly not C# code).

In summary therefore:

  1. C# no longer relates to unoptimised compiler output as directly as C code did 40 years ago (nor does C these days), which makes one of the inspirations of fall-through irrelevant.
  2. C# remains compatible with C in not just having implicit break, for easier learning of the language by those familiar with similar languages, and easier porting.
  3. C# removes a possible source of bugs or misunderstood code that has been well-documented as causing problems for the last four decades.
  4. C# makes existing best-practice with C (document fall through) enforceable by the compiler.
  5. C# makes the unusual case the one with more explicit code, the usual case the one with the code one just writes automatically.
  6. C# uses the same goto-based approach for hitting the same block from different case labels as is used in C. It just generalises it to some other cases.
  7. C# makes that goto-based approach more convenient, and clearer, than it is in C, by allowing case statements to act as labels.

All in all, a pretty reasonable design decision


*Some forms of BASIC would allow one to do the likes of GOTO (x AND 7) * 50 + 240 which while brittle and hence a particularly persuasive case for banning goto, does serve to show a higher-language equivalent of the sort of way that lower-level code can make a jump based on arithmetic upon a value, which is much more reasonable when it's the result of compilation rather than something that has to be maintained manually. Implementations of Duff's Device in particular lend themselves well to the equivalent machine code or IL because each block of instructions will often be the same length without needing the addition of nop fillers.

†Duff's Device comes up here again, as a reasonable exception. The fact that with that and similar patterns there's a repetition of operations serves to make the use of fall-through relatively clear even without an explicit comment to that effect.

Convert array of strings into a string in Java

Following is an example of Array to String conversion.

    public class ArrayToString
    {
public static void main(String[] args) { String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};

        String newString = Arrays.toString(strArray);

        newString = newString.substring(1, newString.length()-1);

        System.out.println("New New String: " + newString);
    }
}

SVN remains in conflict?

I had the same issue on linux, but I couldn't fix it with the accepted answer. I was able to solve it by using cd to go to the correct folder and then executing:

svn remove --force filename  
syn resolve --accept=working filename  
svn up

That's all.

How to create a generic array in Java?

The example is using Java reflection to create an array. Doing this is generally not recommended, since it isn't typesafe. Instead, what you should do is just use an internal List, and avoid the array at all.

python max function using 'key' and lambda expression

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

Can anonymous class implement interface?

The best solution is just not to use anonymous classes.

public class Test
{
    class DummyInterfaceImplementor : IDummyInterface
    {
        public string A { get; set; }
        public string B { get; set; }
    }

    public void WillThisWork()
    {
        var source = new DummySource[0];
        var values = from value in source
                     select new DummyInterfaceImplementor()
                     {
                         A = value.A,
                         B = value.C + "_" + value.D
                     };

        DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());

    }

    public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
    {
        foreach (var value in values)
        {
            Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
        }
    }
}

Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.

Add border-bottom to table row <tr>

No CSS border bottom:

<table>
    <thead>
        <tr>
            <th>Title</th>
        </tr>
        <tr>
            <th>
                <hr>
            </th>
        </tr>
    </thead>
</table>

AngularJS - Multiple ng-view in single template

I believe you can accomplish it by just having single ng-view. In the main template you can have ng-include sections for sub views, then in the main controller define model properties for each sub template. So that they will bind automatically to ng-include sections. This is same as having multiple ng-view

You can check the example given in ng-include documentation

in the example when you change the template from dropdown list it changes the content. Here assume you have one main ng-view and instead of manually selecting sub content by selecting drop down, you do it as when main view is loaded.

Git push requires username and password

When you use https for Git pull & push, just configure remote.origin.url for your project, to avoid input username (or/and password) every time you push.

How to configure remote.origin.url:

URL format:
    https://{username:password@}github.com/{owner}/{repo}

Parameters in URL:

* username 
Optional, the username to use when needed.
authentication, if specified, no need to enter username again when need authentication. Don't use email; use your username that has no "@", otherwise the URL can't be parsed correctly, * password optional, the password to use when need authentication. If specified, there isn't any need to enter the password again when needing authentication. Tip: this value is stored as plain text, so for security concerns, don't specify this parameter, * e.g git config remote.origin.url https://[email protected]/eric/myproject

@Update - using ssh

I think using ssh protocol is a better solution than https, even though the setup step is a little more complex.

Rough steps:

  • Create ssh keys using command, e.g ssh-keygen on Linux, on windows msysgit provide similar commands.
  • Keep the private key on the local machine at a proper location, e.g., ~/.ssh. And add it to the ssh agent via ssh-add command.
  • Upload the public key to the Git server.
  • Change remote.origin.url of the Git repository to ssh style, e.g., [email protected]:myaccount/myrepo.git
  • Then when pull or push, there isn't any need to enter the username or password ever.

Tips:

  • If your ssh key has a passphrase, then you need to input it on first use of the key after each restart of your machine, by default.

@Update - Switch between https and ssh protocol.

Simply changing remote.origin.url will be enough, or you can edit repo_home/.git/config directly to change the value (e.g using vi on Linux).

Usually I add a line for each protocol, and comment out one of them using #.

E.g.

[remote "origin"]
        url = [email protected]:myaccount/myrepo.git
        # url = https://[email protected]/myaccount/myrepo.git
        fetch = +refs/heads/*:refs/remotes/origin/*

What does the construct x = x || y mean?

Basically it checks if the value before the || evaluates to true, if yes, it takes this value, if not, it takes the value after the ||.

Values for which it will take the value after the || (as far as i remember):

  • undefined
  • false
  • 0
  • '' (Null or Null string)

How to access full source of old commit in BitBucket?

You can view the source of the file up to a particular commit by appending ?until=<sha-of-commit> in the URL (after the file name).

java how to use classes in other package?

It should be like import package_name.Class_Name --> If you want to import a specific class (or)

import package_name.* --> To import all classes in a package

How to open local file on Jupyter?

To start Jupyter Notebook in Windows:

  • open a Windows cmd (win + R and return cmd)
  • change directory to the desired file path (cd file-path)
  • give command jupyter notebook

You can further navigate from the UI of Jupyter notebook after you launch it (if you are not directly launching the right file.)
OR you can directly drag and drop the file to the cmd, to open the file.

C:\Users\kushalatreya>jupyter notebook "C:\Users\kushalatreya\Downloads\Material\PythonCourseFolder\PythonCourse-DataTypes.ipynb"

Executing multiple commands from a Windows cmd script

I don't know the direct answer to your question, but if you do a lot of these scripts, it might be worth learning a more powerful language like perl. Free implementations exist for Windows (e.g. activestate, cygwin). I've found it worth the initial effort for my own tasks.

Edit:

As suggested by @Ferruccio, if you can't install extra software, consider vbscript and/or javascript. They're built into the Windows scripting host.

declaring a priority_queue in c++ with a custom comparator

The third template parameter must be a class who has operator()(Node,Node) overloaded. So you will have to create a class this way:

class ComparisonClass {
    bool operator() (Node, Node) {
        //comparison code here
    }
};

And then you will use this class as the third template parameter like this:

priority_queue<Node, vector<Node>, ComparisonClass> q;

Regex for numbers only

If you need to tolerate decimal point and thousand marker

var regex = new Regex(@"^-?[0-9][0-9,\.]+$");

You will need a "-", if the number can go negative.

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

Remove array element based on object property

Iterate through the array, and splice out the ones you don't want. For easier use, iterate backwards so you don't have to take into account the live nature of the array:

for (var i = myArray.length - 1; i >= 0; --i) {
    if (myArray[i].field == "money") {
        myArray.splice(i,1);
    }
}

enum to string in modern C++11 / C++14 / C++17 and future C++20

For C++17 C++20, you will be interested in the work of the Reflection Study Group (SG7). There is a parallel series of papers covering wording (P0194) and rationale, design and evolution (P0385). (Links resolve to the latest paper in each series.)

As of P0194r2 (2016-10-15), the syntax would use the proposed reflexpr keyword:

meta::get_base_name_v<
  meta::get_element_m<
    meta::get_enumerators_m<reflexpr(MyEnum)>,
    0>
  >

For example (adapted from Matus Choclik's reflexpr branch of clang):

#include <reflexpr>
#include <iostream>

enum MyEnum { AAA = 1, BBB, CCC = 99 };

int main()
{
  auto name_of_MyEnum_0 = 
    std::meta::get_base_name_v<
      std::meta::get_element_m<
        std::meta::get_enumerators_m<reflexpr(MyEnum)>,
        0>
    >;

  // prints "AAA"
  std::cout << name_of_MyEnum_0 << std::endl;
}

Static reflection failed to make it into C++17 (rather, into the probably-final draft presented at the November 2016 standards meeting in Issaquah) but there is confidence that it will make it into C++20; from Herb Sutter's trip report:

In particular, the Reflection study group reviewed the latest merged static reflection proposal and found it ready to enter the main Evolution groups at our next meeting to start considering the unified static reflection proposal for a TS or for the next standard.

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

How can you make a custom keyboard in Android?

First of all you will need a keyboard.xml file which will be placed in the res/xml folder (if the folder does not exist, created it).

<?xml version="1.0" encoding="utf-8"?> 
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="15%p"
    android:keyHeight="15%p" >

    <Row>
        <Key android:codes="1"    android:keyLabel="1" android:horizontalGap="4%p"/>
        <Key android:codes="2"    android:keyLabel="2" android:horizontalGap="4%p"/>
        <Key android:codes="3"    android:keyLabel="3" android:horizontalGap="4%p" />
        <Key android:codes="4"    android:keyLabel="4" android:horizontalGap="4%p" />
        <Key android:codes="5"    android:keyLabel="5" android:horizontalGap="4%p" />
    </Row>
    <Row>
        <Key android:codes="6"    android:keyLabel="6" android:horizontalGap="4%p"/>
        <Key android:codes="7"    android:keyLabel="7" android:horizontalGap="4%p"/>
        <Key android:codes="8"    android:keyLabel="8" android:horizontalGap="4%p" />
        <Key android:codes="9"    android:keyLabel="9" android:horizontalGap="4%p" />
        <Key android:codes="0"    android:keyLabel="0" android:horizontalGap="4%p" />
    </Row>

    <Row>
        <Key android:codes="-1"    android:keyIcon="@drawable/backspace" android:keyWidth="34%p" android:horizontalGap="4%p"/>
        <Key android:codes="100"    android:keyLabel="Enter" android:keyWidth="53%p" android:horizontalGap="4%p"/>
    </Row>
 </Keyboard>

**Note that you will have to create the backspace drawable and place it in the res/drawable-ldpi folder with a very small size (like 18x18 pixels)

Then in the xml file that you want it to be used (where your TextView is in) you should add the following code:

<RelativeLayout
 ...
>

        .....


        <android.inputmethodservice.KeyboardView
             android:id="@+id/keyboardview"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true"
             android:layout_centerHorizontal="true"
             android:focusable="true"
             android:focusableInTouchMode="true"
             android:visibility="gone" 
         />
         
        ......


</RelativeLayout>

**Note that the xml file that you will place the android.inputmethodservice.KeyboardView in, has to be RelativeLayout in order to be able to set the alignParentBottom="true" (Usually the keyboards are presented in the bottom of the screen)

Then you need to add the following code in the onCreate function of the Activity that handles the TextView you want to attach the keyboard to

    // Create the Keyboard
    mKeyboard= new Keyboard(this,R.xml.keyboard);

    // Lookup the KeyboardView
    mKeyboardView= (KeyboardView)findViewById(R.id.keyboardview);
    // Attach the keyboard to the view
    mKeyboardView.setKeyboard( mKeyboard );
    
    // Do not show the preview balloons
    //mKeyboardView.setPreviewEnabled(false);
    
    // Install the key handler
    mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);

**Note that mKeyboard and mKeyboardView are private class variables that you have to create.

Then you need the following function for opening the keyboard ( you must associate it with the TextView through the onClick xml property)

    public void openKeyboard(View v)
    {
       mKeyboardView.setVisibility(View.VISIBLE);
       mKeyboardView.setEnabled(true);
       if( v!=null)((InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

And finally you need the OnKeyboardActionListener that will handle your events

private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
    @Override public void onKey(int primaryCode, int[] keyCodes) 
    {
         //Here check the primaryCode to see which key is pressed 
         //based on the android:codes property
         if(primaryCode==1)
         {
            Log.i("Key","You just pressed 1 button");
         }
    }

    @Override public void onPress(int arg0) {
    }

    @Override public void onRelease(int primaryCode) {
    }

    @Override public void onText(CharSequence text) {
    }

    @Override public void swipeDown() {
    }

    @Override public void swipeLeft() {
    }

    @Override public void swipeRight() {
    }

    @Override public void swipeUp() {
    }
};

Hope that helps!!!

Most of the code found here

____________________________________________________________-

EDIT:

Since KeyboardView is depreciated since API level 29, you can find its code in this website and create a class in your code before implementing the keyboard as described above.

How to define dimens.xml for every different screen size in android?

we want to see the changes of required view size in different screens.

We need to create a different values folders for different screens and put dimens.xml file based on screen densities.

I have taken one TextView and observed the changes when i changed dimens.xml in different values folders.

Please follow the process

normal - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - xhdpi \ dimens.xml

nexus 5X ( 5.2" * 1080 * 1920 : 420dpi )

nexus 6P ( 5.7" * 1440 * 2560 : 560dpi)

nexus 6 ( 6.0" * 1440 * 2560 : 560dpi)

nexus 5 (5.0", 1080 1920 : xxhdpi)

nexus 4 (4.7", 768 * 1280 : xhdpi)

Galaxy nexus (4.7", 720 * 1280 : xhdpi)

4.65" 720p ( 720 * 1280 : xhdpi )

4.7" WXGA ( 1280 * 720 : Xhdpi )

Xlarge - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the Xlarge - xhdpi \ dimens.xml

nexus 9 ( 8.9", 2048 * 1556 : xhdpi)

nexus 10 (10.1", 2560 * 1600 : xhdpi)

large - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - xhdpi \ dimens.xml

nexus 7 ( 7.0", 1200 * 1920: xhdpi)

nexus 7 (2012) (7.0", 800 * 1280 : tvdpi)

The below screens are visible in " Search Generic Phones and Tablets "

large - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - mdpi \ dimens.xml

5.1" WVGA ( 480 * 800 : mdpi )

5.4" FWVGA ( 480 * 854 : mdpi )

7.0" WSVGA (Tablet) ( 1024 * 600 : mdpi )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

nexus s ( 4.0", 480 * 800 : hdpi )

nexus one ( 3.7", 480 * 800: hdpi)

small - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the small - ldpi \ dimens.xml

2.7" QVGA Slider ( 240 * 320 : ldpi )

2.7" QVGA ( 240 * 320 : ldpi )

xlarge - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the xlarge - mdpi \ dimens.xml

10.1" WXGA ( tABLET) ( 1280 * 800 : MDPI )

normal - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - ldpi \ dimens.xml

3.3" WQVGA ( 240 * 400 : LDPI )

3.4" WQVGA ( 240 * 432 : LDPI )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

4.0" WVGA ( 480 * 800 : hdpi )

3.7" WVGA ( 480 * 800 : hdpi )

3.7" FWVGA Slider ( 480 * 854 : hdpi )

normal - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - mdpi \ dimens.xml

3.2" HVGA Slider ( ADP1 ) ( 320 * 480 : MDPI )

3.2" QVGA ( ADP2 ) ( 320 * 480 : MDPI )

how to display variable value in alert box?

Clean way with no jQuery:

function check(some_id) {
    var content = document.getElementById(some_id).childNodes[0].nodeValue;
    alert(content);
}

This is assuming each span has only the value as a child and no embedded HTML.

Is there any use for unique_ptr with array?

unique_ptr<char[]> can be used where you want the performance of C and convenience of C++. Consider you need to operate on millions (ok, billions if you don't trust yet) of strings. Storing each of them in a separate string or vector<char> object would be a disaster for the memory (heap) management routines. Especially if you need to allocate and delete different strings many times.

However, you can allocate a single buffer for storing that many strings. You wouldn't like char* buffer = (char*)malloc(total_size); for obvious reasons (if not obvious, search for "why use smart ptrs"). You would rather like unique_ptr<char[]> buffer(new char[total_size]);

By analogy, the same performance&convenience considerations apply to non-char data (consider millions of vectors/matrices/objects).

How can I "disable" zoom on a mobile web page?

The solution using a meta-tag did not work for me (tested on Chrome win10 and safari IOS 14.3), and I also believe that the concerns regarding accessibility, as mentioned by Jack and others, should be honored.

My solution is to disable zooming only on elements that are damaged by the default zoom.

I did this by registering event listeners for zoom-gestures and using event.preventDefault() to suppress the browsers default zoom-behavior.

This needs to be done with several events (touch gestures, mouse wheel and keys). The following snippet is an example for the mouse wheel and pinch gestures on touchpads:

noteSheetCanvas.addEventListener("wheel", e => {
        // suppress browsers default zoom-behavior:
        e.preventDefault();

        // execution my own custom zooming-behavior:
        if (e.deltaY > 0) {
            this._zoom(1);
        } else {
            this._zoom(-1);
        }
    });

How to detect touch gestures is described here: https://stackoverflow.com/a/11183333/1134856

I used this to keep the standard zooming behavior for most parts of my application and to define custom zooming-behavior on a canvas-element.

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

How can I dynamically switch web service addresses in .NET without a recompile?

Just a note about difference beetween static and dynamic.

  • Static: you must set URL property every time you call web service. This because base URL if web service is in the proxy class constructor.
  • Dynamic: a special configuration key will be created for you in your web.config file. By default proxy class will read URL from this key.

When to use: Java 8+ interface default method, vs. abstract method

Although its an old question let me give my input on it as well.

  1. abstract class: Inside abstract class we can declare instance variables, which are required to the child class

    Interface: Inside interface every variables is always public static and final we cannot declare instance variables

  2. abstract class: Abstract class can talk about state of object

    Interface: Interface can never talk about state of object

  3. abstract class: Inside Abstract class we can declare constructors

    Interface: Inside interface we cannot declare constructors as purpose of
    constructors is to initialize instance variables. So what is the need of constructor there if we cannot have instance variables in interfaces.

  4. abstract class: Inside abstract class we can declare instance and static blocks

    Interface: Interfaces cannot have instance and static blocks.

  5. abstract class: Abstract class cannot refer lambda expression

    Interfaces: Interfaces with single abstract method can refer lambda expression

  6. abstract class: Inside abstract class we can override OBJECT CLASS methods

    Interfaces: We cannot override OBJECT CLASS methods inside interfaces.

I will end on the note that:

Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

Android ADB device offline, can't issue commands

I ran to through same problem this fixed for me. connect your phone via usb first then make sure you check your mobile ip which is under settings >> about phone >> status run the following commands.


adb kill-server
adb start-server
adb tcpip 5555 //it resets port so put port you want to connect
adb connect 192.168.1.30:5555 //ip:port of your mobile to connect
adb devices //you will be connected over wifi

Sending arrays with Intent.putExtra

final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}

How do I call a dynamically-named method in Javascript?

Try These

Call Functions With Dynamic Names, like this:

let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()

with parameters:

let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()

Run Dynamic Code:

let some_code = "alert('hahaha');";
(new Function(some_code))()

Why did I get the compile error "Use of unassigned local variable"?

Local variables are not automatically initialized. That only happens with instance-level variables.

You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the new operator.

The code you've shown does indeed attempt to use the value of the variable tmpCnt before it is initialized to anything, and the compiler rightly warns about it.

JavaScript: How to get parent element by selector?

Here's a recursive solution:

function closest(el, selector, stopSelector) {
  if(!el || !el.parentElement) return null
  else if(stopSelector && el.parentElement.matches(stopSelector)) return null
  else if(el.parentElement.matches(selector)) return el.parentElement
  else return closest(el.parentElement, selector, stopSelector)
}

Why does typeof array with objects return "object" and not "array"?

Quoting the spec

15.4 Array Objects

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

And here's a table for typeof

enter image description here


To add some background, there are two data types in JavaScript:

  1. Primitive Data types - This includes null, undefined, string, boolean, number and object.
  2. Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.

An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.

An array can be considered to be an object with the following properties/keys:

  1. Length - This can be 0 or above (non-negative).
  2. The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.

Hope this helped shed more light on why typeof Array returns an object. Cheers!

How would I find the second largest salary from the employee table?

select max(Emp_Sal) 
from Employee a
where 1 = ( select count(*) 
         from Employee b
         where b.Emp_Sal > a.Emp_Sal)

Yes running man.

Linq Query Group By and Selecting First Items

First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.

Set up your variable like this:

IEnumerable<IEnumerable<string>> data = new[] {
    new[]{"...", "...", "..."},
    ... etc ...
};

Then you'd simply go:

var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null); 

The Where makes sure it prunes any nulls if you have an empty list as an item inside.

Alternatively you can implement it as:

string[][] = new[] {
    new[]{"...","...","..."},
    new[]{"...","...","..."},
    ... etc ...
};

This could be used similarly to a [x,y] array but it's used like this: [x][y]

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

From documentation:

More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection. You can determine whether you are experiencing this more uncommon cause by using SHOW STATUS LIKE 'aborted_connections'. It will increase by one for each initial connection attempt that the server aborts. You may see “reading authorization packet” as part of the error message; if so, that also suggests that this is the solution that you need.

Try increasing connect_timeout in your my.cnf file

Another style:

MySQL: Lost connection to MySQL server at 'reading initial communication packet'

  1. At some point, it was impossible for remote clients to connect to the MySQL server.

  2. The client (some application on a Windows platform) gave a vague description like Connection unexpectedly terminated.

  3. When remotely logging in with the MySQL client the following error appeared:

    ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

On FreeBSD this happens because there was no match found in /etc/hosts.allow. Adding the following line before the line saying ALL:ALL fixes this:

mysqld: ALL: allow

On non-FreeBSD Unix systems, it is worth to check the files /etc/hosts.allow and /etc/hosts.deny. If you are restricting connections, make sure this line is in /etc/hosts.allow:

mysqld: ALL

or check if the host is listed in /etc/hosts.deny.

In Arch Linux, a similar line can be added to /etc/hosts.allow:

mysqld: ALL

Error: Unable to run mksdcard SDK tool

This worked for me on Ubuntu 15.04

sudo aptitude install lib32stdc++6

Firstly, I installed aptitude, which helps in installing other dependencies too.

Testing for empty or nil-value string

If you're in Rails, .blank? should be the method you are looking for:

a = nil
b = []
c = ""

a.blank? #=> true
b.blank? #=> true
c.blank? #=> true

d = "1"
e = ["1"]

d.blank? #=> false
e.blank? #=> false

So the answer would be:

variable = id if variable.blank?

How do I set the colour of a label (coloured text) in Java?

JLabel label = new JLabel ("Text Color: Red");
label.setForeground (Color.red);

this should work

Unix shell script find out which directory the script file resides?

Assuming you're using bash

#!/bin/bash

current_dir=$(pwd)
script_dir=$(dirname "$0")

echo $current_dir
echo $script_dir

This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from / with the script in /home/mez/, it outputs

/
/home/mez

Remember, when assigning variables from the output of a command, wrap the command in $( and ) - or you won't get the desired output.

Batch script loop

You could also try this instead of a for loop:

set count=0
:loop
set /a count=%count%+1
(Commands here)
if %count% neq 100 goto loop
(Commands after loop)

It's quite small and it's what I use all the time.

Visual Studio Code Tab Key does not insert a tab

Click "Tab Moves Focus" at the bottom right in the status bar.

I believe I had clicked on ctrl+M. When doing this, the "Tab Moves Focus" tab/button showed up at the bottom right. Clicking on that makes it go away and starts working again.

enter image description here