Programs & Examples On #Xmltask

Passing multiple values for a single parameter in Reporting Services

This is one of the poor supported features in SQL Reporting Services.

What you need to do is pass all of your selected items as a single string to your stored procedure. Each element within the string will be separated by a comma.

What I then do is split the string using a function that returns the provided string as a table. See below.

ALTER FUNCTION [dbo].[fn_MVParam]
   (@RepParam nvarchar(4000), @Delim char(1)= ',')
RETURNS @Values TABLE (Param nvarchar(4000))AS
  BEGIN
  DECLARE @chrind INT
  DECLARE @Piece nvarchar(100)
  SELECT @chrind = 1 
  WHILE @chrind > 0
    BEGIN
      SELECT @chrind = CHARINDEX(@Delim,@RepParam)
      IF @chrind  > 0
        SELECT @Piece = LEFT(@RepParam,@chrind - 1)
      ELSE
        SELECT @Piece = @RepParam
      INSERT  @Values(Param) VALUES(CAST(@Piece AS VARCHAR))
      SELECT @RepParam = RIGHT(@RepParam,LEN(@RepParam) - @chrind)
      IF LEN(@RepParam) = 0 BREAK
    END
  RETURN
  END

You can then reference the results in the where clause of your main query like so:

where someColumn IN(SELECT Param FROM dbo.fn_MVParam(@sParameterString,','))

I hope this you find this solution to be of use. Please feel free to pose any questions you may have.

Cheers,John

Adding a slide effect to bootstrap dropdown

Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:

.dropdown .dropdown-menu {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;

    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
}

.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
    max-height: 300px;
    opacity: 1;
}

The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.

It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.

Here is small example: DEMO


! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.

How to make a rest post call from ReactJS code?

As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:

import axios from 'axios';
...
class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.onLogin = this.onLogin.bind(this);
        ...
    }
    async onLogin() {
        const { email, password } = this.state;
        try {
           const response = await axios.post('/login', { email, password });
           console.log(response);
        } catch (err) {
           ...
        }
    }
    ...
}

How to capture UIView to UIImage without loss of quality on retina display

Swift 3

The Swift 3 solution (based on Dima's answer) with UIView extension should be like this:

extension UIView {
    public func getSnapshotImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
        let snapshotImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return snapshotImage
    }
}

How do you rotate a two dimensional array?

For i:= 0 to X do For j := 0 to X do graphic[j][i] := graphic2[X-i][j]

X is the size of the array the graphic is in.

Index of Currently Selected Row in DataGridView

Try DataGridView.CurrentCellAddress.

Returns: A Point that represents the row and column indexes of the currently active cell.

E.G. Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 )

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

In case this helps anyone:

I had a similar issue, and following Nates instructions I added:

<system.web>
     <customErrors mode="Off"/>
 </system.web>

This showed me more information about the error:

"ExceptionMessage": "Unable to load the specified metadata resource.", "ExceptionType": "System.Data.Entity.Core.MetadataException", "StackTrace": " at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(...

This is when I remembered that I had moved the edmx file to a different location and had forgotten to change the connectionstrings node in the config (connectionsstrings node was placed in a seperate file using "configSource", but that's another story).

PHP function use variable from outside

Do not forget that you also can pass these use variables by reference.

The use cases are when you need to change the use'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).

$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
    $newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);

Now $newarray will comprise (pseudocode here for brevity) [{times2:2},{times2:4}].

On the contrary, using $newarray with no & modifier would make outer $newarray variable be read-only accessible from within the closure scope. But $newarray within closure scope would be a completelly different newly created variable living only within the closure scope.

Despite both variables' names are the same these would be two different variables. The outer $newarray variable would comprise [] in this case after the code has finishes.

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

Angular2 multiple router-outlet in the same template

There seems to be another (rather hacky) way to reuse the router-outlet in one template. This answer is intendend for informational purposes only and the techniques used here should probably not be used in production.

https://stackblitz.com/edit/router-outlet-twice-with-events

The router-outlet is wrapped by an ng-template. The template is updated by listening to events of the router. On every event the template is swapped and re-swapped with an empty placeholder. Without this "swapping" the template would not be updated.

This most definetly is not a recommended approach though, since the whole swapping of two templates seems a bit hacky.

in the controller:

  ngOnInit() {
    this.router.events.subscribe((routerEvent: Event) => {
      console.log(routerEvent);
      this.myTemplateRef = this.trigger;
      setTimeout(() => {
        this.myTemplateRef = this.template;
      }, 0);
    });
  }

in the template:

<div class="would-be-visible-on-mobile-only">
  This would be the mobile-layout with a router-outlet (inside a template): 
  <br>
  <ng-container *ngTemplateOutlet="myTemplateRef"></ng-container>
</div>

<hr>

<div class="would-be-visible-on-desktop-only">
  This would be the desktop-layout with a router-outlet (inside a template): 
  <br>
  <ng-container *ngTemplateOutlet="myTemplateRef"></ng-container>
</div>

<ng-template #template>
    <br>
    This is my counter: {{counter}}
    inside the template, the router-outlet should follow
    <router-outlet>
    </router-outlet>
</ng-template>

<ng-template #trigger>
  template to trigger changes...
</ng-template>

SVG drop shadow using css3

I'm not aware of a CSS-only solution.

As you mentioned, filters are the canonical approach to creating drop shadow effects in SVG. The SVG specification includes an example of this.

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

Update int column in table with unique incrementing values

Try something like this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (partition by interfaceId order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

How to place a file on classpath in Eclipse?

Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.

Check if a variable exists in a list in Bash

I find it's easier to use the form echo $LIST | xargs -n1 echo | grep $VALUE as illustrated below:

LIST="ITEM1 ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | xargs -n1 echo | grep -e \"^$VALUE`$\" ]; then
    ...
fi

This works for a space-separated list, but you could adapt it to any other delimiter (like :) by doing the following:

LIST="ITEM1:ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | sed 's|:|\\n|g' | grep -e \"^$VALUE`$\"`" ]; then
   ...
fi

Note that the " are required for the test to work.

To check if string contains particular word

Not as complicated as they say, check this you will not regret.

String sentence = "Check this answer and you can find the keyword with this code";
String search  = "keyword";

if ( sentence.toLowerCase().indexOf(search.toLowerCase()) != -1 ) {

   System.out.println("I found the keyword");

} else {

   System.out.println("not found");

}

You can change the toLowerCase() if you want.

How can I get all a form's values that would be submitted without submitting

In straight Javascript you could do something similar to the following:

var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
   var e = form.elements[i];
   kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");

In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.

How to determine if a number is odd in JavaScript

When you need to test if some variable is odd, you should first test if it is integer. Also, notice that when you calculate remainder on negative number, the result will be negative (-3 % 2 === -1).

function isOdd(value) {
  return typeof value === "number" && // value should be a number
    isFinite(value) &&                // value should be finite
    Math.floor(value) === value &&    // value should be integer
    value % 2 !== 0;                  // value should not be even
}

If Number.isInteger is available, you may also simplify this code to:

function isOdd(value) {
  return Number.isInteger(value)      // value should be integer
    value % 2 !== 0;                  // value should not be even
}

Note: here, we test value % 2 !== 0 instead of value % 2 === 1 is because of -3 % 2 === -1. If you don't want -1 pass this test, you may need to change this line.

Here are some test cases:

isOdd();         // false
isOdd("string"); // false
isOdd(Infinity); // false
isOdd(NaN);      // false
isOdd(0);        // false
isOdd(1.1);      // false
isOdd("1");      // false
isOdd(1);        // true
isOdd(-1);       // true

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

First of all check error log in the path that your webserver indicates. Then maybe the browser is showing friendly error messages, so disable it.

https://superuser.com/questions/202244/show-http-error-details-in-google-chrome

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

How do I set hostname in docker-compose?

This issue is still open here: https://github.com/docker/compose/issues/2925

You can set hostname but it is not reachable from other containers. So it is mostly useless.

Timing Delays in VBA

The Timer function also applies to Access 2007, Access 2010, Access 2013, Access 2016, Access 2007 Developer, Access 2010 Developer, Access 2013 Developer. Insert this code to to pause time for certain amount of seconds

T0 = Timer
Do
    Delay = Timer - T0
Loop Until Delay = 1 'Change this value to pause time in second

Python: avoiding pylint warnings about too many arguments

Do you want a better way to pass the arguments or just a way to stop pylint from giving you a hard time? If the latter, I seem to recall that you could stop the nagging by putting pylint-controlling comments in your code along the lines of:

#pylint: disable=R0913

or, better:

#pylint: disable=too-many-arguments

remembering to turn them back on as soon as practicable.

In my opinion, there's nothing inherently wrong with passing a lot of arguments and solutions advocating wrapping them all up in some container argument don't really solve any problems, other than stopping pylint from nagging you :-).

If you need to pass twenty arguments, then pass them. It may be that this is required because your function is doing too much and a re-factoring could assist there, and that's something you should look at. But it's not a decision we can really make unless we see what the 'real' code is.

What's the difference between & and && in MATLAB?

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here.

How do I install Eclipse Marketplace in Eclipse Classic?

With Eclipse 3.7 Indigo, I found the link at http://www.eclipse.org/mpc/ which told me the download location and plugin was http://download.eclipse.org/mpc/indigo/ Which made the "Eclipse Marketplace Client" available in my Software updates after I added that address as a repository. Didn't seem to be in the core list on a fresh install.

How do I get a file name from a full path with PHP?

It's simple. For example:

<?php
    function filePath($filePath)
    {
        $fileParts = pathinfo($filePath);

        if (!isset($fileParts['filename']))
        {
            $fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
        }
        return $fileParts;
    }

    $filePath = filePath('/www/htdocs/index.html');
    print_r($filePath);
?>

The output will be:

Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Can a java lambda have more than 1 parameter?

To make the use of lambda : There are three type of operation:
1. Accept parameter --> Consumer
2. Test parameter return boolean --> Predicate
3. Manipulate parameter and return value --> Function

Java Functional interface upto two parameter:
Single parameter interface
Consumer
Predicate
Function

Two parameter interface
BiConsumer
BiPredicate
BiFunction

For more than two, you have to create functional interface as follow(Consumer type):

@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
    public void accept(T t, U u, V v, W w, X x);
}

How do I automatically resize an image for a mobile site?

For me, it worked best to add this in image css: max-width:100%; and NOT specify image width and height in html parameters. This adjusted the width to fit in device screen while adjusting height automatically. Otherwise height might be distorted.

What does the star operator mean, in a function call?

In a function call the single star turns a list into seperate arguments (e.g. zip(*x) is the same as zip(x1,x2,x3) if x=[x1,x2,x3]) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) if k = {'x':my_x, 'y':my_y}.

In a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3), x will be [1,2,3])" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".

Postman: How to make multiple requests at the same time

I don't know if this question is still relevant, but there is such possibility in Postman now. They added it a few months ago.

All you need is create simple .js file and run it via node.js. It looks like this:

var path = require('path'),
  async = require('async'), //https://www.npmjs.com/package/async
  newman = require('newman'),

  parametersForTestRun = {
    collection: path.join(__dirname, 'postman_collection.json'), // your collection
    environment: path.join(__dirname, 'postman_environment.json'), //your env
  };

parallelCollectionRun = function(done) {
  newman.run(parametersForTestRun, done);
};

// Runs the Postman sample collection thrice, in parallel.
async.parallel([
    parallelCollectionRun,
    parallelCollectionRun,
    parallelCollectionRun
  ],
  function(err, results) {
    err && console.error(err);

    results.forEach(function(result) {
      var failures = result.run.failures;
      console.info(failures.length ? JSON.stringify(failures.failures, null, 2) :
        `${result.collection.name} ran successfully.`);
    });
  });

