Programs & Examples On #Gwt mvp

This is an implementation of the Model-View-Presenter pattern for GWT.

How to subtract date/time in JavaScript?

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

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

I really like StartExplorer but it is a contextual launcher rather than in - IDE shell so not sure if that is what you want

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

android:layout_height 50% of the screen size

To achieve this feat, define a outer linear layout with a weightSum={amount of weight to distribute}.

it defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.Another example would be set weightSum=2, and if the two children set layout_weight=1 then each would get 50% of the available space.

WeightSum is dependent on the amount of children in the parent layout.

How to make div go behind another div?

To answer the question in a general manner:

Using z-index will allow you to control this. see z-index at csstricks.

The element of higher z-index will be displayed on top of elements of lower z-index.

For instance, take the following HTML:

<div id="first">first</div>
<div id="second">second</div>

If I have the following CSS:

#first {
    position: fixed;
    z-index: 2;
}

#second {
    position: fixed;
    z-index: 1;
}

#first wil be on top of #second.

But specifically in your case:

The div element is a child of the div that you wish to put in front. This is not logically possible.

How to declare strings in C

This link should satisfy your curiosity.

Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.

But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.

How to transform numpy.matrix or array to scipy sparse matrix

You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.

>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])

>>> A
array([[1, 2, 0],
       [0, 0, 3],
       [1, 0, 4]])

>>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)

>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>

>>> print sA
  (0, 0)        1
  (0, 1)        2
  (1, 2)        3
  (2, 0)        1
  (2, 2)        4

Is it possible to program Android to act as physical USB keyboard?

Your Android already identifies with a VID/PID when plugged into a host. It already has an interface for Mass Storage. You would need to hack the driver at a low level to support a 2nd interface for 03:01 HID. Then it would just be a question of pushing scancodes to the modified driver. This wouldn't be simple, but it would be a neat hack. One use would be for typing long random passwords for logins.

How to change CSS using jQuery?

$(".radioValue").css({"background-color":"-webkit-linear-gradient(#e9e9e9,rgba(255, 255, 255, 0.43137254901960786),#e9e9e9)","color":"#454545", "padding": "8px"});

How to read values from the querystring with ASP.NET Core?

You can just create an object like this:

public class SomeQuery
{
    public string SomeParameter { get; set; }
    public int? SomeParameter2 { get; set; }
}

And then in controller just make something like that:

[HttpGet]
public IActionResult FindSomething([FromQuery] SomeQuery query)
{
    // Your implementation goes here..
}

Even better, you can create API model from:

[HttpGet]
public IActionResult GetSomething([FromRoute] int someId, [FromQuery] SomeQuery query)

to:

[HttpGet]
public IActionResult GetSomething(ApiModel model)

public class ApiModel
{
    [FromRoute]
    public int SomeId { get; set; }
    [FromQuery]
    public string SomeParameter { get; set; }
    [FromQuery]
    public int? SomeParameter2 { get; set; }
}

ASP.Net 2012 Unobtrusive Validation with jQuery

Add a reference to Microsoft.JScript in your application in your web.config as below :

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="Microsoft.JScript, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
  </appSettings>
</configuration>

How to schedule a stored procedure in MySQL

I used this query and it worked for me:

CREATE EVENT `exec`
  ON SCHEDULE EVERY 5 SECOND
  STARTS '2013-02-10 00:00:00'
  ENDS '2015-02-28 00:00:00'
  ON COMPLETION NOT PRESERVE ENABLE
DO 
  call delete_rows_links();

How do I import a .sql file in mysql database using PHP?

<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "demo1"; //Change Your Database Name
$conn = new mysqli($host, $uname, $pass, $database);
$filename = 'users.sql'; //How to Create SQL File Step : url:http://localhost/phpmyadmin->detabase select->table select->Export(In Upper Toolbar)->Go:DOWNLOAD .SQL FILE
$op_data = '';
$lines = file($filename);
foreach ($lines as $line)
{
    if (substr($line, 0, 2) == '--' || $line == '')//This IF Remove Comment Inside SQL FILE
    {
        continue;
    }
    $op_data .= $line;
    if (substr(trim($line), -1, 1) == ';')//Breack Line Upto ';' NEW QUERY
    {
        $conn->query($op_data);
        $op_data = '';
    }
}
echo "Table Created Inside " . $database . " Database.......";
?>

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Is this what you are looking for? Otherwise, let me know and I will remove this post.

Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect

Demo: http://www.stoimen.com/jquery.client.plugin/

This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.

For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html

And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js

Concat a string to SELECT * MySql

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

How do I print the content of a .txt file in Python?

It's pretty simple

#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)

Presenting snapshot from my visual studio IDE.

enter image description here

Replacing spaces with underscores in JavaScript?

try this:

key=key.replace(/ /g,"_");

that'll do a global find/replace

javascript replace

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

As others have already mentioned you are required to provide a default constructor public Employee(){} in your Employee class.

What happens is that the compiler automatically provides a no-argument, default constructor for any class without constructors. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor. In this case you are declaring a constructor in your class Employee therefore you must provide also the no-argument constructor.

Having said that Employee class should look like this:

Your class Employee

import java.util.Date;

public class Employee
{
      private String name, number;
      private Date date;

      public Employee(){} // No-argument Constructor

      public Employee(String name, String number, Date date)
      {
            setName(name);
            setNumber(number);
            setDate(date);
      }

      public void setName(String n)
      {
            name = n;
      }
      public void setNumber(String n)
      {
            number = n;
            // you can check the format here for correctness
      }
      public void setDate(Date d)
      {
            date = d;
      }

      public String getName()
      {
            return name;
      }
      public String getNumber()
      {
            return number;
      }
      public Date getDate()
      {
            return date;
      }
}

Here is the Java Oracle tutorial - Providing Constructors for Your Classes chapter. Go through it and you will have a clearer idea of what is going on.

Sorting using Comparator- Descending order (User defined classes)

I would create a comparator for the person class that can be parametrized with a certain sorting behaviour. Here I can set the sorting order but it can be modified to allow sorting for other person attributes as well.

public class PersonComparator implements Comparator<Person> {

  public enum SortOrder {ASCENDING, DESCENDING}

  private SortOrder sortOrder;

  public PersonComparator(SortOrder sortOrder) {
    this.sortOrder = sortOrder;
  }

  @Override
  public int compare(Person person1, Person person2) {
    Integer age1 = person1.getAge();
    Integer age2 = person2.getAge();
    int compare = Math.signum(age1.compareTo(age2));

    if (sortOrder == ASCENDING) {
      return compare;
    } else {
      return compare * (-1);
    }
  }
}

(hope it compiles now, I have no IDE or JDK at hand, coded 'blind')

Edit

Thanks to Thomas, edited the code. I wouldn't say that the usage of Math.signum is good, performant, effective, but I'd like to keep it as a reminder, that the compareTo method can return any integer and multiplying by (-1) will fail if the implementation returns Integer.MIN_INTEGER... And I removed the setter because it's cheap enough to construct a new PersonComparator just when it's needed.

But I keep the boxing because it shows that I rely on an existing Comparable implementation. Could have done something like Comparable<Integer> age1 = new Integer(person1.getAge()); but that looked too ugly. The idea was to show a pattern which could easily be adapted to other Person attributes, like name, birthday as Date and so on.

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

function range(j, k) { 
    return Array
        .apply(null, Array((k - j) + 1))
        .map(function(_, n){ return n + j; }); 
}

this is roughly equivalent to

function range(j, k) { 
    var targetLength = (k - j) + 1;
    var a = Array(targetLength);
    var b = Array.apply(null, a);
    var c = b.map(function(_, n){ return n + j; });
    return c;
}

breaking it down:

var targetLength = (k - j) + 1;

var a = Array(targetLength);

this creates a sparse matrix of the correct nominal length. Now the problem with a sparse matrix is that although it has the correct nominal length, it has no actual elements, so, for

j = 7, k = 13

console.log(a);

gives us

Array [ <7 empty slots> ]

Then

var b = Array.apply(null, a);

passes the sparse matrix as an argument list to the Array constructor, which produces a dense matrix of (actual) length targetLength, where all elements have undefined value. The first argument is the 'this' value for the the array constructor function execution context, and plays no role here, and so is null.

So now,

 console.log(b);

yields

 Array [ undefined, undefined, undefined, undefined, undefined, undefined, undefined ]

finally

var c = b.map(function(_, n){ return n + j; });

makes use of the fact that the Array.map function passes: 1. the value of the current element and 2. the index of the current element, to the map delegate/callback. The first argument is discarded, while the second can then be used to set the correct sequence value, after adjusting for the start offset.

So then

console.log(c);

yields

 Array [ 7, 8, 9, 10, 11, 12, 13 ]

how to make a full screen div, and prevent size to be changed by content?

<html>
<div style="width:100%; height:100%; position:fixed; left:0;top:0;overflow:hidden;">

</div>
</html>

Execute action when back bar button of UINavigationController is pressed

just do control + drag the bar item to below func. work like charm

@IBAction func done(sender: AnyObject) {
    if((self.presentingViewController) != nil){
        self.dismiss(animated: false, completion: nil)
        print("done")
    }
}

enter image description here

RecyclerView inside ScrollView is not working

If you put RecyclerView inside NestedScrollView and enable recyclerView.setNestedScrollingEnabled(false);, scrolling will working well.
However, there is a problem

RecyclerView don't recycle