Then just run this .js file ('node fileName.js' in cmd).

More details here

jQuery find parent form

You can use the form reference which exists on all inputs, this is much faster than .closest() (5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.

var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();

Make more than one chart in same IPython Notebook cell

Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.

df.plot(subplots=True)

If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].

Sorting list based on values from another list

Here is Whatangs answer if you want to get both sorted lists (python3).

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Zx, Zy = zip(*[(x, y) for x, y in sorted(zip(Y, X))])

print(list(Zx))  # [0, 0, 0, 1, 1, 1, 1, 2, 2]
print(list(Zy))  # ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Just remember Zx and Zy are tuples. I am also wandering if there is a better way to do that.

Warning: If you run it with empty lists it crashes.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Personally, to deal with empty responses, I use in my Integration Tests the MockMvcResponse object like this :

MockMvcResponse response = RestAssuredMockMvc.given()
                .webAppContextSetup(webApplicationContext)
                .when()
                .get("/v1/ticket");

    assertThat(response.mockHttpServletResponse().getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value());

and in my controller I return empty response in a specific case like this :

return ResponseEntity.noContent().build();

Define preprocessor macro through CMake?

The other solution proposed on this page are useful some versions of Cmake < 3.3.2. Here the solution for the version I am using (i.e., 3.3.2). Check the version of your Cmake by using $ cmake --version and pick the solution that fits with your needs. The cmake documentation can be found on the official page.

With CMake version 3.3.2, in order to create

#define foo

I needed to use:

add_definitions(-Dfoo)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

and, in order to have a preprocessor macro definition like this other one:

#define foo=5

the line is so modified:

add_definitions(-Dfoo=5)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

sql searching multiple words in a string

Select * from table where 
  columnname like'%David%' and 
  columnname like '%Moses%' and columnname like'%Robi%' 

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

How can I get new selection in "select" in Angular 2?

I ran into this problem while doing the Angular 2 forms tutorial (TypeScript version) at https://angular.io/docs/ts/latest/guide/forms.html

The select/option block wasn't allowing the value of the selection to be changed by selecting one of the options.

Doing what Mark Rajcok suggested worked, although I'm wondering if there's something I missed in the original tutorial or if there was an update. In any case, adding

onChange(newVal) {
    this.model.power = newVal;
}

to hero-form.component.ts in the HeroFormComponent class

and

(change)="onChange($event.target.value)"

to hero-form.component.html in the <select> element made it work

Set style for TextView programmatically

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
    textView.setTextAppearance(R.style.yourStyle)

Setting up an MS-Access DB for multi-user access

Access is a great multi-user database. It has lots of built in features to handle the multi-user situation. In fact, it is so very popular because it is such a great multi-user database. There is an upper limit on how many users can all use the database at the same time doing updates and edits - depending on how knowledgeable the developer is about access and how the database has been designed - anywhere from 20 users to approx 50 users. Some access databases can be built to handle up to 50 concurrent users, while many others can handle 20 or 25 concurrent users updating the database. These figures have been observed for databases that have been in use for several or more years and have been discussed many times on the access newsgroups.

Composer - the requested PHP extension mbstring is missing from your system

sudo apt-get install php-mbstring

# if your are using php 7.1
sudo apt-get install php7.1-mbstring

# if your are using php 7.2
sudo apt-get install php7.2-mbstring

Vue.JS: How to call function after page loaded?

Vue watch() life-cycle hook, can be used

html

<div id="demo">{{ fullName }}</div>

js

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

How can I enable MySQL's slow query log without restarting MySQL?

For slow queries on version < 5.1, the following configuration worked for me:

log_slow_queries=/var/log/mysql/slow-query.log
long_query_time=20
log_queries_not_using_indexes=YES

Also note to place it under [mysqld] part of the config file and restart mysqld.

How to create strings containing double quotes in Excel formulas?

VBA Function

1) .Formula = "=""THEFORMULAFUNCTION ""&(CHAR(34) & ""STUFF"" & CHAR(34))"

2) .Formula = "THEFORMULAFUNCTION ""STUFF"""

The first method uses vba to write a formula in a cell which results in the calculated value:

 THEFORMULAFUNCTION "STUFF"

The second method uses vba to write a string in a cell which results in the value:

 THEFORMULAFUNCTION "STUFF"

Excel Result/Formula

1) ="THEFORMULAFUNCTION "&(CHAR(34) & "STUFF" & CHAR(34))

2) THEFORMULAFUNCTION "STUFF"

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

How to sleep for five seconds in a batch file/cmd

One hack is to (mis)use the ping command:

ping 127.0.0.1 -n 6 > nul

Explanation:

  • ping is a system utility that sends ping requests. ping is available on all versions of Windows.
  • 127.0.0.1 is the IP address of localhost. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.
  • -n 6 specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.
  • > nul suppress the output of ping, by redirecting it to nul.

How to create a JPA query with LEFT OUTER JOIN

Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.

See,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON

How do I get data from a table?

This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea

//gets table
var oTable = document.getElementById('myTable');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 0; i < rowLength; i++){

   //gets cells of current row
   var oCells = oTable.rows.item(i).cells;

   //gets amount of cells of current row
   var cellLength = oCells.length;

   //loops through each cell in current row
   for(var j = 0; j < cellLength; j++){
      /* get your cell info here */
      /* var cellVal = oCells.item(j).innerHTML; */
   }
}

UPDATED - TESTED SCRIPT

<table id="myTable">
    <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
    </tr>
    <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
    </tr>
</table>
<script>
    //gets table
    var oTable = document.getElementById('myTable');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows    
    for (i = 0; i < rowLength; i++){

      //gets cells of current row  
       var oCells = oTable.rows.item(i).cells;

       //gets amount of cells of current row
       var cellLength = oCells.length;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

              // get your cell info here

              var cellVal = oCells.item(j).innerHTML;
              alert(cellVal);
           }
    }
</script>

How to access ssis package variables inside script component

I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.

After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.

So to access the variable, I type

string fp = Variables.FilePath;

In the PreExecute() method of the Script Component.

ASP.NET Web API : Correct way to return a 401/unauthorised response

To add to an existing answer in ASP.NET Core >= 1.0 you can

return Unauthorized();

return Unauthorized(object value);

To pass info to the client you can do a call like this:

return Unauthorized(new { Ok = false, Code = Constants.INVALID_CREDENTIALS, ...});

On the client besides the 401 response you will have the passed data too. For example on most clients you can await response.json() to get it.

Real time data graphing on a line chart with html5

You get the data from server, update your previously available datasetand then probably use one of the freely available libraries to draw the graph (eg: http://www.rgraph.net)

Things you might want to considering : If your chart is represents a state , get only the new data with xhr , update data on client and draw .

Connection string with relative path to the database file

In your config file give the relative path

ConnectionString = "Data Source=|DataDirectory|\Database.sdf";

Change the DataDirectory to your executable path

string path = AppDomain.CurrentDomain.BaseDirectory;
AppDomain.CurrentDomain.SetData("DataDirectory", path);

If you are using EntityFramework, then you can set the DataDirectory path in your Context class

How can I join multiple SQL tables using the IDs?

Simple INNER JOIN VIEW code....

CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;

Bash scripting, multiple conditions in while loop

The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))

Some notes:

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

  2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

How to download the latest artifact from Artifactory repository?

Artifactory has a good extensive REST-API and almost anything that can be done in the UI (perhaps even more) can also be done using simple HTTP requests.

The feature that you mention - retrieving the latest artifact, does indeed require the Pro edition; but it can also be achieved with a bit of work on your side and a few basic scripts.

Option 1 - Search:

Perform a GAVC search on a set of group ID and artifact ID coordinates to retrieve all existing versions of that set; then you can use any version string comparison algorithm to determine the latest version.

Option 2 - the Maven way:

Artifactory generates a standard XML metadata that is to be consumed by Maven, because Maven is faced with the same problem - determining the latest version; The metadata lists all available versions of an artifact and is generated for every artifact level folder; with a simple GET request and some XML parsing, you can discover the latest version.

Android SDK Setup under Windows 7 Pro 64 bit

The following solution was implemented because recently our IDE stopped compiling and building [refresh or clean] on the standard Eclipse IDE for Java Developers version. We kept receiving the error "Your project contains error(s), please fix it before running it." We reviewed all errors, cleaned over and over, rebuilt and even created a new workspace and imported the files however nothing worked. Our product manager Johnpaul, found the error with in the compiled build path and even though it was a manual fix it would come back on the next refresh or rebuild so he recommended we back-up our work-space and do a complete re-install of the developers environment.

We made the switch as a recommendation we found from: http://knol.google.com/k/fred-grott/which-eclipse-package-for-android/166jfml0mowlh/18#report-comment-166jfml0mowlh.7wc65w

We now use the Eclipse IDE [Indigo]for Java and Report Developers Windows 64 Bit without a problem.

After the IDE broke we downloaded:

  • Java Developer Environment with jdk-6u26-windows-x64
  • Eclipse Indigo IDE for Java and Report Developers Windows 64 Bit
  • Android SDK Tools installer_r13-windows

We then:

  • Disconnected from the internet
  • Disabled all Anti-virus programs
  • Disabled our Firewalls

Next we:

  • Uninstalled our SDK via the Eclipse IDE line by line,
  • Updated [installed] our Java Developer Environment with jdk-6u26-windows-x64
  • Unpacked and over wrote Eclipse with the new Indigo "Eclipse IDE for Java and Report Developers"

Windows 64 Bit

  • List item
  • Turned our anti-virus back on and connected to the internet
  • Reinstalled Android SDK Tools installer_r13-windows

We kept all of the default preferences and now everything is working perfectly again. Actually better as the rewrite also solved a few problems with our app not working on some devices. No idea as to why but we aren't complaining. Hope this helps as it is not a true install however a reinstall for Fall 2011 in a Windows 7 64 bit environment.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

you can try something like this, or just copy and past below piece.

boolean exception = true;
Charset charset = Charset.defaultCharset(); //Try the default one first.        
int index = 0;

while(exception) {
    try {
        lines = Files.readAllLines(f.toPath(),charset);
          for (String line: lines) {
              line= line.trim();
              if(line.contains(keyword))
                  values.add(line);
              }           
        //No exception, just returns
        exception = false; 
    } catch (IOException e) {
        exception = true;
        //Try the next charset
        if(index<Charset.availableCharsets().values().size())
            charset = (Charset) Charset.availableCharsets().values().toArray()[index];
        index ++;
    }
}

Why is my xlabel cut off in my matplotlib plot?

An easy option is to configure matplotlib to automatically adjust the plot size. It works perfectly for me and I'm not sure why it's not activated by default.

Method 1

Set this in your matplotlibrc file

figure.autolayout : True

See here for more information on customizing the matplotlibrc file: http://matplotlib.org/users/customizing.html

Method 2

Update the rcParams during runtime like this

from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})

The advantage of using this approach is that your code will produce the same graphs on differently-configured machines.

Document directory path of Xcode Device Simulator