For example, your RecyclerView (inside NestedScrollView or ScrollView) have 100 item.
When Activity launch, 100 item will create (onCreateViewHolder and onBindViewHolder of 100 item will called at same time).
Example, for each item, you will load a large image from API => activity created -> 100 image will load.
It make starting Activity slowness and lagging.
Possible solution:
- Thinking about using RecyclerView with multiple type.

However, if in your case, there are just a few item in RecyclerView and recycle or don't recycle don't affect performance a lot, you can use RecyclerView inside ScrollView for simple

MAX function in where clause mysql

Do you want the first and last name of the row with the largest id?

If so (and you were missing a FROM clause):

SELECT firstname, lastname, id
FROM foo
ORDER BY id DESC
LIMIT 1;

Does PHP have threading?

There is a Threading extension being activley developed based on PThreads that looks very promising at https://github.com/krakjoe/pthreads

How can I brew link a specific version?

if @simon's answer is not working in some of the mac's please follow the below process.

If you have already installed swiftgen using the following commands:

$ brew update $ brew install swiftgen

then follow the steps below in order to run swiftgen with older version.

Step 1: brew uninstall swiftgen Step 2: Navigate to: https://github.com/SwiftGen/SwiftGen/releases and download the swiftgen with version: swiftgen-4.2.0.zip.

Unzip the package in any of the directories.

Step 3: Execute the following in a terminal:

$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/

$ swiftgen --version

You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)

enter image description here

How to return multiple objects from a Java method?

Why not create a WhateverFunctionResult object that contains your results, and the logic required to parse these results, iterate over then etc. It seems to me that either:

  1. These results objects are intimately tied together/related and belong together, or:
  2. they are unrelated, in which case your function isn't well defined in terms of what it's trying to do (i.e. doing two different things)

I see this sort of issue crop up again and again. Don't be afraid to create your own container/result classes that contain the data and the associated functionality to handle this. If you simply pass the stuff around in a HashMap or similar, then your clients have to pull this map apart and grok the contents each time they want to use the results.

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

HTML table with horizontal scrolling (first column fixed)

Take a look at this JQuery plugin:

http://fixedheadertable.com

It adds vertical (fixed header row) or horizontal (fixed first column) scrolling to an existing HTML table. There is a demo you can check for both cases of scrolling.

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How do I put text on ProgressBar?

I wold create a control named for example InfoProgresBar, that provide this functionality with a label or two (Main Job, Current Job) and ProgressBar and use it instead of that ProgressBar.

Nullable property to entity field, Entity Framework through Code First

Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

This worked for me though:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}

WorksheetFunction.CountA - not working post upgrade to Office 2010

I'm not sure exactly what your problem is, because I cannot get your code to work as written. Two things seem evident:

  1. It appears you are relying on VBA to determine variable types and modify accordingly. This can get confusing if you are not careful, because VBA may assign a variable type you did not intend. In your code, a type of Range should be assigned to myRange. Since a Range type is an object in VBA it needs to be Set, like this: Set myRange = Range("A:A")
  2. Your use of the worksheet function CountA() should be called with .WorksheetFunction

If you are not doing it already, consider using the Option Explicit option at the top of your module, and typing your variables with Dim statements, as I have done below.

The following code works for me in 2010. Hopefully it works for you too:

Dim myRange As Range
Dim NumRows As Integer

Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)

Good Luck.

How to pass an array within a query string?

I don't think there's a standard.
Each web environment provides its own 'standard' for such things. Besides, the url is usually too short for anything (256 bytes limit on some browsers). Of course longer arrays/data can be send with POST requests.

However, there are some methods:

  1. There's a PHP way, which uses square brackets ([,]) in URL queries. For example a query such as ?array_name[]=item&array_name[]=item_2 has been said to work, despite being poorly documented, with PHP automatically converting it into an array. Source: https://stackoverflow.com/a/9547490/3787376

  2. Object data-interchange formats (e.g. JSON - official website, PHP documentation) can also be used if they have methods of converting variables to and from strings as JSON does.
    Also an url-encoder (available for most programming languages) is required for HTTP get requests to encode the string data correctly.

Although the "square brackets method" is simple and works, it is limited to PHP and arrays.
If other types of variable such as classes or passing variables within query strings in a language other than PHP is required, the JSON method is recommended.

Example in PHP of JSON method (method 2):

$myarray = array(2, 46, 34, "dfg");
$serialized = json_encode($myarray)
$data = 'myarray=' . rawurlencode($serialized);
// Send to page via cURL, header() or other service.

Code for receiving page (PHP):

$myarray = json_decode($_GET["myarray"]); // Or $_POST["myarray"] if a post request.

JPA Hibernate One-to-One relationship

I think you still need the primary key property in the OtherInfo class.

@Entity
public class OtherInfo {
    @Id
    public int id;

    @OneToOne(mappedBy="otherInfo")
    public Person person;

    rest of attributes ...
}

Also, you may need to add the @PrimaryKeyJoinColumn annotation to the other side of the mapping. I know that Hibernate uses this by default. But then I haven't used JPA annotations, which seem to require you to specify how the association wokrs.

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

Check whether an array is empty

Try to check it's size with sizeof if 0 no elements.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

$_ is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ... so $_ represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:

write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH

How to stop a setTimeout loop?

I know this is an old question, I'd like to post my approach anyway. This way you don't have to handle the 0 trick that T. J. Crowder expained.

var keepGoing = true;

function myLoop() {
    // ... Do something ...

    if(keepGoing) {
        setTimeout(myLoop, 1000);
    }
}

function startLoop() {
    keepGoing = true;
    myLoop();
}

function stopLoop() {
    keepGoing = false;
}

How can I create a two dimensional array in JavaScript?

This is my implementation of Multi-Dimension Array.

In this approach, I am creating a single dimension array

I have added a prototype function multi to Array object, Which can be used to create any dimension Array.

I have also added a prototype function index to Array object, Which can be used to get index in linear Array from multi-dimension indexes.

Creating a Array

//Equivalent to arr[I][J][K]..[] in C
var arr = new Array().multi(I,J,K,..);

Accessing array value at any index

//Equivalent in C arr[i][j][k];
var vaue = arr[arr.index(i,j,k)];

SNIPPET

_x000D_
_x000D_
/*_x000D_
   Storing array as single dimension _x000D_
   and access using Array.index(i,j,k,...)_x000D_
*/_x000D_
_x000D_
_x000D_
Array.prototype.multi = function(){_x000D_
 this.multi_size = arguments;_x000D_
 this.multi_len = 1_x000D_
 for(key in arguments) this.multi_len *=  arguments[key];_x000D_
 for(var i=0;i<this.multi_len;i++) this.push(0);_x000D_
 return this;_x000D_
}_x000D_
_x000D_
Array.prototype.index = function(){_x000D_
   var _size = this.multi_len;_x000D_
   var temp = 1;_x000D_
   var index = 0;_x000D_
   for(key in arguments) {_x000D_
      temp*=this.multi_size[key];_x000D_
      index+=(arguments[key]*(_size/temp))_x000D_
   }_x000D_
   return index;_x000D_
}_x000D_
_x000D_
// Now you can use the multi dimension array_x000D_
// A 3x3 2D Matrix_x000D_
_x000D_
var arr2d = new Array().multi(3,3); // A 2D Array_x000D_
arr2d[arr2d.index(1,1,1)]  = 5;_x000D_
console.log(arr2d[arr2d.index(1,1,1)]);_x000D_
_x000D_
// A 3x3x3 3D Matrix_x000D_
_x000D_
var arr3d = new Array().multi(3,3,3); // a 3D Array_x000D_
arr3d[arr3d.index(1,1,1)]  = 5;_x000D_
console.log(arr3d[arr3d.index(1,1,1)]);_x000D_
_x000D_
// A 4x3x3 4D Matrix_x000D_
var arr4d = new Array().multi(4,3,3,3); // a 4D Array_x000D_
arr4d[arr4d.index(4,0,0,1)]  = 5;_x000D_
console.log(arr4d[arr4d.index(4,0,0,1)]);
_x000D_
_x000D_
_x000D_

XSL xsl:template match="/"

The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.

To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.

Could I write "table" or any other html tag instead of "/" ?

Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.

Here a few links:

Python str vs unicode types

Your terminal happens to be configured to UTF-8.

The fact that printing a works is a coincidence; you are writing raw UTF-8 bytes to the terminal. a is a value of length two, containing two bytes, hex values C3 and A1, while ua is a unicode value of length one, containing a codepoint U+00E1.

This difference in length is one major reason to use Unicode values; you cannot easily measure the number of text characters in a byte string; the len() of a byte string tells you how many bytes were used, not how many characters were encoded.

You can see the difference when you encode the unicode value to different output encodings:

>>> a = 'á'
>>> ua = u'á'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> a
'\xc3\xa1'

Note that the first 256 codepoints of the Unicode standard match the Latin 1 standard, so the U+00E1 codepoint is encoded to Latin 1 as a byte with hex value E1.

Furthermore, Python uses escape codes in representations of unicode and byte strings alike, and low code points that are not printable ASCII are represented using \x.. escape values as well. This is why a Unicode string with a code point between 128 and 255 looks just like the Latin 1 encoding. If you have a unicode string with codepoints beyond U+00FF a different escape sequence, \u.... is used instead, with a four-digit hex value.

It looks like you don't yet fully understand what the difference is between Unicode and an encoding. Please do read the following articles before you continue:

Print content of JavaScript object?

This will give you very nice output with indented JSON object:

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));