I faced the same issue when I stored the full path using CoreData. When retrieving the full path, it return null because the document folder UUID is different every time the app restarts. Following is my resolution:

  1. Make sure storing only the relative path of the document / file in CoreData. E.g. store "Files/image.jpg" instead of "/Users/yourname/.../Applications/UUID/Document/Files/image.jpg".
  2. Use the following to retrieve the app document location:

    [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

  3. Concatenate both #2 and #1 to get the full path of the document / file you want to retrieve.
You can refer to Apple Developer Note: https://developer.apple.com/library/ios/technotes/tn2406/_index.html

An efficient way to transpose a file in Bash

Have a look at GNU datamash which can be used like datamash transpose. A future version will also support cross tabulation (pivot tables)

Here is how you would do it with space separated columns:

datamash transpose -t ' ' < file > transposed_file

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

You may also get :

Could not load file or assembly 'WebMatrix.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This has moved to this package

 Install-Package Microsoft.AspNet.WebPages.Data

You should probably do a clean build before attempting any of the answers to this question and after updating packages

Programmatically register a broadcast receiver

for LocalBroadcastManager

   Intent intent = new Intent("any.action.string");
   LocalBroadcastManager.getInstance(context).
                                sendBroadcast(intent);

and register in onResume

LocalBroadcastManager.getInstance(
                    ActivityName.this).registerReceiver(chatCountBroadcastReceiver, filter);

and Unregister it onStop

LocalBroadcastManager.getInstance(
                ActivityName.this).unregisterReceiver(chatCountBroadcastReceiver);

and recieve it ..

mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("mBroadcastReceiver", "onReceive");
        }
    };

where IntentFilter is

 new IntentFilter("any.action.string")

How can I access a hover state in reactjs?

I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

onMouseOver={() => this.onMouseOver(someId)}
onMouseOut={() => this.onMouseOut(someId)

And implement the map as follows:

onMouseOver(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = setTimeout(() => {
    scrollPreviewToComponentId(listId);
  }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
  this.hoverHandleMap[listId] = handle;
}

onMouseOut(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = this.hoverHandleMap[listId];
  clearTimeout(handle);
  delete this.hoverHandleMap[listId];
}

And the map is like so,

hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};

I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

MySQL Error 1093 - Can't specify target table for update in FROM clause

According to the Mysql UPDATE Syntax linked by @CheekySoft, it says right at the bottom.

Currently, you cannot update a table and select from the same table in a subquery.

I guess you are deleting from store_category while still selecting from it in the union.

How to generate sample XML documents from their DTD or XSD?

Seems like nobody was able to answer the question so far :)

I use EclipseLink's MOXy to dynamically generate binding classes and then recursively go through the bound types. It is somewhat heavy, but it allows XPath value injection once the object tree is instantiated:

InputStream in = new FileInputStream(PATH_TO_XSD);
DynamicJAXBContext jaxbContext = 
            DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);
DynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);
DynamicEntity root = rootType.newDynamicEntity();
traverseProps(jaxbContext, root, rootType, 0);

TraverseProps is pretty simple recursive method:

private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{
        if (t!=null) {
            logger.info(indent(level) + "type [" + t.getName() + "] of class [" + t.getClassName() + "] has " + t.getNumberOfProperties() + " props");
            for (String pName:t.getPropertiesNames()){
                Class<?> clazz = t.getPropertyType(pName);
                logger.info(indent(level) + "prop [" + pName + "] in type: " + clazz);
                //logger.info("prop [" + pName + "] in entity: " + e.get(pName));

                if (clazz==null){
                    // need to create an instance of object
                    String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);
                    logger.info(indent(level) + "Creating new type instance for " + pName + " using following class name: " + updatedClassName );
                    DynamicType child = c.getDynamicType("generated." + updatedClassName);
                    DynamicEntity childEntity = child.newDynamicEntity();
                    e.set(pName, childEntity);
                    traverseProps(c, childEntity, child, level+1);
                } else {
                    // just set empty value
                    e.set(pName, clazz.newInstance());
                }
            }
        } else {
            logger.warn("type is null");
        }
    }

Converting everything to XML is pretty easy:

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);

Android Overriding onBackPressed()

Yes. Only override it in that one Activity with

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}

don't put this code in any other Activity

Is it possible to declare two variables of different types in a for loop?

No - but technically there is a work-around (not that i'd actually use it unless forced to):

for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}

Change Active Menu Item on Page Scroll?

It's done by binding to the scroll event of the container (usually window).

Quick example:

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});?

See the above in action at jsFiddle including scroll animation.

simple Jquery hover enlarge

Well I'm not exactly sure why your code is not working because I usually follow a different approach when trying to accomplish something similar.

But your code is erroring out.. There seems to be an issue with the way you are using scale I got the jQuery to actually execute by changing your code to the following.

$(document).ready(function(){
    $('img').hover(function() {
        $(this).css("cursor", "pointer");
        $(this).toggle({
          effect: "scale",
          percent: "90%"
        },200);
    }, function() {
         $(this).toggle({
           effect: "scale",
           percent: "80%"
         },200);

    });
});  

But I have always done it by using CSS to setup my scaling and transition..

Here is an example, hopefully it helps.

$(document).ready(function(){
    $('#content').hover(function() {
        $("#content").addClass('transition');

    }, function() {
        $("#content").removeClass('transition');
    });
});

http://jsfiddle.net/y4yAP/

Get an OutputStream into a String

This worked nicely

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();
    }
};

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream) is for working with XML. It is irrelevant to this topic.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....

How do you create a UIImage View Programmatically - Swift

In Swift 4.2 and Xcode 10.1

//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view

//Add image view properties like this(This is one of the way to add properties).  
extension UIImageView {
    //If you want only round corners
    func imgViewCorners() {
        layer.cornerRadius = 10
        layer.borderWidth = 1.0
        layer.masksToBounds = true
    }
}

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece::datetime() can eliminate T.

use Time::Piece;
print localtime->datetime(T => q{ });

Get the current displaying UIViewController on the screen in AppDelegate.m

extension UIApplication {
    /// The top most view controller
    static var topMostViewController: UIViewController? {
        return UIApplication.shared.keyWindow?.rootViewController?.visibleViewController
    }
}

extension UIViewController {
    /// The visible view controller from a given view controller
    var visibleViewController: UIViewController? {
        if let navigationController = self as? UINavigationController {
            return navigationController.topViewController?.visibleViewController
        } else if let tabBarController = self as? UITabBarController {
            return tabBarController.selectedViewController?.visibleViewController
        } else if let presentedViewController = presentedViewController {
            return presentedViewController.visibleViewController
        } else {
            return self
        }
    }
}

With this you can easily get the top post view controller like so

let viewController = UIApplication.topMostViewController

One thing to note is that if there's a UIAlertController currently being displayed, UIApplication.topMostViewController will return a UIAlertController.

How to round up integer division and have int result in Java?

Google's Guava library handles this in the IntMath class:

IntMath.divide(numerator, divisor, RoundingMode.CEILING);

Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.

Replace all elements of Python NumPy Array that are greater than some value

Lets us assume you have a numpy array that has contains the value from 0 all the way up to 20 and you want to replace numbers greater than 10 with 0

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21) # creates an array
my_arr[my_arr > 10] = 0 # modifies the value
_x000D_
_x000D_
_x000D_

Note this will however modify the original array to avoid overwriting the original array try using arr.copy() to create a new detached copy of the original array and modify that instead.

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21)
my_arr_copy = my_arr.copy() # creates copy of the orignal array

my_arr_copy[my_arr_copy > 10] = 0 
_x000D_
_x000D_
_x000D_

JFrame Exit on close Java

I spent quite a bit of time spelunking through the internet for an elegant solution to this. As is usually the case, I found a lot of conflicting information.

I finally ended with:

  1. Do not use EXIT_ON_CLOSE as this can leave resources behind;
  2. Do use something like the following in the JFrame initialization:

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    
  3. The real discovery was how to actually dispatch a window message to the JFrame. As an example, as part of your JMenuItem for exiting the application, use the following, where the function getFrame() returns a reference to the JFrame:

    public class AppMenuFileExit extends JMenuItem implements ActionListener
    {
        // do your normal menu item code here
    
          @Override
          public void actionPerformed(ActionEvent e)
          {
            WindowEvent we;
            we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING);
    
            App.getFrame().dispatchEvent(we);
          }
    }
    

    JFrame is a subclass of Window so may be cast to Window for this purpose.

  4. And, have the following in your JFrame class to handle Window messages:

    public class AppFrame extends JFrame implements WindowListener
    {
      // Do all the things you need to for the class
    
      @Override
      public void windowOpened(WindowEvent e)
      {}
      @Override
      public void windowClosing(WindowEvent e)
      {/* can do cleanup here if necessary */}
    
      @Override
      public void windowClosed(WindowEvent e)
      {
        dispose();
        System.exit(0);
      }
      @Override
      public void windowActivated(WindowEvent e)
      {}
      @Override
      public void windowDeactivated(WindowEvent e)
      {}    
      @Override
      public void windowDeiconified(WindowEvent e)
      {}
      @Override
      public void windowIconified(WindowEvent e)
      {}
    }
    

Angular ForEach in Angular4/Typescript?

in angular4 foreach like that. try this.

 selectChildren(data, $event) {
      let parentChecked = data.checked;
       this.hierarchicalData.forEach(obj => {
          obj.forEach(childObj=> {
            value.checked = parentChecked;
         });
      });
    }

Spaces cause split in path with PowerShell

Not sure if someone still needs it... I needed to invoke msbuild in powershell and following worked fine:

$MSBuild = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"

& $MSBuild $PathToSolution /p:OutDir=$OutDirVar /t:Rebuild /p:Configuration=Release

How to select the first element of a set with JSTL?

You can access individual elements with the array [] operator:

<c:out value="${attachments[0].id}" />

This will work for arrays and lists. It won't work for maps and sets. In that case you must put the key of the element inside the brackets.

OpenCV !_src.empty() in function 'cvtColor' error

If anyone is experiencing this same problem when reading a frame from a webcam [with code similar to "frame = cv2.VideoCapture(0)"] and work in Jupyter Notebook, you may try:

  1. ensure previously tried code is not running already and restart Jupyter Notebook kernel

  2. SEPARATE code "frame = cv2.VideoCapture(0)" in separate cell on place where it is [previous code put in cell above, code under put to cell down]

  3. then run all the code above cell where is "frame = cv2.VideoCapture(0)"

  4. then try run next cell with its only code "frame = cv2.VideoCapture(0)" - AND - till you will continue in executing other cells - ENSURE - that ASTERIX on the left side of this particular cell DISAPEAR and command order number appear instead - only then continue

  5. now you can try execute the rest of your code as your camera input should not be empty anymore :-)

  6. After end, ensure you close all your program and restart kernel to prepare it for another run

Count the number of Occurrences of a Word in a String

Java 8 version.

System.out.println(Pattern.compile("\\bmale cat")
            .splitAsStream("i have a male cat. the color of male cat is Black")
            .count()-1);

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

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

request.getRequestDispatcher(“url”) means the dispatch is relative to the current HTTP request.Means this is for chaining two servlets with in the same web application Example

RequestDispatcher reqDispObj = request.getRequestDispatcher("/home.jsp");

getServletContext().getRequestDispatcher(“url”) means the dispatch is relative to the root of the ServletContext.Means this is for chaining two web applications with in the same server/two different servers

Example

RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/ContextRoot/home.jsp");

How to stop a looping thread in Python?

Threaded stoppable function

Instead of subclassing threading.Thread, one can modify the function to allow stopping by a flag.

We need an object, accessible to running function, to which we set the flag to stop running.

We can use threading.currentThread() object.

import threading
import time


def doit(arg):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        print ("working on %s" % arg)
        time.sleep(1)
    print("Stopping as you wish.")


def main():
    t = threading.Thread(target=doit, args=("task",))
    t.start()
    time.sleep(5)
    t.do_run = False
    t.join()

if __name__ == "__main__":
    main()

The trick is, that the running thread can have attached additional properties. The solution builds on assumptions:

  • the thread has a property "do_run" with default value True
  • driving parent process can assign to started thread the property "do_run" to False.

Running the code, we get following output:

$ python stopthread.py                                                        
working on task
working on task
working on task
working on task
working on task
Stopping as you wish.

Pill to kill - using Event

Other alternative is to use threading.Event as function argument. It is by default False, but external process can "set it" (to True) and function can learn about it using wait(timeout) function.

We can wait with zero timeout, but we can also use it as the sleeping timer (used below).

def doit(stop_event, arg):
    while not stop_event.wait(1):
        print ("working on %s" % arg)
    print("Stopping as you wish.")


def main():
    pill2kill = threading.Event()
    t = threading.Thread(target=doit, args=(pill2kill, "task"))
    t.start()
    time.sleep(5)
    pill2kill.set()
    t.join()

Edit: I tried this in Python 3.6. stop_event.wait() blocks the event (and so the while loop) until release. It does not return a boolean value. Using stop_event.is_set() works instead.

Stopping multiple threads with one pill

Advantage of pill to kill is better seen, if we have to stop multiple threads at once, as one pill will work for all.

The doit will not change at all, only the main handles the threads a bit differently.

def main():
    pill2kill = threading.Event()
    tasks = ["task ONE", "task TWO", "task THREE"]

    def thread_gen(pill2kill, tasks):
        for task in tasks:
            t = threading.Thread(target=doit, args=(pill2kill, task))
            yield t

    threads = list(thread_gen(pill2kill, tasks))
    for thread in threads:
        thread.start()
    time.sleep(5)
    pill2kill.set()
    for thread in threads:
        thread.join()

Reading NFC Tags with iPhone 6 / iOS 8

The ability to read an NFC tag has been added to iOS 11 which only support iPhone 7 and 7 plus

As a test drive I made this repo

First: We need to initiate NFCNDEFReaderSession class

var session: NFCNDEFReaderSession? 
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)

Then we need to start the session by:

session?.begin()

and when done:

session?.invalidate()

The delegate (which self should implement) has basically two functions:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage])
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error)

here is my reference Apple docs

How to get the date from jQuery UI datepicker

Use

var jsDate = $('#your_datepicker_id').datepicker('getDate');
if (jsDate !== null) { // if any date selected in datepicker
    jsDate instanceof Date; // -> true
    jsDate.getDate();
    jsDate.getMonth();
    jsDate.getFullYear();
}

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

Pandas dataframe fillna() only some columns in place

Here's how you can do it all in one line:

df[['a', 'b']].fillna(value=0, inplace=True)

Breakdown: df[['a', 'b']] selects the columns you want to fill NaN values for, value=0 tells it to fill NaNs with zero, and inplace=True will make the changes permanent, without having to make a copy of the object.

Android ListView selected item stay highlighted

From Avinash Kumar Pankaj's example

View v;

then at oncreate method

v = new View(getActivity());

and then onlistitemclick method i wrote

public void onListItemClick(ListView listView, View view, int position,
       long id) {
   v.setBackgroundResource(0);
   view.setBackgroundResource(R.color.green);
   v = view;
}

It worked for me. Thank you.

I replaced

v = new View(getActivity());

to

v = new View(this);

and the code worked well.

It is necessary the xml files 'colors' and 'bg_key' from previous examples too, as well as ListView attribute android:background="@drawable/bg_key"

Mauro

Converting a byte array to PNG/JPG

You should be able to do something like this:

byte[] bitmap = GetYourImage();

using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
    image.Save("output.jpg", ImageFormat.Jpeg);  // Or Png
}

Look here for more info.

Hopefully this helps.

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

Char array to hex string C++

The simplest:

int main()
{
    const char* str = "hello";
    for (const char* p = str; *p; ++p)
    {
        printf("%02x", *p);
    }
    printf("\n");
    return 0;
}

How to convert <font size="10"> to px?

Using the data points from the accepted answer you can use polynomial interpolation to obtain a formula.

WolframAlpha Input: interpolating polynomial {{1,.63},{2,.82}, {3,1}, {4,1.13}, {5,1.5}, {6, 2}, {7,3}}

Formula: 0.00223611x^6 - 0.0530417x^5 + 0.496319x^4 - 2.30479x^3 + 5.51644x^2 - 6.16717x + 3.14

And use in Groovy code:

import java.math.*
def convert = {x -> (0.00223611*x**6 - 0.053042*x**5 + 0.49632*x**4 - 2.30479*x**3 + 5.5164*x**2 - 6.167*x + 3.14).setScale(2, RoundingMode.HALF_UP) }
(1..7).each { i -> println(convert(i)) }

Angular 2 Scroll to bottom (Chat style)

Vivek's answer has worked for me, but resulted in an expression has changed after it was checked error. None of the comments worked for me, but what I did was change the change detection strategy.

import {  Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'page1',
  templateUrl: 'page1.html',
})

Processing $http response in service

Related to this I went through a similar problem, but not with get or post made by Angular but with an extension made by a 3rd party (in my case Chrome Extension).
The problem that I faced is that the Chrome Extension won't return then() so I was unable to do it the way in the solution above but the result is still Asynchronous.
So my solution is to create a service and to proceed to a callback

app.service('cookieInfoService', function() {
    this.getInfo = function(callback) {
        var model = {};
        chrome.cookies.get({url:serverUrl, name:'userId'}, function (response) {
            model.response= response;
            callback(model);
        });
    };
});

Then in my controller

app.controller("MyCtrl", function ($scope, cookieInfoService) {
    cookieInfoService.getInfo(function (info) {
        console.log(info);
    });
});

Hope this can help others getting the same issue.

Android Horizontal RecyclerView scroll Direction

You can do it with just xml.

the app:reverseLayout="true" do the job!

<android.support.v7.widget.RecyclerView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:divider="@null"
                        android:orientation="horizontal"
                        app:reverseLayout="true"
                        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

How to change a dataframe column from String type to Double type in PySpark?

There is no need for an UDF here. Column already provides cast method with DataType instance :

from pyspark.sql.types import DoubleType

changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))

or short string:

changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))

where canonical string names (other variations can be supported as well) correspond to simpleString value. So for atomic types:

from pyspark.sql import types 

for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType', 
          'DecimalType', 'DoubleType', 'FloatType', 'IntegerType', 
           'LongType', 'ShortType', 'StringType', 'TimestampType']:
    print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp

and for example complex types

types.ArrayType(types.IntegerType()).simpleString()   
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'

How to develop or migrate apps for iPhone 5 screen resolution?

I solve this problem here. Just add ~568h@2x suffix to images and ~568h to xib's. No needs more runtime checks or code changes.

Can't use SURF, SIFT in OpenCV

The following page provides a relatively good guide that requires few corrections : https://cv-tricks.com/how-to/installation-of-opencv-4-1-0-in-windows-10-from-source/

On step 8, when you are choosing generator for the project (tool used for building), don't forget to specify x64 in the second field if you need it. If you don't, you will get LNK1112 error, which is a linker error caused if one module is created with the x64 compiler, and another module is created with the x86 compiler.

Next, when choosing flags in step 9, don't forget to tick the "OPENCV_ENABLE_NONFREE", and set the path for flag "OPENCV_EXTRA_MODULES_PATH" flag. The path must be set to "modules" folder in opencv-contrib-python.

So you need both opencv, and opencv-contrib-python in order to use SIFT and SURF.

Deep copy in ES6 using the spread syntax

No such functionality is built-in to ES6. I think you have a couple of options depending on what you want to do.

If you really want to deep copy:

  1. Use a library. For example, lodash has a cloneDeep method.
  2. Implement your own cloning function.

Alternative Solution To Your Specific Problem (No Deep Copy)

However, I think, if you're willing to change a couple things, you can save yourself some work. I'm assuming you control all call sites to your function.

  1. Specify that all callbacks passed to mapCopy must return new objects instead of mutating the existing object. For example:

    mapCopy(state, e => {
      if (e.id === action.id) {
        return Object.assign({}, e, {
          title: 'new item'
        });
      } else {  
        return e;
      }
    });
    

    This makes use of Object.assign to create a new object, sets properties of e on that new object, then sets a new title on that new object. This means you never mutate existing objects and only create new ones when necessary.

  2. mapCopy can be really simple now:

    export const mapCopy = (object, callback) => {
      return Object.keys(object).reduce(function (output, key) {
        output[key] = callback.call(this, object[key]);
        return output;
      }, {});
    }
    

Essentially, mapCopy is trusting its callers to do the right thing. This is why I said this assumes you control all call sites.

What is the meaning of curly braces?

In languages like C curly braces ({}) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

c# - How to get sum of the values from List?

You can use LINQ for this

var list = new List<int>();
var sum = list.Sum();

and for a List of strings like Roy Dictus said you have to convert

list.Sum(str => Convert.ToInt32(str));

Java 8 Lambda function that throws exception?

You can actually extend Consumer (and Function etc.) with a new interface that handles exceptions -- using Java 8's default methods!

Consider this interface (extends Consumer):

@FunctionalInterface
public interface ThrowingConsumer<T> extends Consumer<T> {

    @Override
    default void accept(final T elem) {
        try {
            acceptThrows(elem);
        } catch (final Exception e) {
            // Implement your own exception handling logic here..
            // For example:
            System.out.println("handling an exception...");
            // Or ...
            throw new RuntimeException(e);
        }
    }

    void acceptThrows(T elem) throws Exception;

}

Then, for example, if you have a list:

final List<String> list = Arrays.asList("A", "B", "C");

If you want to consume it (eg. with forEach) with some code that throws exceptions, you would traditionally have set up a try/catch block:

final Consumer<String> consumer = aps -> {
    try {
        // maybe some other code here...
        throw new Exception("asdas");
    } catch (final Exception ex) {
        System.out.println("handling an exception...");
    }
};
list.forEach(consumer);

But with this new interface, you can instantiate it with a lambda expression and the compiler will not complain:

final ThrowingConsumer<String> throwingConsumer = aps -> {
    // maybe some other code here...
    throw new Exception("asdas");
};
list.forEach(throwingConsumer);

Or even just cast it to be more succinct!:

list.forEach((ThrowingConsumer<String>) aps -> {
    // maybe some other code here...
    throw new Exception("asda");
});

Update: Looks like there's a very nice utility library part of Durian called Errors which can be used to solve this problem with a lot more flexibility. For example, in my implementation above I've explicitly defined the error handling policy (System.out... or throw RuntimeException), whereas Durian's Errors allow you to apply a policy on the fly via a large suite of utility methods. Thanks for sharing it, @NedTwigg!.

Sample usage:

list.forEach(Errors.rethrow().wrap(c -> somethingThatThrows(c)));

SSL Error: CERT_UNTRUSTED while using npm command

I think I got the reason for the above error. It is the corporate proxy(virtual private network) provided in order to work in the client network. Without that connection I frequently faced the same problem be it maven build or npm install.

must appear in the GROUP BY clause or be used in an aggregate function

SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
    SELECT cname, MAX(avg) max
    FROM makerar
    GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;

Using rank() window function:

SELECT cname, wmname, avg
FROM (
    SELECT cname, wmname, avg, rank() 
    OVER (PARTITION BY cname ORDER BY avg DESC)
    FROM makerar) t
WHERE rank = 1;

Note

Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.

composer laravel create project

make sure that your composer is up to date. write in the cmd