The second argument alters the contents of the string before returning it. The third argument specifies how many spaces to use as white space for readability.

Algorithm to return all combinations of k elements from n

Short java solution:

import java.util.Arrays;

public class Combination {
    public static void main(String[] args){
        String[] arr = {"A","B","C","D","E","F"};
        combinations2(arr, 3, 0, new String[3]);
    }

    static void combinations2(String[] arr, int len, int startPosition, String[] result){
        if (len == 0){
            System.out.println(Arrays.toString(result));
            return;
        }       
        for (int i = startPosition; i <= arr.length-len; i++){
            result[result.length - len] = arr[i];
            combinations2(arr, len-1, i+1, result);
        }
    }       
}

Result will be

[A, B, C]
[A, B, D]
[A, B, E]
[A, B, F]
[A, C, D]
[A, C, E]
[A, C, F]
[A, D, E]
[A, D, F]
[A, E, F]
[B, C, D]
[B, C, E]
[B, C, F]
[B, D, E]
[B, D, F]
[B, E, F]
[C, D, E]
[C, D, F]
[C, E, F]
[D, E, F]

JQuery .hasClass for multiple values in an if statement

Try this:

if ($('html').hasClass('class1 class2')) {

// do stuff 

}

jQuery.each - Getting li elements inside an ul

First I think you need to fix your lists, as the first node of a <ul> must be a <li> (stackoverflow ref). Once that is setup you can do this:

// note this array has outer scope
var phrases = [];

$('.phrase').each(function(){
        // this is inner scope, in reference to the .phrase element
        var phrase = '';
        $(this).find('li').each(function(){
            // cache jquery var
            var current = $(this);
            // check if our current li has children (sub elements)
            // if it does, skip it
            // ps, you can work with this by seeing if the first child
            // is a UL with blank inside and odd your custom BLANK text
            if(current.children().size() > 0) {return true;}
            // add current text to our current phrase
            phrase += current.text();
        });
        // now that our current phrase is completely build we add it to our outer array
        phrases.push(phrase);
    });
    // note the comma in the alert shows separate phrases
    alert(phrases);

Working jsfiddle.

One thing is if you get the .text() of an upper level li you will get all sub level text with it.

Keeping an array will allow for many multiple phrases to be extracted.


EDIT:

This should work better with an empty UL with no LI:

// outer scope
var phrases = [];

$('.phrase').each(function(){
    // inner scope
    var phrase = '';
    $(this).find('li').each(function(){
        // cache jquery object
        var current = $(this);
        // check for sub levels
        if(current.children().size() > 0) {
            // check is sublevel is just empty UL
            var emptyULtest = current.children().eq(0); 
            if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
                phrase += ' -BLANK- '; //custom blank text
                return true;   
            } else {
             // else it is an actual sublevel with li's
             return true;   
            }
        }
        // if it gets to here it is actual li
        phrase += current.text();
    });
    phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);

Make absolute positioned div expand parent div height

There is a better way to do this now. You can use the bottom property.

    .my-element {
      position: absolute;
      bottom: 30px;
    }

get all the elements of a particular form

Use this

var theForm = document.forms['formname']
[].slice.call(theForm).forEach(function (el, i) {
    console.log(el.value);
});

The el stands for the particular form element. It is better to use this than the foreach loop, as the foreach loop also returns a function as one of the element. However this only returns the DOM elements of the form.

Java JDBC - How to connect to Oracle using Service Name instead of SID

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

So I would try:

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse's answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

Check if an array item is set in JS

var is a statement... so it's a reserved word... So just call it another way. And that's a better way of doing it (=== is better than ==)

if(typeof array[name] !== 'undefined') {
    alert("Has var");
} else {
    alert("Doesn't have var");
}

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

If it's reasonable to alter the original Map data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null key entries, if possible, before calling Jackson. That said...


To suppress serializing Map entries with null values:

Before Jackson 2.9

you can still make use of WRITE_NULL_MAP_VALUES, but note that it's moved to SerializationFeature:

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

Since Jackson 2.9

The WRITE_NULL_MAP_VALUES is deprecated, you can use the below equivalent:

mapper.setDefaultPropertyInclusion(
   JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))

To suppress serializing properties with null values, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To handle null Map keys, some custom serialization is necessary, as best I understand.

A simple approach to serialize null keys as empty strings (including complete examples of the two previously mentioned configurations):

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Map<String, Foo> foos = new HashMap<String, Foo>();
    foos.put("foo1", new Foo("foo1"));
    foos.put("foo2", new Foo(null));
    foos.put("foo3", null);
    foos.put(null, new Foo("foo4"));

    // System.out.println(new ObjectMapper().writeValueAsString(foos));
    // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
    System.out.println(mapper.writeValueAsString(foos));
    // output: 
    // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
  }
}

class MyNullKeySerializer extends JsonSerializer<Object>
{
  @Override
  public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) 
      throws IOException, JsonProcessingException
  {
    jsonGenerator.writeFieldName("");
  }
}

class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To suppress serializing Map entries with null keys, further custom serialization processing would be necessary.

Using JSON POST Request

Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).

Otherwise, you might want to go with another JS library like jQuery or Mootools.

Xcode 'CodeSign error: code signing is required'

Have you updated the firmware version of the iPhone you are testing on?

Word-wrap in an HTML table

It appears you need to set word-wrap:break-word; on a block element (div), with specified (non relative) width. Ex:

_x000D_
_x000D_
<table style="width: 100%;"><tr>_x000D_
    <td><div style="display:block; word-wrap: break-word; width: 40em;">loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</div></td>_x000D_
    <td><span style="display: inline;">Foo</span></td>_x000D_
</tr></table>
_x000D_
_x000D_
_x000D_

or using word-break:break-all per Abhishek Simon's suggestion.

Check if key exists and iterate the JSON array using Python

if "my_data" in my_json_data:
         print json.dumps(my_json_data["my_data"])

XML parsing of a variable string in JavaScript

Marknote is a nice lightweight cross-browser JavaScript XML parser. It's object-oriented and it's got plenty of examples, plus the API is documented. It's fairly new, but it has worked nicely in one of my projects so far. One thing I like about it is that it will read XML directly from strings or URLs and you can also use it to convert the XML into JSON.

Here's an example of what you can do with Marknote:

var str = '<books>' +
          '  <book title="A Tale of Two Cities"/>' +
          '  <book title="1984"/>' +
          '</books>';

var parser = new marknote.Parser();
var doc = parser.parse(str);

var bookEls = doc.getRootElement().getChildElements();

for (var i=0; i<bookEls.length; i++) {
    var bookEl = bookEls[i];
    // alerts "Element name is 'book' and book title is '...'"
    alert("Element name is '" + bookEl.getName() + 
        "' and book title is '" + 
        bookEl.getAttributeValue("title") + "'"
    );
}

psycopg2: insert multiple rows with one query

execute_batch has been added to psycopg2 since this question was posted.

It is slower than execute_values but simpler to use.

How much does it cost to develop an iPhone application?

The Barack Obama app took 22 days to develop from first code to release. Three developers (although not all of them were full time). 10 people total. Figure 500-1000 man hours. Contracting rates are $100-150/hr. Figure $50000-$150000. Compare your app to Obama.app and scale accordingly.

Do I really need to encode '&' as '&amp;'?

I think this has turned into more of a question of "why follow the spec when browser's don't care." Here is my generalized answer:

Standards are not a "present" thing. They are a "future" thing. If we, as developers, follow web standards, then browser vendors are more likely to correctly implement those standards, and we move closer to a completely interoperable web, where CSS hacks, feature detection, and browser detection are not necessary. Where we don't have to figure out why our layouts break in a particular browser, or how to work around that.

Specifically, if HTML5 does not require using &amp; in your specific situation, and you're using an HTML5 doctype (and also expecting your users to be using HTML5-compliant browsers), then there is no reason to do it.

How to len(generator())

Suppose we have a generator:

def gen():
    for i in range(10):
        yield i

We can wrap the generator, along with the known length, in an object:

import itertools
class LenGen(object):
    def __init__(self,gen,length):
        self.gen=gen
        self.length=length
    def __call__(self):
        return itertools.islice(self.gen(),self.length)
    def __len__(self):
        return self.length

lgen=LenGen(gen,10)

Instances of LenGen are generators themselves, since calling them returns an iterator.

Now we can use the lgen generator in place of gen, and access len(lgen) as well:

def new_gen():
    for i in lgen():
        yield float(i)/len(lgen)

for i in new_gen():
    print(i)

Convert Decimal to Varchar

Here's one way:

create table #work
(
  something decimal(8,3) not null 
)

insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )

select convert(varchar,convert(decimal(8,2),something))
from #work

if you want it right-aligned, something like this should do you:

select str(something,8,2) from #work

What does \d+ mean in regular expression terms?

\d is a digit, + is 1 or more, so a sequence of 1 or more digits

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

For an assembly project (ProjectName -> Build Dependencies -> Build Customizations -> masm (selected)), setting Generate Preprocessed Source Listing to True caused the problem for me too, clearing the setting fixed it. VS2013 here.

Update multiple columns in SQL

I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.

First, get the result of table2.

enter image description here

Next, unpivot it.

enter image description here

Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB

--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')

DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(    
    colName VARCHAR(255),
    val VARCHAR(255)
)

INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
    val
    FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id

SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot

SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + ''' 
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL

PRINT @TSQL result:

enter image description here

Python MYSQL update statement

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
   connect.commit()

tmux status bar configuration

I have been playing about with tmux today, trying to customised a little here and there, managed to get battery info displaying on the status right with a ruby script.

Copy the ruby script from http://natedickson.com/blog/2013/04/30/battery-status-in-tmux/ and save it as:

 battinfo.rb in ~/bin

To make it executable make sure to run:

chmod +x ~/bin/battinfo.rb

edit your ~/.tmux.config and include this line

set -g status-right "#[fg=colour155]#(pmset -g batt | ~/bin/battinfo.rb) | #[fg=colour45]%d %b %R"

JSON.parse unexpected token s

Because JSON has a string data type (which is practically anything between " and "). It does not have a data type that matches something

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

How to add leading zeros for for-loop in shell?

Use printf command to have 0 padding:

printf "%02d\n" $num

Your for loop will be like this:

for (( num=1; num<=5; num++ )); do printf "%02d\n" $num; done
01
02
03
04
05

Python != operation vs "is not"

First, let me go over a few terms. If you just want your question answered, scroll down to "Answering your question".

Definitions

Object identity: When you create an object, you can assign it to a variable. You can then also assign it to another variable. And another.

>>> button = Button()
>>> cancel = button
>>> close = button
>>> dismiss = button
>>> print(cancel is close)
True

In this case, cancel, close, and dismiss all refer to the same object in memory. You only created one Button object, and all three variables refer to this one object. We say that cancel, close, and dismiss all refer to identical objects; that is, they refer to one single object.

Object equality: When you compare two objects, you usually don't care that it refers to the exact same object in memory. With object equality, you can define your own rules for how two objects compare. When you write if a == b:, you are essentially saying if a.__eq__(b):. This lets you define a __eq__ method on a so that you can use your own comparison logic.

Rationale for equality comparisons

Rationale: Two objects have the exact same data, but are not identical. (They are not the same object in memory.) Example: Strings

>>> greeting = "It's a beautiful day in the neighbourhood."
>>> a = unicode(greeting)
>>> b = unicode(greeting)
>>> a is b
False
>>> a == b
True

Note: I use unicode strings here because Python is smart enough to reuse regular strings without creating new ones in memory.

Here, I have two unicode strings, a and b. They have the exact same content, but they are not the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the unicode object has implemented the __eq__ method.

class unicode(object):
    # ...

    def __eq__(self, other):
        if len(self) != len(other):
            return False

        for i, j in zip(self, other):
            if i != j:
                return False

        return True

Note: __eq__ on unicode is definitely implemented more efficiently than this.

Rationale: Two objects have different data, but are considered the same object if some key data is the same. Example: Most types of model data

>>> import datetime
>>> a = Monitor()
>>> a.make = "Dell"
>>> a.model = "E770s"
>>> a.owner = "Bob Jones"
>>> a.warranty_expiration = datetime.date(2030, 12, 31)
>>> b = Monitor()
>>> b.make = "Dell"
>>> b.model = "E770s"
>>> b.owner = "Sam Johnson"
>>> b.warranty_expiration = datetime.date(2005, 8, 22)
>>> a is b
False
>>> a == b
True

Here, I have two Dell monitors, a and b. They have the same make and model. However, they neither have the same data nor are the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the Monitor object implemented the __eq__ method.

class Monitor(object):
    # ...

    def __eq__(self, other):
        return self.make == other.make and self.model == other.model

Answering your question

When comparing to None, always use is not. None is a singleton in Python - there is only ever one instance of it in memory.

By comparing identity, this can be performed very quickly. Python checks whether the object you're referring to has the same memory address as the global None object - a very, very fast comparison of two numbers.

By comparing equality, Python has to look up whether your object has an __eq__ method. If it does not, it examines each superclass looking for an __eq__ method. If it finds one, Python calls it. This is especially bad if the __eq__ method is slow and doesn't immediately return when it notices that the other object is None.

Did you not implement __eq__? Then Python will probably find the __eq__ method on object and use that instead - which just checks for object identity anyway.

When comparing most other things in Python, you will be using !=.

How to initialize all the elements of an array to any specific value in java

Evidently you can use Arrays.fill(), The way you have it done also works though.

PHP function overloading

PHP does not support overloading for now. Hope this will be implemented in the other versions like other programming languages.

Checkout this library, This will allow you to use PHP Overloading in terms of closures. https://github.com/Sahil-Gulati/Overloading

Unable to locate tools.jar

  • Right click on your ant file
  • Go to "Run as" then click on "Ant Build..."
  • Go to the "JRE" tab
  • Select a JDK and not a JRE

Increment variable value by 1 ( shell programming)

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13

Note the spaces in the last example, also note that's the only one that uses $i.

Convert seconds value to hours minutes seconds?

This Code Is working Fine :

txtTimer.setText(String.format("%02d:%02d:%02d",(SecondsCounter/3600), ((SecondsCounter % 3600)/60), (SecondsCounter % 60)));

JS regex: replace all digits in string

find the numbers and then replaced with strings which specified. It is achieved by two methods

  1. Using a regular expression literal

  2. Using keyword RegExp object

Using a regular expression literal:

<script type="text/javascript">

var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));

</script>

**Output:**my contact number is XXX. my age is XXX.

for more details:

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156

Using RegEx in SQL Server

You will have to build a CLR procedure that provides regex functionality, as this article illustrates.

Their example function uses VB.NET:

Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here  


Namespace SimpleTalk.Phil.Factor
    Public Class RegularExpressionFunctions
        'RegExIsMatch function
        <SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
        Public Shared Function RegExIsMatch( _
                                            ByVal pattern As SqlString, _
                                            ByVal input As SqlString, _
                                            ByVal Options As SqlInt32) As SqlBoolean
            If (input.IsNull OrElse pattern.IsNull) Then
                Return SqlBoolean.False
            End If
            Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
            RegExOption = Options
            Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
        End Function
    End Class      ' 
End Namespace

...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:

sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE

IF EXISTS ( SELECT   1
            FROM     sys.objects
            WHERE    object_id = OBJECT_ID(N'dbo.RegExIsMatch') ) 
   DROP FUNCTION dbo.RegExIsMatch
go

IF EXISTS ( SELECT   1
            FROM     sys.assemblies asms
            WHERE    asms.name = N'RegExFunction ' ) 
   DROP ASSEMBLY [RegExFunction]

CREATE ASSEMBLY RegExFunction 
           FROM '%FILE%'
GO

CREATE FUNCTION RegExIsMatch
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options int
   )
RETURNS BIT
AS EXTERNAL NAME 
   RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO

--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT  dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
        dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
        dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
        dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
        dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

You can use regex.findall():

import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)

Command line .cmd/.bat script, how to get directory of running script

Raymond Chen has a few ideas:

https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573

Quoted here in full because MSDN archives tend to be somewhat unreliable:

The easy way is to use the %CD% pseudo-variable. It expands to the current working directory.

set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory

(Of course, directory save/restore could more easily have been done with pushd/popd, but that's not the point here.)

The %CD% trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.

set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args

(I like to use %_% as my scratch environment variable.)

Type SET /? to see the other pseudo-variables provided by the command processor.

Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):

http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741

This covers the use of %~dp0:

If you want to know where the batch file lives: %~dp0

%0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.

Import multiple csv files into pandas and concatenate into one DataFrame

Easy and Fast

Import two or more csv's without having to make a list of names.

import glob

df = pd.concat(map(pd.read_csv, glob.glob('data/*.csv')))

Update data on a page without refreshing

I think you would like to learn ajax first, try this: Ajax Tutorial

If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:

var xhr = new XMLHttpReuqest();
xhr.open("GET", "http://some.com");

xhr.onreadystatechange = handler; // do something here...
xhr.send();

How to draw border on just one side of a linear layout?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#f28b24" />
            <stroke
                android:width="1dp"
                android:color="#f28b24" />
            <corners
                android:radius="0dp"/>
            <padding
                android:left="0dp"
                android:top="0dp"
                android:right="0dp"
                android:bottom="0dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#f28b24"
                android:endColor="#f28b24"
                android:angle="270" />
            <stroke
                android:width="0dp"
                android:color="#f28b24" />
            <corners
                android:bottomLeftRadius="8dp"
                android:bottomRightRadius="0dp"
                android:topLeftRadius="0dp"
                android:topRightRadius="0dp"/>
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Load local HTML file in a C# WebBrowser

What worked for me was

<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />

from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:

Correct:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Incorrect:

<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />

Incorrect:

<uses-permission android:name="android.permission.access_fine_location" />

Though this may seem trivial, its easy to overlook.

If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!

Javascript to stop HTML5 video playback on modal window close

I'm using the following trick to stop HTML5 video. pause() the video on modal close and set currentTime = 0;

<script>
     var video = document.getElementById("myVideoPlayer");
     function stopVideo(){
          video.pause();
          video.currentTime = 0;
     }
</script>

Now you can use stopVideo() method to stop HTML5 video. Like,

$("#stop").on('click', function(){
    stopVideo();
});

How to call a function after delay in Kotlin?

You can use Schedule

inline fun Timer.schedule(
    delay: Long, 
    crossinline action: TimerTask.() -> Unit
): TimerTask (source)

example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)

import java.util.Timer
import kotlin.concurrent.schedule

Timer("SettingUp", false).schedule(500) { 
   doSomething()
}

How to set MimeBodyPart ContentType to "text/html"?

There is a method setText() which takes 3 arguments :

public void setText(String text, String charset, String subtype)
    throws MessagingException

Parameters:

text - the text content to set
charset - the charset to use for the text
subtype - the MIME subtype to use (e.g., "html")

NOTE: the subtype takes text after / in MIME types so for ex.

  • text/html would be html
  • text/css would be css
  • and so on..

Xpath: select div that contains class AND whose specific child element contains text

You can change your second condition to check only the span element:

...and contains(div/span, 'someText')]

If the span isn't always inside another div you can also use

...and contains(.//span, 'someText')]

This searches for the span anywhere inside the div.

How to get streaming url from online streaming radio station

Edited ZygD's answer for python 3.x.:

import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
    print ("Stream #" + str(i + 1));
    print ("Stream stats:");
    print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
    print ("Reliability: " + str(reliability[i]) + "%");
    print ("HasPlaylist: " + str(isPlaylist[i]));
    print ("Stream codec: " + str(codec[i]));
    print ("This audio stream is " + tipe[i].lower());
    print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")

C++ compiling on Windows and Linux: ifdef switch

It depends on the used compiler.

For example, Windows' definition can be WIN32 or _WIN32.

And Linux' definition can be UNIX or __unix__ or LINUX or __linux__.

How to overwrite the previous print to stdout in python?

Here's my solution! Windows 10, Python 3.7.1

I'm not sure why this code works, but it completely erases the original line. I compiled it from the previous answers. The other answers would just return the line to the beginning, but if you had a shorter line afterwards, it would look messed up like hello turns into byelo.

import sys
#include ctypes if you're on Windows
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
#end ctypes

def clearline(msg):
    CURSOR_UP_ONE = '\033[K'
    ERASE_LINE = '\x1b[2K'
    sys.stdout.write(CURSOR_UP_ONE)
    sys.stdout.write(ERASE_LINE+'\r')
    print(msg, end='\r')

#example
ig_usernames = ['beyonce','selenagomez']
for name in ig_usernames:
    clearline("SCRAPING COMPLETE: "+ name)

Output - Each line will be rewritten without any old text showing:

SCRAPING COMPLETE: selenagomez

Next line (rewritten completely on same line):

SCRAPING COMPLETE: beyonce

How to check a string for specific characters?

s=input("Enter any character:")   
if s.isalnum():   
   print("Alpha Numeric Character")   
   if s.isalpha():   
       print("Alphabet character")   
       if s.islower():   
         print("Lower case alphabet character")   
       else:   
         print("Upper case alphabet character")   
   else:   
     print("it is a digit")   
elif s.isspace():   
    print("It is space character")   

else:
print("Non Space Special Character")

Capture Signature using HTML5 and iPad

A canvas element with some JavaScript would work great.

In fact, Signature Pad (a jQuery plugin) already has this implemented.

Where are Magento's log files located?

You can find the log within you Magento root directory under

var/log

there are two types of log files system.log and exception.log

you need to give the correct permission to var folder, then enable logging from your Magento admin by going to

System > Configuration> Developer > Log Settings > Enable = Yes

system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.

exception.log is reserved for exceptions only, for example when you are using try-catch statement.

To output to either the default system.log or the exception.log see the following code examples:

Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);

You can create your own log file for more debugging

Mage::log('My log entry', null, 'mylogfile.log');

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

C++ - Assigning null to a std::string

I can't assign a null to a String?

No. std::string is not a pointer type; it cannot be made "null." It cannot represent the absence of a value, which is what a null pointer is used to represent.

It can be made empty, by assigning an empty string to it (s = "" or s = std::string()) or by clearing it (s.clear()).

Microsoft Azure: How to create sub directory in a blob container

To add on to what Egon said, simply create your blob called "folder/1.txt", and it will work. No need to create a directory.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I too had a similar type of problem . The solution is simple . just dont try to enter NULL or None value in values or u might have to use Something like this
dic.update([(key,value)])

use localStorage across subdomains

If you're using the iframe and postMessage solution just for this particular problem, I think it might be less work (both code-wise and computation-wise) to just store the data in a subdomain-less cookie and, if it's not already in localStorage on load, grab it from the cookie.

Pros:

  • Doesn't need the extra iframe and postMessage set up.

Cons:

  • Will make the data available across all subdomains (not just www) so if you don't trust all the subdomains it may not work for you.
  • Will send the data to the server on each request. Not great, but depending on your scenario, maybe still less work than the iframe/postMessage solution.
  • If you're doing this, why not just use the cookies directly? Depends on your context.
  • 4K max cookie size, total across all cookies for the domain (Thanks to Blake for pointing this out in comments)

I agree with other commenters though, this seems like it should be a specifiable option for localStorage so work-arounds aren't required.

TypeScript hashmap/dictionary interface

Just as a normal js object:

let myhash: IHash = {};   

myhash["somestring"] = "value"; //set

let value = myhash["somestring"]; //get

There are two things you're doing with [indexer: string] : string

  • tell TypeScript that the object can have any string-based key
  • that for all key entries the value MUST be a string type.

enter image description here

You can make a general dictionary with explicitly typed fields by using [key: string]: any;

enter image description here

e.g. age must be number, while name must be a string - both are required. Any implicit field can be any type of value.

As an alternative, there is a Map class:

let map = new Map<object, string>(); 

let key = new Object();

map.set(key, "value");
map.get(key); // return "value"

This allows you have any Object instance (not just number/string) as the key.

Although its relatively new so you may have to polyfill it if you target old systems.

How to open link in new tab on html?

Use one of these as per your requirements.

Open the linked document in a new window or tab:

 <a href="xyz.html" target="_blank"> Link </a>

Open the linked document in the same frame as it was clicked (this is default):

 <a href="xyz.html" target="_self"> Link </a>

Open the linked document in the parent frame:

 <a href="xyz.html" target="_parent"> Link </a>

Open the linked document in the full body of the window:

 <a href="xyz.html" target="_top"> Link </a>

Open the linked document in a named frame:

 <a href="xyz.html" target="framename"> Link </a>

See MDN

What are bitwise shift (bit-shift) operators and how do they work?

Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.

For example:

(long) 4 >> 65

equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:

(long) 4 >> (65 % 64)

This is true for <<, >>, and >>>. I have not tried it out in other languages.

Private class declaration

private modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public, abstract & final are permitted.

Note : Even you can not make it protected.

Docker is installed but Docker Compose is not ? why?

If you installed docker by adding their official repository to your repository list, like:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

Just do:

$ sudo apt-get install docker-compose

In case on RHEL based distro / Fedora:

$ sudo dnf install docker-compose

"’" showing on page instead of " ' "

This sometimes happens when a string is converted from Windows-1252 to UTF-8 twice.

We had this in a Zend/PHP/MySQL application where characters like that were appearing in the database, probably due to the MySQL connection not specifying the correct character set. We had to:

  1. Ensure Zend and PHP were communicating with the database in UTF-8 (was not by default)

  2. Repair the broken characters with several SQL queries like this...

    UPDATE MyTable SET 
    MyField1 = CONVERT(CAST(CONVERT(MyField1 USING latin1) AS BINARY) USING utf8),
    MyField2 = CONVERT(CAST(CONVERT(MyField2 USING latin1) AS BINARY) USING utf8);
    

    Do this for as many tables/columns as necessary.

You can also fix some of these strings in PHP if necessary. Note that because characters have been encoded twice, we actually need to do a reverse conversion from UTF-8 back to Windows-1252, which confused me at first.

mb_convert_encoding('’', 'Windows-1252', 'UTF-8');    // returns ’

What should be the values of GOPATH and GOROOT?

I had to append

export GOROOT=/usr/local/Cellar/go/1.10.1/libexec

to my ~/.bash_profile on Mac OS X

indexOf Case Sensitive?

Converting both strings to lower-case is usually not a big deal but it would be slow if some of the strings is long. And if you do this in a loop then it would be really bad. For this reason, I would recommend indexOfIgnoreCase.

How to retrieve available RAM from Windows command line?

This cannot be done in pure java. But you can run external programs using java and get the result.

Process p=Runtime.getRuntime().exec("systeminfo");
Scanner scan=new Scanner(p.getInputStream());
while(scan.hasNext()){
    String temp=scan.nextLine();
    if(temp.equals("Available Physical Memmory")){
       System.out.println("RAM :"temp.split(":")[1]);
       break;
    }
}

How to get CPU temperature?

For others who may come by here, maybe take a look at : http://openhardwaremonitor.org/

Follow that link and at first you might think, "hey that's an Application, that is why it was removed, the question was how to do this from C# code, not to find an application that can tell me the temperature..." This is where it shows you are not willing to invest enough time in reading what "Open Hardware Monitor" also is.

They also include a Data Interface, here is the description:

Data Interface The Open Hardware Monitor publishes all sensor data to WMI (Windows Management Instrumentation). This allows other applications to read and use the sensor information as well. A preliminary documentation of the interface can be found here(click).

When you download it, it contains the OpenHardwareMonitor.exe application, you're not looking for that one. It also contains the OpenHardwareMonitorLib.dll, you're looking for that one.

It is mostly, if not 100%, just a wrapper around the WinRing0 API, which you could choose to wrap your self if you feel like it.

I have tried this out from a C# app myself, and it works. Although it is still in beta, it seemed rather stable. It is also open source so it could be a good starting point instead.

At the end of the day I find it hard to believe that is not on topic of this question.

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

AngularJS HTTP post to PHP and undefined

This is the best solution (IMO) as it requires no jQuery and no JSON decode:

Source: https://wordpress.stackexchange.com/a/179373 and: https://stackoverflow.com/a/1714899/196507

Summary:

//Replacement of jQuery.param
var serialize = function(obj, prefix) {
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
};

//Your AngularJS application:
var app = angular.module('foo', []);

app.config(function ($httpProvider) {
    // send all requests payload as query string
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return serialize(data);
    };

    // set all post requests content type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Example:

...
   var data = { id: 'some_id', name : 'some_name' };
   $http.post(my_php_url,data).success(function(data){
        // It works!
   }).error(function() {
        // :(
   });

PHP code:

<?php
    $id = $_POST["id"];
?>

MySQL error 2006: mysql server has gone away

This error happens basically for two reasons.

  1. You have a too low RAM.
  2. The database connection is closed when you try to connect.

You can try this code below.

# Simplification to execute an SQL string of getting a data from the database
def get(self, sql_string, sql_vars=(), debug_sql=0):
    try:            
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()
    except (AttributeError, MySQLdb.OperationalError):
        self.__init__()
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()

It mitigates the error whatever the reason behind it, especially for the second reason.

If it's caused by low RAM, you either have to raise database connection efficiency from the code, from the database configuration, or simply raise the RAM.

Laravel: Get base url

You can also use URL::to('/') to display image in Laravel. Please see below:

<img src="{{URL::to('/')}}/images/{{ $post->image }}" height="100" weight="100"> 

Assume that, your image is stored under "public/images".

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

Listen to changes within a DIV and act accordingly

Try this

$('#D25,#E37,#E31,#F37,#E16,#E40,#F16,#F40,#E41,#F41').bind('DOMNodeInserted DOMNodeRemoved',function(){
          // your code;
       });

Do not use this. This may crash the page.

$('mydiv').bind("DOMSubtreeModified",function(){
  alert('changed');
});

What is the difference between UTF-8 and Unicode?

I have checked the links in Gumbo's answer, and I wanted to paste some part of those things here to exist on Stack Overflow as well.

"...Some people are under the misconception that Unicode is simply a 16-bit code where each character takes 16 bits and therefore there are 65,536 possible characters. This is not, actually, correct. It is the single most common myth about Unicode, so if you thought that, don't feel bad.

In fact, Unicode has a different way of thinking about characters, and you have to understand the Unicode way of thinking of things or nothing will make sense.

Until now, we've assumed that a letter maps to some bits which you can store on disk or in memory:

A -> 0100 0001

In Unicode, a letter maps to something called a code point which is still just a theoretical concept. How that code point is represented in memory or on disk is a whole other story..."

"...Every platonic letter in every alphabet is assigned a magic number by the Unicode consortium which is written like this: U+0639. This magic number is called a code point. The U+ means "Unicode" and the numbers are hexadecimal. U+0639 is the Arabic letter Ain. The English letter A would be U+0041...."

"...OK, so say we have a string:

Hello

which, in Unicode, corresponds to these five code points:

U+0048 U+0065 U+006C U+006C U+006F.

Just a bunch of code points. Numbers, really. We haven't yet said anything about how to store this in memory or represent it in an email message..."

"...That's where encodings come in.

The earliest idea for Unicode encoding, which led to the myth about the two bytes, was, hey, let's just store those numbers in two bytes each. So Hello becomes

00 48 00 65 00 6C 00 6C 00 6F

Right? Not so fast! Couldn't it also be:

48 00 65 00 6C 00 6C 00 6F 00 ? ..."

How to make <a href=""> link look like a button?

Yes you can do that.

Here is an example:

a{
    background:IMAGE-URL;
    display:block;
    height:IMAGE-HEIGHT;
    width:IMAGE-WIDTH;
}

Of course you can modify the above example to your need. The important thing is to make it appear as a block (display:block) or an inline block (display:inline-block).

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

Define: What is a HashSet?

A HashSet has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet (or getting an item by index) is rather slow.

So why would someone want be able to know if an entry already exists in a set?

One situation where a HashSet is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet it is quick to determine if the item exists (Contains operator).

Other advantages of the HashSet are the Set operations: IntersectWith, IsSubsetOf, IsSupersetOf, Overlaps, SymmetricExceptWith, UnionWith.

If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.

Flutter: Run method on Widget build complete

Try SchedulerBinding,

 SchedulerBinding.instance
                .addPostFrameCallback((_) => setState(() {
              isDataFetched = true;
            }));

Intellij idea cannot resolve anything in maven

<option name="workOffline" value="true" /> in workspace.xml is not your friend. Advise to check this before deleting your .idea (which has a lot of useful settings you probably don't want to lose)

It's a maven workspace.xml setting

Can't compile C program on a Mac after upgrade to Mojave

The problem is that Xcode, especially Xcode 10.x, has not installed everything, so ensure the command line tools are installed, type this in a terminal shell:

xcode-select --install

also start Xcode and ensure all the required installation is installed ( you should get prompted if it is not.) and since Xcode 10 does not install the full Mac OS SDK, run the installer at

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

as this package is not installed by Xcode 10.

"Eliminate render-blocking CSS in above-the-fold content"

Few tips that may help:

  • I came across this article in CSS optimization yesterday: CSS profiling for ... optimization
    A lot of useful info on CSS and what CSS causes the most performance drains.

  • I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.

  • Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.

Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.

Python: get key of index in dictionary

Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.

You can only do this in a loop:

[k for (k, v) in i.iteritems() if v == 0]

Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0} is perfectly legal.

If you want ordering you either need to use a list or a OrderedDict instance instead:

items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0]         # gives 'a'

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

Command to get time in milliseconds

date command didnt provide milli seconds on OS X, so used an alias from python

millis(){  python -c "import time; print(int(time.time()*1000))"; }

OR

alias millis='python -c "import time; print(int(time.time()*1000))"'

EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.

$ time date +%s%N
1597103627N
date +%s%N  0.00s user 0.00s system 63% cpu 0.006 total

Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date).

On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date)

$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))"  0.03s user 0.01s system 83% cpu 0.053 total

I figured awk is lightweight than python, so awk takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):

$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'  0.00s user 0.00s system 74% cpu 0.010 total

Getting today's date in YYYY-MM-DD in Python?

I always use the isoformat() function for this.

from datetime import date    
today = date.today().isoformat()
print(today) # '2018-12-05'

Note that this also works on datetime objects if you need the time in standard format as well.

from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'

How can I align button in Center or right using IONIC framework?

You should put the button inside a div, and in the div you should be able to use the classes:
text-left, text-center and text-right.

for example:

<div class="row">
   <div class="col text-center">
      <button class="button button-small button-light">Search</button>
   </div>
</div>

And about the "textarea" position:

<div class="list">
<label class="item item-input">
    <span class="input-label">Date</span>
    <input type="text" placeholder="Text Area">
</label>

Demo using your code:
http://codepen.io/douglask/pen/zxXvYY

docker build with --build-arg with multiple arguments

It's a shame that we need multiple ARG too, it results in multiple layers and slows down the build because of that, and for anyone also wondering that, currently there is no way to set multiple ARGs.

Enable the display of line numbers in Visual Studio

For me, line numbers wouldn't appear in the editor until I added the option under both the "all languages" pane, and the language I was working under (C# etc)... screen capture showing editor options

Android. Fragment getActivity() sometimes returns null

Don't call methods within the Fragment that require getActivity() until onStart in the parent Activity.

private MyFragment myFragment;


public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    myFragment = new MyFragment();

    ft.add(android.R.id.content, youtubeListFragment).commit();

    //Other init calls
    //...
}


@Override
public void onStart()
{
    super.onStart();

    //Call your Fragment functions that uses getActivity()
    myFragment.onPageSelected();
}

How to loop through all but the last item of a list?

for x in y[:-1]

If y is a generator, then the above will not work.

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

Angular - "has no exported member 'Observable'"

Try this:

npm install rxjs-compat --save

How to read/write a boolean when implementing the Parcelable interface?

It is hard to identify the real question here. I guess it is how to deal with booleans when implementing the Parcelable interface.

Some attributes of MyObject are boolean but Parcel don't have any method read/writeBoolean.

You will have to either store the value as a string or as a byte. If you go for a string then you'll have to use the static method of the String class called valueOf() to parse the boolean value. It isn't as effective as saving it in a byte tough.

String.valueOf(theBoolean);

If you go for a byte you'll have to implement a conversion logic yourself.

byte convBool = -1;
if (theBoolean) {
    convBool = 1;
} else {
    convBool = 0;
}

When unmarshalling the Parcel object you have to take care of the conversion to the original type.

Convert unsigned int to signed int C

It seems like you are expecting int and unsigned int to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting.

Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases:

unsigned int x = 65529;
int y = (short) x;      //  If short is a 16-bit integer.

or alternatively:

unsigned int x = 65529;
int y = (int16_t) x;    //  This is defined in <stdint.h>

Remove Object from Array using JavaScript

Here is an example with map and splice

_x000D_
_x000D_
const arrayObject = [
  { name: "name1", value: "value1" },
  { name: "name2", value: "value2" },
  { name: "name3", value: "value3" },
];

let index = arrayObject.map((item) => item.name).indexOf("name1");
if (index > -1) {
  
  arrayObject.splice(index, 1);
  console.log("Result", arrayObject);
  

}
_x000D_
_x000D_
_x000D_

Iterate through <select> options

And the requisite, non-jquery way, for followers, since google seems to send everyone here:

  var select = document.getElementById("select_id");
  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    // now have option.text, option.value
  }

Iterate Multi-Dimensional Array with Nested Foreach Statement

Two ways:

  1. Define the array as a jagged array, and use nested foreachs.
  2. Define the array normally, and use foreach on the entire thing.

Example of #2:

int[,] arr = { { 1, 2 }, { 3, 4 } };
foreach(int a in arr)
    Console.Write(a);

Output will be 1234. ie. exactly the same as doing i from 0 to n, and j from 0 to n.

What MIME type should I use for CSV?

My users are allowed to upload CSV files and text/csv and application/csv did not appear by now. These are the ones identified through finfo():

text/plain
text/x-csv

And these are the ones transmitted through the browser:

text/plain
application/vnd.ms-excel
text/x-csv

The following types did not appear, but could:

application/csv
application/x-csv
text/csv
text/comma-separated-values
text/x-comma-separated-values
text/tab-separated-values

Last element in .each() set

each passes into your function index and element. Check index against the length of the set and you're good to go:

var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
      thisVal = $(this).val();
      if(parseInt(thisVal) !== 0) {
          console.log('Valid Field: ' + thisVal);
          if (index === (length - 1)) {
              console.log('Last field, submit form here');
          }
      }
});

XML element with attribute and content using JAXB

Updated Solution - using the schema solution that we were debating. This gets you to your answer:

Sample Schema:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport" 
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
jaxb:version="2.0">

<complexType name="sportType">
    <attribute name="type" type="string" />
    <attribute name="gender" type="string" />
</complexType>

<element name="sports">
    <complexType>
        <sequence>
            <element name="sport" minOccurs="0" maxOccurs="unbounded"
                type="tns:sportType" />
        </sequence>
    </complexType>
</element>

Code Generated

SportType:

package org.example.sport; 

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {

    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String gender;

    public String getType() {
        return type;
    }


    public void setType(String value) {
        this.type = value;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String value) {
        this.gender = value;
    }

}

Sports:

package org.example.sport;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
        "sport"
})
@XmlRootElement(name = "sports")
public class Sports {

    protected List<SportType> sport;

    public List<SportType> getSport() {
        if (sport == null) {
            sport = new ArrayList<SportType>();
        }
        return this.sport;
    }

}

Output class files are produced by running xjc against the schema on the command line

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

jquery validate check at least one checkbox

make sure the input-name[] is in inverted commas in the ruleset. Took me hours to figure that part out.

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

read more here... http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29

Send private messages to friends

There isn't any graph api for this, you need to use facebook xmpp chat api to send the message, good news is: I have made a php class which is too easy to use,call a function and message will be sent, its open source, check it out: facebook message api php the description says its a closed source but the it was made open source later, see the first comment, you can clone from github. It's a open source now.

How to update the value stored in Dictionary in C#?

This may work for you:

Scenario 1: primitive types

string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};

if(!dictToUpdate.ContainsKey(keyToMatchInDict))
   dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
   dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;

Scenario 2: The approach I used for a List as Value

int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...

if(!dictToUpdate.ContainsKey(keyToMatch))
   dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
   dictToUpdate[keyToMatch] = objInValueListToAdd;

Hope it's useful for someone in need of help.

history.replaceState() example?

According to MDN History doc
There is clearly said that second argument is for future used not for now. You are right that second argument is deal with web-page title but currently it's ignored by all major browser.

Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

How to install Intellij IDEA on Ubuntu?

I find and follow this youtube:

https://www.youtube.com/watch?v=PbW-doAiAvI

Basically, download the tar.gz package, extract into /opt/, and then run the "idea.sh" under bin folder (i.e. /opt/idea-IC-163.7743.44/bin/idea.sh)

Enjoy

OpenSSL: unable to verify the first certificate for Experian URL

If you are using MacOS use:

sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs

after this Trust anchor not found error disappears

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

Ctrl+click doesn't work in Eclipse Juno

Please check your .classpath file as well. Some times Eclipse do not redirect when using "ctrl+click" to Class or method if classpath is not proper. I had faced same issue in Eclipse Mars but it got resolved when I got proper .classpath file at my work location.

Why is setTimeout(fn, 0) sometimes useful?

Take a look at John Resig's article about How JavaScript Timers Work. When you set a timeout, it actually queues the asynchronous code until the engine executes the current call stack.

What is the best IDE to develop Android apps in?

you can use Juno, i just find it. it's fastest than Helios that i worked with that. you can try it.

Arrays.asList() of an array

Let's consider the following simplified example:

public class Example {
    public static void main(String[] args) {
        int[] factors = {1, 2, 3};
        ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));
        System.out.println(f);
    }
}

At the println line this prints something like "[[I@190d11]" which means that you have actually constructed an ArrayList that contains int arrays.

Your IDE and compiler should warn about unchecked assignments in that code. You should always use new ArrayList<Integer>() or new ArrayList<>() instead of new ArrayList(). If you had used it, there would have been a compile error because of trying to pass List<int[]> to the constructor.

There is no autoboxing from int[] to Integer[], and anyways autoboxing is only syntactic sugar in the compiler, so in this case you need to do the array copy manually:

public static int getTheNumber(int[] factors) {
    List<Integer> f = new ArrayList<Integer>();
    for (int factor : factors) {
        f.add(factor); // after autoboxing the same as: f.add(Integer.valueOf(factor));
    }
    Collections.sort(f);
    return f.get(0) * f.get(f.size() - 1);
}

How can I find the method that called the current method?

Maybe you are looking for something like this:

StackFrame frame = new StackFrame(1);
frame.GetMethod().Name; //Gets the current method name

MethodBase method = frame.GetMethod();
method.DeclaringType.Name //Gets the current class name

Center icon in a div - horizontally and vertically

Since they are already inline-block child elements, you can set text-align:center on the parent without having to set a width or margin:0px auto on the child. Meaning it will work for dynamically generated content with varying widths.

.img_container, .img_container2 {
    text-align: center;
}

This will center the child within both div containers.

UPDATE:

For vertical centering, you can use the calc() function assuming the height of the icon is known.

.img_container > i, .img_container2 > i {
    position:relative;
    top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}

jsFiddle demo - it works.

For what it's worth - you can also use vertical-align:middle assuming display:table-cell is set on the parent.

Installing specific package versions with pip

If you want to update to latest version and you don't know what is the latest version you can type.

pip install MySQL_python --upgrade

This will update the MySQL_python for latest version available, you can use for any other package version.

MySQL joins and COUNT(*) from another table

MySQL use HAVING statement for this tasks.

Your query would look like this:

SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4

example when references have different names

SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4

Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.

How to show Snackbar when Activity starts?

It can be done simply by using the following codes inside onCreate. By using android's default layout

Snackbar.make(findViewById(android.R.id.content),"Your Message",Snackbar.LENGTH_LONG).show();

Injection of autowired dependencies failed;

public class Organization {

    @Id
    @Column(name="org_id")
    @GeneratedValue
    private int id;

    @Column(name="org_name")
    private String name;

    @Column(name="org_office_address1")
    private String address1;

    @Column(name="org_office_addres2")
    private String address2;

    @Column(name="city")
    private String city;

    @Column(name="state")
    private String state;

    @Column(name="country")
    private String country;

    @JsonIgnore
    @OneToOne
    @JoinColumn(name="pkg_id")
    private int pkgId;

    public int getPkgId() {
        return pkgId;
    }

    public void setPkgId(int pkgId) {
        this.pkgId = pkgId;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name="pincode")
    private String pincode;

    @OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);

    @Column(name="status")
    private String status = "ACTIVE";

    @Column(name="project_id")
    private int redmineProjectId;

    public int getRedmineProjectId() {
        return redmineProjectId;
    }

    public void setRedmineProjectId(int redmineProjectId) {
        this.redmineProjectId = redmineProjectId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Set<OrganizationBranch> getOrganizationBranch() {
        return organizationBranch;
    }

    public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
        this.organizationBranch = organizationBranch;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }
}

You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired

Why does the 260 character path length limit exist in Windows?

This is not strictly true as the NTFS filesystem supports paths up to 32k characters. You can use the win32 api and "\\?\" prefix the path to use greater than 260 characters.

A detailed explanation of long path from the .Net BCL team blog.
A small excerpt highlights the issue with long paths

Another concern is inconsistent behavior that would result by exposing long path support. Long paths with the \\?\ prefix can be used in most of the file-related Windows APIs, but not all Windows APIs. For example, LoadLibrary, which maps a module into the address of the calling process, fails if the file name is longer than MAX_PATH. So this means MoveFile will let you move a DLL to a location such that its path is longer than 260 characters, but when you try to load the DLL, it would fail. There are similar examples throughout the Windows APIs; some workarounds exist, but they are on a case-by-case basis.

Java Could not reserve enough space for object heap error

This was occuring for me and it is such an easy fix.

  1. you have to make sure that you have the correct java for your system such as 32bit or 64bit.
  2. if you have installed the correct software and it still occurs than goto

    control panelsystemadvanced system settings for Windows 8 or

    control panelsystem and securitysystemadvanced system settings for Windows 10.

  3. you must goto the {advanced tab} and then click on {Environment Variables}.
  4. you will click on {New} under the <system variables>
  5. you will create a new variable. Variable name: _JAVA_OPTIONS Variable Value: -Xmx512M

At least that is what worked for me.

Change Row background color based on cell value DataTable

DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({
  // ...
  "createdRow": function(row, data, dataIndex) {
    if (data["column_index"] == "column_value") {
      $(row).css("background-color", "Orange");
      $(row).addClass("warning");
    }
  },
  // ...
});

running multiple bash commands with subprocess

If you're only running the commands in one shot then you can just use subprocess.check_output convenience function:

def subprocess_cmd(command):
    output = subprocess.check_output(command, shell=True)
    print output

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

If any one had the same problem as me and the charset was already correct, simply do this:

  1. Copy all the code inside the .html file.
  2. Open notepad (or any basic text editor) and paste the code.
  3. Go "File -> Save As"
  4. Enter you file name "example.html" (Select "Save as type: All Files (.)")
  5. Select Encoding as UTF-8
  6. Hit Save and you can now delete your old .html file and the encoding should be fixed

Why is the Java main method static?

If the main method would not be static, you would need to create an object of your main class from outside the program. How would you want to do that?

jQuery: click function exclude children.

My solution:

jQuery('.foo').on('click',function(event){
    if ( !jQuery(event.target).is('.foo *') ) {
        // code goes here
    } 
});

Regular expressions inside SQL Server

Try this

select * from mytable
where p1 not like '%[^0-9]%' and substring(p1,1,1)='5'

Of course, you'll need to adjust the substring value, but the rest should work...

Uninstall old versions of Ruby gems

Way to clean out any old versions of gems.

sudo gem cleanup

If you just want to see a list of what would be removed you can use:

sudo gem cleanup -d

You can also cleanup just a specific gem by specifying its name:

sudo gem cleanup gemname

for remove specific version like 1.1.9 only

gem uninstall gemname --version 1.1.9

If you still facing some exception to install gem, like:

invalid gem: package is corrupt, exception while verifying: undefined method `size' for nil:NilClass (NoMethodError) in /home/rails/.rvm/gems/ruby-2.1.1@project/cache/nokogiri-1.6.6.2.gem

the, you can remove it from cache:

rm /home/rails/.rvm/gems/ruby-2.1.1@project/cache/nokogiri-1.6.6.2.gem

For more detail:

http://blog.grepruby.com/2015/04/way-to-clean-up-gem-or-remove-old.html

Git - deleted some files locally, how do I get them from a remote repository

You need to check out a previous version from before you deleted the files. Try git checkout HEAD^ to checkout the last revision.

Python: Find a substring in a string and returning the index of the substring

Here is a simple approach:

my_string = 'abcdefg'
print(text.find('def'))

Output:

3

I the substring is not there, you will get -1. For example:

my_string = 'abcdefg'
print(text.find('xyz'))

Output:

-1

Sometimes, you might want to throw exception if substring is not there:

my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present

Output:

Traceback (most recent call last):

File "test.py", line 6, in print(text.index('xyz'))

ValueError: substring not found

Eclipse "Invalid Project Description" when creating new project from existing source

If you wish to open a new project from an existing source code in the following way:

File -> Import -> General -> Existing Project into Workspace

you still have the message "Invalid Project Description". I solve it just by going in

File -> Switch Workspace

and choosing one of the recent workspaces.

Git merge reports "Already up-to-date" though there is a difference

This often happens to me when I know there are changes on the remote master, so I try to merge them using git merge master. However, this doesn't merge with the remote master, but with your local master.

So before doing the merge, checkout master, and then git pull there. Then you will be able to merge the new changes into your branch.

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

Why do access tokens expire?

In addition to the other responses:

Once obtained, Access Tokens are typically sent along with every request from Clients to protected Resource Servers. This induce a risk for access token stealing and replay (assuming of course that access tokens are of type "Bearer" (as defined in the initial RFC6750).

Examples of those risks, in real life:

  • Resource Servers generally are distributed application servers and typically have lower security levels compared to Authorization Servers (lower SSL/TLS config, less hardening, etc.). Authorization Servers on the other hand are usually considered as critical Security infrastructure and are subject to more severe hardening.

  • Access Tokens may show up in HTTP traces, logs, etc. that are collected legitimately for diagnostic purposes on the Resource Servers or clients. Those traces can be exchanged over public or semi-public places (bug tracers, service-desk, etc.).

  • Backend RS applications can be outsourced to more or less trustworthy third-parties.

The Refresh Token, on the other hand, is typically transmitted only twice over the wires, and always between the client and the Authorization Server: once when obtained by client, and once when used by client during refresh (effectively "expiring" the previous refresh token). This is a drastically limited opportunity for interception and replay.

Last thought, Refresh Tokens offer very little protection, if any, against compromised clients.

How can a add a row to a data frame in R?

There is a simpler way to append a record from one dataframe to another IF you know that the two dataframes share the same columns and types. To append one row from xx to yy just do the following where i is the i'th row in xx.

yy[nrow(yy)+1,] <- xx[i,]

Simple as that. No messy binds. If you need to append all of xx to yy, then either call a loop or take advantage of R's sequence abilities and do this:

zz[(nrow(zz)+1):(nrow(zz)+nrow(yy)),] <- yy[1:nrow(yy),]

Can't find/install libXtst.so.6?

Your problem comes from the 32/64 bit version of your JDK/JRE... Your shared lib is searched for a 32 bit version.

Your default JDK is a 32 bit version. Try to install a 64 bit one by default and relaunch your `.sh file.

How to check python anaconda version installed on Windows 10 PC?

On the anaconda prompt, do a

  • conda -V or conda --version to get the conda version.
  • python -V or python --version to get the python version.
  • conda list anaconda$ to get the Anaconda version.
  • conda list to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).
  • conda info to get all the current environment details.
  • conda info --envs To see a list of all your environments

Detailed description here, download cheat sheet from here

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

Regex - how to match everything except a particular pattern

My answer here might solve your problem as well:

https://stackoverflow.com/a/27967674/543814

  • Instead of Replace, you would use Match.
  • Instead of group $1, you would read group $2.
  • Group $2 was made non-capturing there, which you would avoid.

Example:

Regex.Match("50% of 50% is 25%", "(\d+\%)|(.+?)");

The first capturing group specifies the pattern that you wish to avoid. The last capturing group captures everything else. Simply read out that group, $2.

How to run a class from Jar which is not the Main-Class in its Manifest file

Apart from calling java -jar myjar.jar com.mycompany.Myclass, you can also make the main class in your Manifest a Dispatcher class.

Example:

public class Dispatcher{

    private static final Map<String, Class<?>> ENTRY_POINTS =
        new HashMap<String, Class<?>>();
    static{
        ENTRY_POINTS.put("foo", Foo.class);
        ENTRY_POINTS.put("bar", Bar.class);
        ENTRY_POINTS.put("baz", Baz.class);
    }

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

        if(args.length < 1){
            // throw exception, not enough args
        }
        final Class<?> entryPoint = ENTRY_POINTS.get(args[0]);
        if(entryPoint==null){
            // throw exception, entry point doesn't exist
        }
        final String[] argsCopy =
            args.length > 1
                ? Arrays.copyOfRange(args, 1, args.length)
                : new String[0];
        entryPoint.getMethod("main", String[].class).invoke(null,
            (Object) argsCopy);

    }
}

Can someone post a well formed crossdomain.xml sample?

If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.

<?xml version="1.0" ?>
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

There is already an object named in the database

I had same problem and after three hour struggling I find out what's going on

In my case, when I wanted to migrate for the first time in up() method, the default code wants to create the tables that already existed so I got same error as you

To solve it, just delete those code and write want you want. For example, I wanted to add a column so i just write

migrationBuilder.AddColumn<string>(
            name: "fieldName",
            table: "tableName",
            nullable: true);

Change x axes scale in matplotlib

This is not so much an answer to your original question as to one of the queries you had in the body of your question.

A little preamble, so that my naming doesn't seem strange:

import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )

As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:

ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')

You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:

ax.xaxis.major.formatter._useMathText = True

This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:

rc('text', usetex=True)

Using PUT method in HTML form

_method hidden field workaround

The following simple technique is used by a few web frameworks:

  • add a hidden _method parameter to any form that is not GET or POST:

    <input type="hidden" name="_method" value="PUT">
    

    This can be done automatically in frameworks through the HTML creation helper method.

  • fix the actual form method to POST (<form method="post")

  • processes _method on the server and do exactly as if that method had been sent instead of the actual POST

You can achieve this in:

  • Rails: form_tag
  • Laravel: @method("PATCH")

Rationale / history of why it is not possible in pure HTML: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms

Export to CSV via PHP

Just like @Dampes8N said:

$result = mysql_query($sql,$conecction);
$fp = fopen('file.csv', 'w');
while($row = mysql_fetch_assoc($result)){
    fputcsv($fp, $row);
}
fclose($fp);

Hope this helps.

how to add a day to a date using jquery datepicker

Try this:

 $('.pickupDate').change(function() {
  var date2 = $('.pickupDate').datepicker('getDate', '+1d'); 
  date2.setDate(date2.getDate()+1); 
  $('.dropoffDate').datepicker('setDate', date2);
});

What is the best way to parse html in C#?

Try this script.

http://www.biterscripting.com/SS_URLs.html

When I use it with this url,

script SS_URLs.txt URL("http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c")

It shows me all the links on the page for this thread.

http://sstatic.net/so/all.css
http://sstatic.net/so/favicon.ico
http://sstatic.net/so/apple-touch-icon.png
.
.
.

You can modify that script to check for images, variables, whatever.

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

Java Date - Insert into database

You should be using java.sql.Timestamp instead of java.util.Date. Also using a PreparedStatement will save you worrying about the formatting.

Difference between arguments and parameters in Java

Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.

You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.