composer create-project –-prefer-dist laravel/laravel NameOfProject "Version" 

How do I convert a Swift Array to a String?

In Swift 2.2 you may have to cast your array to NSArray to use componentsJoinedByString(",")

let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")

How to execute an SSIS package from .NET?

You can use this Function if you have some variable in the SSIS.

    Package pkg;

    Microsoft.SqlServer.Dts.Runtime.Application app;
    DTSExecResult pkgResults;
    Variables vars;

    app = new Microsoft.SqlServer.Dts.Runtime.Application();
    pkg = app.LoadPackage(" Location of your SSIS package", null);

    vars = pkg.Variables;

    // your variables
    vars["somevariable1"].Value = "yourvariable1";
    vars["somevariable2"].Value = "yourvariable2";

    pkgResults = pkg.Execute(null, vars, null, null, null);

    if (pkgResults == DTSExecResult.Success)
    {
        Console.WriteLine("Package ran successfully");
    }
    else
    {

        Console.WriteLine("Package failed");
    }

Permissions for /var/www/html

You just need 775 for /var/www/html as long as you are logging in as myuser. The 7 octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:

chmod -R g+w /var/www/html

Refused to load the script because it violates the following Content Security Policy directive

It was solved with:

script-src 'self' http://xxxx 'unsafe-inline' 'unsafe-eval';

display: flex not working on Internet Explorer

Am afraid this question has been answered a few times, Pls take a look at the following if it's related

Boolean Field in Oracle

Either 1/0 or Y/N with a check constraint on it. ether way is fine. I personally prefer 1/0 as I do alot of work in perl, and it makes it really easy to do perl Boolean operations on database fields.

If you want a really in depth discussion of this question with one of Oracles head honchos, check out what Tom Kyte has to say about this Here

What's the best way to check if a String represents an integer in Java?

For kotlin, isDigitsOnly() (Also for Java's TextUtils.isDigitsOnly()) of String always returns false it has a negative sign in front though the rest of the character is digit only. For example -

/** For kotlin*/
var str = "-123" 
str.isDigitsOnly()  //Result will be false 

/** For Java */
String str = "-123"
TextUtils.isDigitsOnly(str) //Result will be also false 

So I made a quick fix by this -

 var isDigit=str.matches("-?\\d+(\\.\\d+)?".toRegex()) 
/** Result will be true for now*/

Getting and removing the first character of a string

Another alternative is to use capturing sub-expressions with the regular expression functions regmatches and regexec.

# the original example
x <- 'hello stackoverflow'

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))

This returns the entire string, the first character, and the "popped" result in a list of length 1.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). That is, it contains the super set of the desired elements as well as the full string.


Adding sapply will allow this method to work for a character vector of length > 1.

# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))

This returns a list with the matched full string as the first element and the matching subexpressions captured by () as the following elements. So in the regular expression '(^.)(.*)', (^.) matches the first character and (.*) matches the remaining characters.

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

[[2]]
[1] "right back" "r"          "ight back" 

[[3]]
[1] "at yah" "a"      "t yah" 

Now, we can use the trusty sapply + [ method to pull out the desired substrings.

myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back"          "t yah"

Checking if a key exists in a JavaScript object?

The accepted answer refers to Object. Beware using the in operator on Array to find data instead of keys:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)

To test existing elements in an Array: Best way to find if an item is in a JavaScript array?

What is the purpose of Android's <merge> tag in XML layouts?

Another reason to use merge is when using custom viewgroups in ListViews or GridViews. Instead of using the viewHolder pattern in a list adapter, you can use a custom view. The custom view would inflate an xml whose root is a merge tag. Code for adapter:

public class GridViewAdapter extends BaseAdapter {
     // ... typical Adapter class methods
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
        WallpaperView wallpaperView;
        if (convertView == null)
           wallpaperView = new WallpaperView(activity);
        else
            wallpaperView = (WallpaperView) convertView;

        wallpaperView.loadWallpaper(wallpapers.get(position), imageWidth);
        return wallpaperView;
    }
}

here is the custom viewgroup:

public class WallpaperView extends RelativeLayout {

    public WallpaperView(Context context) {
        super(context);
        init(context);
    }
    // ... typical constructors

    private void init(Context context) {
        View.inflate(context, R.layout.wallpaper_item, this);
        imageLoader = AppController.getInstance().getImageLoader();
        imagePlaceHolder = (ImageView) findViewById(R.id.imgLoader2);
        thumbnail = (NetworkImageView) findViewById(R.id.thumbnail2);
        thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    public void loadWallpaper(Wallpaper wallpaper, int imageWidth) {
        // ...some logic that sets the views
    }
}

and here is the XML:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/imgLoader"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerInParent="true"
        android:src="@drawable/ico_loader" />

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</merge>

Fastest way to serialize and deserialize .NET objects

Protobuf is very very fast.

See http://code.google.com/p/protobuf-net/wiki/Performance for in depth information concerning the performance of this system, and an implementation.

Ruby value of a hash key?

It seems that your question is maybe a bit ambiguous.

If “values” in the first sentence means any generic value (i.e. object, since everything in Ruby can be viewed as an object), then one of the other answers probably tells you what you need to know (i.e. use Hash#[] (e.g. hash[some_key]) to find the value associated with a key).

If, however, “values” in first sentence is taken to mean the value part of the “key, value pairs” (as are stored in hashes), then your question seems like it might be about working in the other direction (key for a given value).

You can find a key that leads to a certain value with Hash#key.

ruby-1.9.2-head :001 > hash = { :a => '1', :b => :two, :c => 3, 'bee' => :two }
 => {:a=>"1", :b=>:two, :c=>3, "bee"=>:two} 
ruby-1.9.2-head :002 > a_value = :two
 => :two 
ruby-1.9.2-head :003 > hash.key(a_value)
 => :b 

If you are using a Ruby earlier than 1.9, you can use Hash#index.

When there are multiple keys with the desired value, the method will only return one of them. If you want all the keys with a given value, you may have to iterate a bit:

ruby-1.9.2-head :004 > hash[:b] == hash['bee']
 => true 
ruby-1.9.2-head :005 > keys = hash.inject([]) do # all keys with value a_value
ruby-1.9.2-head :006 >       |l,kv| kv[1] == a_value ? l << kv[0] : l
ruby-1.9.2-head :007?>   end
 => [:b, "bee"] 

Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera. Just how you compare them depends on the kind of objects you are using for keys (people often use strings and symbols, but Ruby hashes can use any kind of object as keys (as long as they are not modified while they serve as keys)).

Set ANDROID_HOME environment variable in mac

Based on Abraham Mayowa Oluwasina answer provided above is the correct one. MacOS Catalina, .bash_profile is no longer apple's default shell and it won't persist your path variables instead use .zprofile instead.

In root directory,

touch .zprofile
open -e .zprofile

Add the following in file,

export ANDROID_HOME=/Users/<username>/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/platform-tools

Save and exit

To activate

source ~/. zprofile

echo $ANDROID_HOME

ArrayAdapter in android to create simple listview

ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString() method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.

For your use, I would suggest that you use the constructor:

ArrayAdapter(Context context, int resource, T[] objects). 

In your case, this would be:

ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)

and it should be fine. This will bind each string to the default TextView display - plain and simple white background.

So to answer your question, you do not have to use the textViewResourceId.

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

Nobody mentioned this, but IETester is a great tool. It supports Internet Explorer 5.5, 6, 7 and 8RC1. The rendering matches the corresponding browsers. At least I haven't found any discrepancies yet.

I normally use it to do a basic check of the layout. I still need VMs to debug JavaScript or to use the Developer Toolbar with a specific Internet Explorer version.

IETester 0.3

How can I check for an empty/undefined/null string in JavaScript?

function tell()
{
    var pass = document.getElementById('pasword').value;
    var plen = pass.length;

    // Now you can check if your string is empty as like
    if(plen==0)
    {
        alert('empty');
    }
    else
    {
        alert('you entered something');
    }
}

<input type='text' id='pasword' />

This is also a generic way to check if field is empty.

UTF-8 byte[] to String

String has a constructor that takes byte[] and charsetname as parameters :)

Convert string to buffer Node

This is working for me, you might change your code like this

var responseData=x.toString();

to

var responseData=x.toString("binary");

and finally

response.write(new Buffer(toTransmit, "binary"));

405 method not allowed Web API

I was getting the 405 on my GET call, and the problem turned out that I named the parameter in the GET server-side method Get(int formId), and I needed to change the route, or rename it Get(int id).

Creating a PHP header/footer

the simpler, the better.

index.php

<? 
if (empty($_SERVER['QUERY_STRING'])) { 
  $name="index"; 
} else { 
  $name=basename($_SERVER['QUERY_STRING']); 
} 
$file="txt/".$name.".htm"; 
if (is_readable($file)) { 
  include 'header.php';
  readfile($file);
} else { 
  header("HTTP/1.0 404 Not Found");
  exit;
} 
?>

header.php

<a href="index.php">Main page</a><br>
<a href=?about>About</a><br>
<a href=?links>Links</a><br>
<br><br> 

the actual static html pages stored in the txt folder in the page.htm format

how to split the ng-repeat data with three columns using bootstrap

All of these answers seem massively over engineered.

By far the simplest method would be to set up the input divs in a col-md-4 column bootstrap, then bootstrap will automatically format it into 3 columns due to the 12 column nature of bootstrap:

<div class="col-md-12">
    <div class="control-group" ng-repeat="oneExt in configAddr.ext">
        <div class="col-md-4">
            <input type="text" name="macAdr{{$index}}"
                   id="macAddress" ng-model="oneExt.newValue" value="" />
        </div>
    </div>
</div>

Does JavaScript have a built in stringbuilder class?

No, there is no built-in support for building strings. You have to use concatenation instead.

You can, of course, make an array of different parts of your string and then call join() on that array, but it then depends on how the join is implemented in the JavaScript interpreter you are using.

I made an experiment to compare the speed of str1+str2 method versus array.push(str1, str2).join() method. The code was simple:

var iIterations =800000;
var d1 = (new Date()).valueOf();
str1 = "";
for (var i = 0; i<iIterations; i++)
    str1 = str1 + Math.random().toString();
var d2 = (new Date()).valueOf();
log("Time (strings): " + (d2-d1));

var d3 = (new Date()).valueOf();
arr1 = [];
for (var i = 0; i<iIterations; i++)
    arr1.push(Math.random().toString());
var str2 = arr1.join("");
var d4 = (new Date()).valueOf();
log("Time (arrays): " + (d4-d3));

I tested it in Internet Explorer 8 and Firefox 3.5.5, both on a Windows 7 x64.

In the beginning I tested on small number of iterations (some hundred, some thousand items). The results were unpredictable (sometimes string concatenation took 0 milliseconds, sometimes it took 16 milliseconds, the same for array joining).

When I increased the count to 50,000, the results were different in different browsers - in Internet Explorer the string concatenation was faster (94 milliseconds) and join was slower(125 milliseconds), while in Firefox the array join was faster (113 milliseconds) than string joining (117 milliseconds).

Then I increased the count to 500'000. Now the array.join() was slower than string concatenation in both browsers: string concatenation was 937 ms in Internet Explorer, 1155 ms in Firefox, array join 1265 in Internet Explorer, and 1207 ms in Firefox.

The maximum iteration count I could test in Internet Explorer without having "the script is taking too long to execute" was 850,000. Then Internet Explorer was 1593 for string concatenation and 2046 for array join, and Firefox had 2101 for string concatenation and 2249 for array join.

Results - if the number of iterations is small, you can try to use array.join(), as it might be faster in Firefox. When the number increases, the string1+string2 method is faster.

UPDATE

I performed the test on Internet Explorer 6 (Windows XP). The process stopped to respond immediately and never ended, if I tried the test on more than 100,000 iterations. On 40,000 iterations the results were

Time (strings): 59175 ms
Time (arrays): 220 ms

This means - if you need to support Internet Explorer 6, choose array.join() which is way faster than string concatenation.

How to set default font family for entire Android app

The answer is yes.

Global Roboto light for TextView and Button classes:

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:textViewStyle">@style/RobotoTextViewStyle</item>
    <item name="android:buttonStyle">@style/RobotoButtonStyle</item>
</style>

<style name="RobotoTextViewStyle" parent="android:Widget.TextView">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="RobotoButtonStyle" parent="android:Widget.Holo.Button">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

Just select the style you want from list themes.xml, then create your custom style based on the original one. At the end, apply the style as the theme of the application.

<application
    android:theme="@style/AppTheme" >
</application>

It will work only with built-in fonts like Roboto, but that was the question. For custom fonts (loaded from assets for example) this method will not work.

EDIT 08/13/15

If you're using AppCompat themes, remember to remove android: prefix. For example:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:textViewStyle">@style/RobotoTextViewStyle</item>
    <item name="buttonStyle">@style/RobotoButtonStyle</item>
</style>

Note the buttonStyle doesn't contain android: prefix, but textViewStyle must contain it.

Set NA to 0 in R

A solution using mutate_all from dplyr in case you want to add that to your dplyr pipeline:

library(dplyr)
df %>%
  mutate_all(funs(ifelse(is.na(.), 0, .)))

Result:

   A B C
1  0 0 0
2  1 0 0
3  2 0 2
4  3 0 5
5  0 0 2
6  0 0 1
7  1 0 1
8  2 0 5
9  3 0 2
10 0 0 4
11 0 0 3
12 1 0 5
13 2 0 5
14 3 0 0
15 0 0 1

If in any case you only want to replace the NA's in numeric columns, which I assume it might be the case in modeling, you can use mutate_if:

library(dplyr)
df %>%
  mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))

or in base R:

replace(is.na(df), 0)

Result:

   A    B C
1  0    0 0
2  1 <NA> 0
3  2    0 2
4  3 <NA> 5
5  0    0 2
6  0 <NA> 1
7  1    0 1
8  2 <NA> 5
9  3    0 2
10 0 <NA> 4
11 0    0 3
12 1 <NA> 5
13 2    0 5
14 3 <NA> 0
15 0    0 1

Update

with dplyr 1.0.0, across is introduced:

library(dplyr)
# Replace `NA` for all columns
df %>%
  mutate(across(everything(), ~ ifelse(is.na(.), 0, .)))

# Replace `NA` for numeric columns
df %>%
  mutate(across(where(is.numeric), ~ ifelse(is.na(.), 0, .)))

Data:

set.seed(123)
df <- data.frame(A=rep(c(0:3, NA), 3), 
                 B=rep(c("0", NA), length.out = 15), 
                 C=sample(c(0:5, NA), 15, replace = TRUE))

How to detect the end of loading of UITableView

The best approach that I know is Eric's answer at: Get notified when UITableView has finished asking for data?

Update: To make it work I have to put these calls in -tableView:cellForRowAtIndexPath:

[tableView beginUpdates];
[tableView endUpdates];

Node.js: How to read a stream into a buffer?

in ts, [].push(bufferPart) is not compatible;

so:

getBufferFromStream(stream: Part | null): Promise<Buffer> {
    if (!stream) {
        throw 'FILE_STREAM_EMPTY';
    }
    return new Promise(
        (r, j) => {
            let buffer = Buffer.from([]);
            stream.on('data', buf => {
               buffer = Buffer.concat([buffer, buf]);
            });
            stream.on('end', () => r(buffer));
            stream.on('error', j);
        }
    );
}

How to set a background image in Xcode using swift?

SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage

How to define a circle shape in an Android XML drawable file?

Look in the Android SDK samples. There are several examples in the ApiDemos project:

/ApiDemos/res/drawable/

  • black_box.xml
  • shape_5.xml
  • etc

It will look something like this for a circle with a gradient fill:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
            android:angle="270"/>
</shape>

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.

// capture ctrl+c and stop CPU profiler                            
c := make(chan os.Signal, 1)                                       
signal.Notify(c, os.Interrupt)                                     
go func() {                                                        
  for sig := range c {                                             
    log.Printf("captured %v, stopping profiler and exiting..", sig)
    pprof.StopCPUProfile()                                         
    os.Exit(1)                                                     
  }                                                                
}()    

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

CentOS: Enabling GD Support in PHP Installation

CentOs 6.5+ & PHP 5.6:

sudo yum install php56-gd

service httpd restart

How to trigger an event after using event.preventDefault()

A more recent version of the accepted answer.

Brief version:

$('#form').on('submit', function(e, options) {
    options = options || {};

    if ( !options.lots_of_stuff_done ) {
        e.preventDefault();
        $.ajax({
            /* do lots of stuff */
        }).then(function() {
            // retrigger the submit event with lots_of_stuff_done set to true
            $(e.currentTarget).trigger('submit', { 'lots_of_stuff_done': true });
        });
    } else {
        /* allow default behavior to happen */
    }

});



A good use case for something like this is where you may have some legacy form code that works, but you've been asked to enhance the form by adding something like email address validation before submitting the form. Instead of digging through the back-end form post code, you could write an API and then update your front-end code to hit that API first before allowing the form to do it's traditional POST.

To do that, you can implement code similar to what I've written here:

$('#signup_form').on('submit', function(e, options) {
    options = options || {};

    if ( !options.email_check_complete ) {

        e.preventDefault(); // Prevent form from submitting.
        $.ajax({
            url: '/api/check_email'
            type: 'get',
            contentType: 'application/json',
            data: { 
                'email_address': $('email').val() 
            }
        })
        .then(function() {
            // e.type === 'submit', if you want this to be more dynamic
            $(e.currentTarget).trigger(e.type, { 'email_check_complete': true });
        })
        .fail(function() {
            alert('Email address is not valid. Please fix and try again.');
        })

    } else {

        /**
             Do traditional <form> post.
             This code will be hit on the second pass through this handler because
             the 'email_check_complete' option was passed in with the event.
         */

        $('#notifications').html('Saving your personal settings...').fadeIn();

    }

});

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

Interesting question! While there are plenty of guides on horizontally and vertically centering a div, an authoritative treatment of the subject where the centered div is of an unpredetermined width is conspicuously absent.

Let's apply some basic constraints:

  • No Javascript
  • No mangling of the display property to table-cell, which is of questionable support status

Given this, my entry into the fray is the use of the inline-block display property to horizontally center the span within an absolutely positioned div of predetermined height, vertically centered within the parent container in the traditional top: 50%; margin-top: -123px fashion.

Markup: div > div > span

CSS:

body > div { position: relative; height: XYZ; width: XYZ; }
div > div { 
  position: absolute;
  top: 50%;
  height: 30px;
  margin-top: -15px; 
  text-align: center;}
div > span { display: inline-block; }

Source: http://jsfiddle.net/38EFb/


An alternate solution that doesn't require extraneous markups but that very likely produces more problems than it solves is to use the line-height property. Don't do this. But it is included here as an academic note: http://jsfiddle.net/gucwW/

How to load data from a text file in a PostgreSQL database?

The slightly modified version of COPY below worked better for me, where I specify the CSV format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT.

COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );

BACKUP LOG cannot be performed because there is no current database backup

You can use following SQL to restore if you've already created database

RESTORE DATABASE [YourDB]
FROM DISK = 'C:\YourDB.bak'
WITH MOVE 'YourDB' TO 'C:\YourDB.mdf',
MOVE 'YourDB_Log' TO 'C:\YourDB.ldf', REPLACE

How does Facebook disable the browser's integrated Developer Tools?

I located the Facebook's console buster script using Chrome developer tools. Here is the script with minor changes for readability. I have removed the bits that I could not understand:

Object.defineProperty(window, "console", {
    value: console,
    writable: false,
    configurable: false
});

var i = 0;
function showWarningAndThrow() {
    if (!i) {
        setTimeout(function () {
            console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
        }, 1);
        i = 1;
    }
    throw "Console is disabled";
}

var l, n = {
        set: function (o) {
            l = o;
        },
        get: function () {
            showWarningAndThrow();
            return l;
        }
    };
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);

With this, the console auto-complete fails silently while statements typed in console will fail to execute (the exception will be logged).

References:

How do I display a decimal value to 2 decimal places?

If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits):

decimal val = 3.14789m;
decimal result = Math.Floor(val * 100) / 100; // result = 3.14

If you need to keep only 3 decimal places:

decimal val = 3.14789m;
decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147

How to add a TextView to a LinearLayout dynamically in Android?

I customized more @Suragch code. My output looks

enter image description here

I wrote a method to stop code redundancy.

public TextView createATextView(int layout_widh, int layout_height, int align,
        String text, int fontSize, int margin, int padding) {

    TextView textView_item_name = new TextView(this);

    // LayoutParams layoutParams = new LayoutParams(
    // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    // layoutParams.gravity = Gravity.LEFT;
    RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
            layout_widh, layout_height);

    _params.setMargins(margin, margin, margin, margin);
    _params.addRule(align);
    textView_item_name.setLayoutParams(_params);

    textView_item_name.setText(text);
    textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
    textView_item_name.setTextColor(Color.parseColor("#000000"));
    // textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView_item_name.setPadding(padding, padding, padding, padding);

    return textView_item_name;

}

It can be called like

createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20);

Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.

    RelativeLayout primary_layout = new RelativeLayout(this);

    LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);

    primary_layout.setLayoutParams(layoutParam);

    // FOR LINEAR LAYOUT SET ORIENTATION
    // primary_layout.setOrientation(LinearLayout.HORIZONTAL);

    // FOR BACKGROUND COLOR 
    primary_layout.setBackgroundColor(0xff99ccff);

    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
            20, 10, 20));
    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20));

How do I remove objects from a JavaScript associative array?

That only deletes the object, but it still keeps the array length the same.

To remove the element from the array, you need to do something like:

array.splice(index, 1);

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Official Notice: success and error have been deprecated, please use the standard then method instead.

Deprecation Notice: The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

link: https://code.angularjs.org/1.5.7/docs/api/ng/service/$http

screenshot: view the screenshot

Vertical (rotated) text in HTML table

Alternate Solution?

Instead of rotating the text, would it work to have it written "top to bottom?"

Like this:

S  
O  
M  
E  

T  
E  
X  
T  

I think that would be a lot easier - you can pick a string of text apart and insert a line break after each character.

This could be done via JavaScript in the browser like this:

"SOME TEXT".split("").join("\n")

... or you could do it server-side, so it wouldn't depend on the client's JS capabilities. (I assume that's what you mean by "portable?")

Also the user doesn't have to turn his/her head sideways to read it. :)

Update

This thread is about doing this with jQuery.

Parse large JSON file in Nodejs

I had similar requirement, i need to read a large json file in node js and process data in chunks and call a api and save in mongodb. inputFile.json is like:

{
 "customers":[
       { /*customer data*/},
       { /*customer data*/},
       { /*customer data*/}....
      ]
}

Now i used JsonStream and EventStream to achieve this synchronously.

var JSONStream = require("JSONStream");
var es = require("event-stream");

fileStream = fs.createReadStream(filePath, { encoding: "utf8" });
fileStream.pipe(JSONStream.parse("customers.*")).pipe(
  es.through(function(data) {
    console.log("printing one customer object read from file ::");
    console.log(data);
    this.pause();
    processOneCustomer(data, this);
    return data;
  }),
  function end() {
    console.log("stream reading ended");
    this.emit("end");
  }
);

function processOneCustomer(data, es) {
  DataModel.save(function(err, dataModel) {
    es.resume();
  });
}

MySQL Select Query - Get only first 10 characters of a value

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

In Netbeans, it may be helpful to design a max heap size. Go to Run => Set Project Configuration => Customise. In the Run of its popped up window, go to VM Option, fill in -Xms2048m -Xmx2048m. It could solve heap size problem.

Different font size of strings in the same TextView

You can get this done using html string and setting the html to Textview using
txtView.setText(Html.fromHtml("Your html string here"));

For example :

txtView.setText(Html.fromHtml("<html><body><font size=5 color=red>Hello </font> World </body><html>"));`

Warning: X may be used uninitialized in this function

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

Php multiple delimiters in explode

How about using strtr() to substitute all of your other delimiters with the first one?

private function multiExplode($delimiters,$string) {
    return explode(
        $delimiters[0],
        strtr(
            $string,
            array_combine(
                array_slice(    $delimiters, 1  ),
                array_fill(
                    0,
                    count($delimiters)-1,
                    array_shift($delimiters)
                )
            )
        )
    );
}

It's sort of unreadable, I guess, but I tested it as working over here.

One-liners ftw!

Error in Swift class: Property not initialized at super.init call

The "super.init()" should be called after you initialize all your instance variables.

In Apple's "Intermediate Swift" video (you can find it in Apple Developer video resource page https://developer.apple.com/videos/wwdc/2014/), at about 28:40, it is explicit said that all initializers in super class must be called AFTER you initialize your instance variables.

In Objective-C, it was the reverse. In Swift, since all properties need to be initialized before it's used, we need to initialize properties first. This is meant to prevent a call to overrided function from super class's "init()" method, without initializing properties first.

So the implementation of "Square" should be:

class Square: Shape {
    var sideLength: Double

    init(sideLength:Double, name:String) {
        self.sideLength = sideLength
        numberOfSides = 4
        super.init(name:name) // Correct position for "super.init()"
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Why does an image captured using camera intent gets rotated on some devices on Android?

By combining Jason Robinson's answer with Felix's answer and filling the missing parts, here is the final complete solution for this issue that will do the following after testing it on Android Android 4.1 (Jelly Bean), Android 4.4 (KitKat) and Android 5.0 (Lollipop).

Steps

  1. Scale down the image if it was bigger than 1024x1024.

  2. Rotate the image to the right orientation only if it was rotate 90, 180 or 270 degree.

  3. Recycle the rotated image for memory purposes.

Here is the code part:

Call the following method with the current Context and the image URI that you want to fix

/**
 * This method is responsible for solving the rotation issue if exist. Also scale the images to
 * 1024x1024 resolution
 *
 * @param context       The current context
 * @param selectedImage The Image URI
 * @return Bitmap image results
 * @throws IOException
 */
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
        throws IOException {
    int MAX_HEIGHT = 1024;
    int MAX_WIDTH = 1024;

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
    BitmapFactory.decodeStream(imageStream, null, options);
    imageStream.close();

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    imageStream = context.getContentResolver().openInputStream(selectedImage);
    Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);

    img = rotateImageIfRequired(context, img, selectedImage);
    return img;
}

Here is the CalculateInSampleSize method from the pre mentioned source:

/**
  * Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding
  * bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates
  * the closest inSampleSize that will result in the final decoded bitmap having a width and
  * height equal to or larger than the requested width and height. This implementation does not
  * ensure a power of 2 is returned for inSampleSize which can be faster when decoding but
  * results in a larger bitmap which isn't as useful for caching purposes.
  *
  * @param options   An options object with out* params already populated (run through a decode*
  *                  method with inJustDecodeBounds==true
  * @param reqWidth  The requested width of the resulting bitmap
  * @param reqHeight The requested height of the resulting bitmap
  * @return The value to be used for inSampleSize
  */
private static int calculateInSampleSize(BitmapFactory.Options options,
                                         int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee a final image
        // with both dimensions larger than or equal to the requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger inSampleSize).

        final float totalPixels = width * height;

        // Anything more than 2x the requested pixels we'll sample down further
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
    }
    return inSampleSize;
}

Then comes the method that will check the current image orientation to decide the rotation angle

 /**
 * Rotate an image if required.
 *
 * @param img           The image bitmap
 * @param selectedImage Image URI
 * @return The resulted Bitmap after manipulation
 */
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {

InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
    ei = new ExifInterface(input);
else
    ei = new ExifInterface(selectedImage.getPath());

    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            return rotateImage(img, 90);
        case ExifInterface.ORIENTATION_ROTATE_180:
            return rotateImage(img, 180);
        case ExifInterface.ORIENTATION_ROTATE_270:
            return rotateImage(img, 270);
        default:
            return img;
    }
}

Finally the rotation method itself

private static Bitmap rotateImage(Bitmap img, int degree) {
    Matrix matrix = new Matrix();
    matrix.postRotate(degree);
    Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
    img.recycle();
    return rotatedImg;
}

-Don't forget to vote up for those guys answers for their efforts and Shirish Herwade who asked this helpful question.

Add a border outside of a UIView (instead of inside)

Ok, there already is an accepted answer but I think there is a better way to do it, you just have to had a new layer a bit larger than your view and do not mask it to the bounds of the view's layer (which actually is the default behaviour). Here is the sample code :

CALayer * externalBorder = [CALayer layer];
externalBorder.frame = CGRectMake(-1, -1, myView.frame.size.width+2, myView.frame.size.height+2);
externalBorder.borderColor = [UIColor blackColor].CGColor;
externalBorder.borderWidth = 1.0;

[myView.layer addSublayer:externalBorder];
myView.layer.masksToBounds = NO;

Of course this is if you want your border to be 1 unity large, if you want more you adapt the borderWidth and the frame of the layer accordingly. This is better than using a second view a bit larger as a CALayer is lighter than a UIView and you don't have do modify the frame of myView, which is good for instance if myView is aUIImageView

N.B : For me the result was not perfect on simulator (the layer was not exactly at the right position so the layer was thicker on one side sometimes) but was exactly what is asked for on real device.

EDIT

Actually the problem I talk about in the N.B was just because I had reduced the screen of the simulator, on normal size there is absolutely no issue

Hope it helps

Fastest JavaScript summation

The fastest loop, according to this test is a while loop in reverse

var i = arr.length; while (i--) { }

So, this code might be the fastest you can get

Array.prototype.sum = function () {
    var total = 0;
    var i = this.length; 

    while (i--) {
        total += this[i];
    }

    return total;
}

Array.prototype.sum adds a sum method to the array class... you could easily make it a helper function instead.

CSS way to horizontally align table

style="text-align:center;" 

(i think)

or you could just ignore it, it still works

Calculate execution time of a SQL query?

try this

DECLARE @StartTime DATETIME
SET @StartTime = GETDATE()

  SET @EndTime = GETDATE()
  PRINT 'StartTime = ' + CONVERT(VARCHAR(30),@StartTime,121)
  PRINT '  EndTime = ' + CONVERT(VARCHAR(30),@EndTime,121)
  PRINT ' Duration = ' + CONVERT(VARCHAR(30),@EndTime -@starttime,114)

If that doesn't do it, then try SET STATISTICS TIME ON

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

Return Result from Select Query in stored procedure to a List

Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:

private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "it.hurts.when.IP";
            builder.UserID = "someDBUser";
            builder.Password = "someDBPassword";
            builder.InitialCatalog = "someDB";
            return new SqlConnection(builder.ConnectionString);
        }

        public static List<T> ExecuteSP<T>(string SPName, List<SqlParameter> Params)
        {
            try
            {
                DataTable dataTable = new DataTable();

                using (SqlConnection Connection = getConnectionString())
                {
                    // Open connection
                    Connection.Open();

                    // Create command from params / SP
                    SqlCommand cmd = new SqlCommand(SPName, Connection);

                    // Add parameters
                    cmd.Parameters.AddRange(Params.ToArray());
                    cmd.CommandType = CommandType.StoredProcedure;

                    // Make datatable for conversion
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dataTable);
                    da.Dispose();

                    // Close connection
                    Connection.Close();
                }

                // Convert to list of T
                var retVal = ConvertToList<T>(dataTable);
                return retVal;
            }
            catch (SqlException e)
            {
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

        /// <summary>
        /// Converts datatable to List<someType> if possible.
        /// </summary>
        public static List<T> ConvertToList<T>(DataTable dt)
        {
            try // Necesarry unfotunately.
            {
                var columnNames = dt.Columns.Cast<DataColumn>()
                    .Select(c => c.ColumnName)
                    .ToList();

                var properties = typeof(T).GetProperties();

                return dt.AsEnumerable().Select(row =>
                    {
                        var objT = Activator.CreateInstance<T>();

                        foreach (var pro in properties)
                        {
                            if (columnNames.Contains(pro.Name))
                            {
                                if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
                                else pro.SetValue(objT, row[pro.Name], null);
                            }
                        }

                        return objT;
                    }).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

Visual Studio 2010 always thinks project is out of date, but nothing has changed

For me, the problem arose in a WPF project where some files had their 'Build Action' property set to 'Resource' and their 'Copy to Output Directory' set to 'Copy if newer'. The solution seemed to be to change the 'Copy to Output Directory' property to 'Do not copy'.

msbuild knows not to copy 'Resource' files to the output - but still triggers a build if they're not there. Maybe that could be considered a bug?

It's hugely helpful with the answers here hinting how to get msbuild to spill the beans on why it keeps building everything!

JavaScript OR (||) variable assignment explanation

Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.

The following values are considered falsy in JavaScript.

  • false
  • null
  • "" (empty string)
  • 0
  • Nan
  • undefined

Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.

false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"

The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:

1 && [] && {} && true && "World" && null && 2010 // null

The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.

The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.

var a = false;
var b = a || "Hello";

You could call the below example an exploitation of this feature, and I believe it makes code harder to read.

var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);

Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

This message means the 'emulator-x86' or 'emulator64-x86' program is missing from $SDK/tools/, or cannot be found for some reason.

First of all, are you sure you have a valid download / install of the SDK?

Getting Index of an item in an arraylist;

I think a for-loop should be a valid solution :

    public int getIndexByname(String pName)
    {
        for(AuctionItem _item : *yourArray*)
        {
            if(_item.getName().equals(pName))
                return *yourarray*.indexOf(_item)
        }
        return -1;
    }

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

jQuery show/hide not working

Demo

_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
  $( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
    margin-left:auto;_x000D_
    margin-right:auto;_x000D_
    width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
    height:20px;_x000D_
    background-color:#CCC;_x000D_
    display:block;_x000D_
    border:#333 solid 1px;_x000D_
    margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
 float:right;_x000D_
 height: 100%;_x000D_
 padding-right:5px;_x000D_
 cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
    width: 100%;_x000D_
    height:100px;   _x000D_
    background-color:#0F3;_x000D_
    margin-top: -2px;_x000D_
    display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://api.jquery.com/toggle/
"Display or hide the matched elements."

This is much shorter in code than using show() and hide() methods.

What are some resources for getting started in operating system development?

Check out the Managed Operating System Alliance (MOSA) Project at www.mosa-project.org. They are designing an AOT/JIT compiler and fully managed operating system in C#. Some of the developers are from the inactive SharpOS project.

Hash Table/Associative Array in VBA

I think you are looking for the Dictionary object, found in the Microsoft Scripting Runtime library. (Add a reference to your project from the Tools...References menu in the VBE.)

It pretty much works with any simple value that can fit in a variant (Keys can't be arrays, and trying to make them objects doesn't make much sense. See comment from @Nile below.):

Dim d As dictionary
Set d = New dictionary

d("x") = 42
d(42) = "forty-two"
d(CVErr(xlErrValue)) = "Excel #VALUE!"
Set d(101) = New Collection

You can also use the VBA Collection object if your needs are simpler and you just want string keys.

I don't know if either actually hashes on anything, so you might want to dig further if you need hashtable-like performance. (EDIT: Scripting.Dictionary does use a hash table internally.)

How to use bootstrap-theme.css with bootstrap 3?

For an example of the css styles have a look at: http://getbootstrap.com/examples/theme/

If you want to see how the example looks without the bootstrap-theme.css file open up your browser developer tools and delete the link from the <head> of the example and then you can compare it.

I know this is an old question but posted it just in case anyone is looking for an example of how it looks like I was.

Update

bootstrap.css = main css framework (grids, basic styles, etc)

bootstrap-theme.css = extended styling (3D buttons, gradients etc). This file is optional and does not effect the functionality of bootstrap at all, it only enhances the appearance.

Update 2

With the release of v3.2.0 Bootstrap have added an option to view the theme css on the doc pages. If you go to one of the doc pages (css, components, javascript) you should see a "Preview theme" link at the bottom of the side nav which you can use to turn the theme css on and off.

How to generate random positive and negative numbers in Java

([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

example:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));

How to add an element to Array and shift indexes?

Try this

public static int [] insertArry (int inputArray[], int index, int value){
    for(int i=0; i< inputArray.length-1; i++) {

        if (i == index){

            for (int j = inputArray.length-1; j >= index; j-- ){
                inputArray[j]= inputArray[j-1];
            }

            inputArray[index]=value;
        }

    }
    return inputArray;
}

How to generate xsd from wsdl

(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :

Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.

This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).

How to find Port number of IP address?

If it is a normal then the port number is always 80 and may be written as http://www.somewhere.com:80 Though you don't need to specify it as :80 is the default of every web browser.

If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin.

If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in https://something.somewhere.com:nn Then your isp or their antivirus will probably notice and disconnect you.

How do I mock a class without an interface?

The standard mocking frameworks are creating proxy classes. This is the reason why they are technically limited to interfaces and virtual methods.

If you want to mock 'normal' methods as well, you need a tool that works with instrumentation instead of proxy generation. E.g. MS Moles and Typemock can do that. But the former has a horrible 'API', and the latter is commercial.

how to add value to a tuple?

I was going through some details related to tuple and list, and what I understood is:

  • Tuples are Heterogeneous collection data type
  • Tuple has Fixed length (per tuple type)
  • Tuple are Always finite

So for appending new item to a tuple, need to cast it to list, and do append() operation on it, then again cast it back to tuple.

But personally what I felt about the Question is, if Tuples are supposed to be finite, fixed length items and if we are using those data types in our application logics then there should not be a scenario to appending new items OR updating an item value in it. So instead of list of tuples it should be list of list itself, Am I right on this?

How to pass parameters to $http in angularjs?

We can use input data to pass it as a parameter in the HTML file w use ng-model to bind the value of input field.

<input type="text" placeholder="Enter your Email" ng-model="email" required>

<input type="text" placeholder="Enter your password " ng-model="password" required> 

and in the js file w use $scope to access this data:

$scope.email="";
$scope.password="";

Controller function will be something like that:

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

    app.controller('assignController', function($scope, $http) {
      $scope.email="";
      $scope.password="";

      $http({
        method: "POST",
        url: "http://localhost:3000/users/sign_in",
        params: {email: $scope.email, password: $scope.password}

      }).then(function mySuccess(response) {
          // a string, or an object, carrying the response from the server.
          $scope.myRes = response.data;
          $scope.statuscode = response.status;

        }, function myError(response) {
          $scope.myRes = response.statusText;
      });
    });

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

This may not only happen due to windows containers!

Today all Node.Js docker images are not pullable. Always check the image you are trying to pull before.

Related Github-Issue

String comparison using '==' vs. 'strcmp()'

PHP Instead of using alphabetical sorting, use the ASCII value of the character to make the comparison. Lowercase letters have a higher ASCII value than capitals. It's better to use the identity operator === to make this sort of comparison. strcmp() is a function to perform binary safe string comparisons. It takes two strings as arguments and returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. There is also a case-insensitive version named strcasecmp() that first converts strings to lowercase and then compares them.

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

Get the name of a pandas DataFrame

Sometimes df.name doesn't work.

you might get an error message:

'DataFrame' object has no attribute 'name'

try the below function:

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

Retrieving Property name from lambda expression

Starting with .NET 4.0 you can use ExpressionVisitor to find properties:

class ExprVisitor : ExpressionVisitor {
    public bool IsFound { get; private set; }
    public string MemberName { get; private set; }
    public Type MemberType { get; private set; }
    protected override Expression VisitMember(MemberExpression node) {
        if (!IsFound && node.Member.MemberType == MemberTypes.Property) {
            IsFound = true;
            MemberName = node.Member.Name;
            MemberType = node.Type;
        }
        return base.VisitMember(node);
    }
}

Here is how you use this visitor:

var visitor = new ExprVisitor();
visitor.Visit(expr);
if (visitor.IsFound) {
    Console.WriteLine("First property in the expression tree: Name={0}, Type={1}", visitor.MemberName, visitor.MemberType.FullName);
} else {
    Console.WriteLine("No properties found.");
}

NumPy array is not JSON serializable

I found the best solution if you have nested numpy arrays in a dictionary:

import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
    """ Special json encoder for numpy types """
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

dumped = json.dumps(data, cls=NumpyEncoder)

with open(path, 'w') as f:
    json.dump(dumped, f)

Thanks to this guy.

PostgreSQL error 'Could not connect to server: No such file or directory'

It's very simple. Only add host in your database.yaml file.

Gradle build without tests

You will have to add -x test

e.g. ./gradlew build -x test

or

gradle build -x test

Counter increment in Bash loop not working

Instead of using a temporary file, you can avoid creating a subshell around the while loop by using process substitution.

while ...
do
   ...
done < <(grep ...)

By the way, you should be able to transform all that grep, grep, awk, awk, awk into a single awk.

Starting with Bash 4.2, there is a lastpipe option that

runs the last command of a pipeline in the current shell context. The lastpipe option has no effect if job control is enabled.

bash -c 'echo foo | while read -r s; do c=3; done; echo "$c"'

bash -c 'shopt -s lastpipe; echo foo | while read -r s; do c=3; done; echo "$c"'
3

Why is "forEach not a function" for this object?

When I tried to access the result from

Object.keys(a).forEach(function (key){ console.log(a[key]); });

it was plain text result with no key-value pairs Here is an example

var fruits = {
    apple: "fruits/apple.png",
    banana: "fruits/banana.png",
    watermelon: "watermelon.jpg",
    grapes: "grapes.png",
    orange: "orange.jpg"
}

Now i want to get all links in a separated array , but with this code

    function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
    console.log('\"'+obJect[x]+'\"');
});
}

the result of :

linksOfPics(fruits)



"fruits/apple.png"
 "fruits/banana.png"
 "watermelon.jpg"
 "grapes.png"
 "orange.jpg"
undefined

I figured out this one which solves what I'm looking for

  console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]

How do I append text to a file?

Other possible way is:

echo "text" | tee -a filename >/dev/null

The -a will append at the end of the file.

If needing sudo, use:

echo "text" | sudo tee -a filename >/dev/null

How do I write good/correct package __init__.py files

My own __init__.py files are empty more often than not. In particular, I never have a from blah import * as part of __init__.py -- if "importing the package" means getting all sort of classes, functions etc defined directly as part of the package, then I would lexically copy the contents of blah.py into the package's __init__.py instead and remove blah.py (the multiplication of source files does no good here).

If you do insist on supporting the import * idioms (eek), then using __all__ (with as miniscule a list of names as you can bring yourself to have in it) may help for damage control. In general, namespaces and explicit imports are good things, and I strong suggest reconsidering any approach based on systematically bypassing either or both concepts!-)

How to sort by dates excel?

The hashes are just because your column width is not enough to display the "number".

About the sorting, you should review how you system region and language is configured. For the US region, Excel date input should be "5/17/2012" not "17/05/2012" (this 17-may-12).

Regards

Using external images for CSS custom cursors

I would put this as a comment, but I don't have the rep for it. What Josh Crozier answered is correct, but for IE .cur and .ani are the only supported formats for this. So you should probably have a fallback just in case:

.test {
    cursor:url("http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif"), url(foo.cur), auto;
}

GCM with PHP (Google Cloud Messaging)

Also you can try this piece of code, source:

<?php
    define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVscA");
    define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");

    function send_gcm_notify($reg_id, $message) {
        $fields = array(
            'registration_ids'  => array( $reg_id ),
            'data'              => array( "message" => $message ),
        );

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Problem occurred: ' . curl_error($ch));
        }

        curl_close($ch);
        echo $result;
    }

    $reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg";
    $msg = "Google Cloud Messaging working well";

    send_gcm_notify($reg_id, $msg);

How to reliably open a file in the same directory as a Python script

Ok here is what I do

sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe

For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.

    C:\Documents and Settings\Admin>python test.py
    sys.argv[0]: test.py
    C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py"
    sys.argv[0]: C:\Documents and Settings\Admin\test.py

Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname

    import sys, os
    print os.path.dirname(os.path.abspath(sys.argv[0]))

That will output this:

   C:\Documents and Settings\Admin\

it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"

The problem with using __file__ Consider these two files test.py

import sys
import os

def paths():
        print "__file__: %s" % __file__
        print "sys.argv: %s" % sys.argv[0]

        a_f = os.path.abspath(__file__)
        a_s = os.path.abspath(sys.argv[0])

        print "abs __file__: %s" % a_f
        print "abs sys.argv: %s" % a_s

if __name__ == "__main__":
    paths()

import_test.py

import test
import sys

test.paths()

print "--------"
print __file__
print sys.argv[0]

Output of "python test.py"

C:\Documents and Settings\Admin>python test.py
__file__: test.py
sys.argv: test.py
abs __file__: C:\Documents and Settings\Admin\test.py
abs sys.argv: C:\Documents and Settings\Admin\test.py

Output of "python test_import.py"

C:\Documents and Settings\Admin>python test_import.py
__file__: C:\Documents and Settings\Admin\test.pyc
sys.argv: test_import.py
abs __file__: C:\Documents and Settings\Admin\test.pyc
abs sys.argv: C:\Documents and Settings\Admin\test_import.py
--------
test_import.py
test_import.py

So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.

symfony2 : failed to write cache directory

I move the whole directory from my Windows installation to a unix production server and I got the same error. To fix it, I just ran these two lines in unix and everything started to run fine

rm -rf app/cache/*
rm -rf app/logs/*

<hr> tag in Twitter Bootstrap not functioning correctly?

By default, the hr element in Twitter Bootstrap CSS file has a top and bottom margin of 18px. That's what creates a gap. If you want the gap to be smaller you'll need to adjust margin property of the hr element.

In your example, do something like this:

.container hr {
margin: 2px 0;
}

onclick event function in JavaScript

Try this

<input type="button" onClick="return click();">button text</input>