Programs & Examples On #Ccombobox

Image resolution for new iPhone 6 and 6+, @3x support added?

UPDATE:

New link for the icons image size by apple.

https://developer.apple.com/ios/human-interface-guidelines/graphics/image-size-and-resolution/

enter image description here


Yes it's True here it is Apple provide Official documentation regarding icon's or image size

enter image description here

you have to set images for iPhone6 and iPhone6+

For iPhone 6:

750 x 1334 (@2x) for portrait

1334 x 750 (@2x) for landscape

For iPhone 6 Plus:

1242 x 2208 (@3x) for portrait

2208 x 1242 (@3x) for landscape

For more info regarding Images and it's resolution this is best ever helpful post

For setting images size for controls you can set 1x @2x and @3x like following:

enter image description here

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

Extracting date from a string in Python

Using python-dateutil:

In [1]: import dateutil.parser as dparser

In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)

Invalid dates raise a ValueError:

In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month

It can recognize dates in many formats:

In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)

Note that it makes a guess if the date is ambiguous:

In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)

But the way it parses ambiguous dates is customizable:

In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)

Configuring diff tool with .gitconfig

Others have done a 99% answer on this, but there is one step left out. (My answer will be coming from OS X so you will have to change file paths accordingly.)

You make these changes to your ~/.gitconfig:

[diff]
    tool = diffmerge
[difftool "diffmerge"]
    cmd = /Applications/Diffmerge.app/Contents/MacOS/diffmerge $LOCAL $REMOTE

This will fix the diff tool. You can also fix this without editing the ~/.gitconfig directly by entering these commands from the terminal:

git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd "/Applications/DiffMerge.appContents/MacOS/diffmerge \$LOCAL \$REMOTE"

The 1% that everyone else failed to mention is when using this you can't just run git diff myfile.txt; you need to run git difftool myfile.txt.

Running a cron every 30 seconds

You have */30 in the minutes specifier - that means every minute but with a step of 30 (in other words, every half hour). Since cron does not go down to sub-minute resolutions, you will need to find another way.

One possibility, though it's a bit of a kludge(a), is to have two jobs, one offset by 30 seconds:

# Need these to run on 30-sec boundaries, keep commands in sync.
* * * * *              /path/to/executable param1 param2
* * * * * ( sleep 30 ; /path/to/executable param1 param2 )

You'll see I've added comments and formatted to ensure it's easy to keep them synchronised.

Both cron jobs actually run every minute but the latter one will wait half a minute before executing the "meat" of the job, /path/to/executable.

For other (non-cron-based) options, see the other answers here, particularly the ones mentioning fcron and systemd. These are probably preferable assuming your system has the ability to use them (such as installing fcron or having a distro with systemd in it).


If you don't want to use the kludgy solution, you can use a loop-based solution with a small modification. You'll still have to manage keeping your process running in some form but, once that's sorted, the following script should work:

#!/bin/env bash

# Debug code to start on minute boundary and to
# gradually increase maximum payload duration to
# see what happens when the payload exceeds 30 seconds.

((maxtime = 20))
while [[ "$(date +%S)" != "00" ]]; do true; done

while true; do
    # Start a background timer BEFORE the payload runs.

    sleep 30 &

    # Execute the payload, some random duration up to the limit.
    # Extra blank line if excess payload.

    ((delay = RANDOM % maxtime + 1))
    ((maxtime += 1))
    echo "$(date) Sleeping for ${delay} seconds (max ${maxtime})."
    [[ ${delay} -gt 30 ]] && echo
    sleep ${delay}

    # Wait for timer to finish before next cycle.

    wait
done

The trick is to use a sleep 30 but to start it in the background before your payload runs. Then, after the payload is finished, just wait for the background sleep to finish.

If the payload takes n seconds (where n <= 30), the wait after the payload will then be 30 - n seconds. If it takes more than 30 seconds, then the next cycle will be delayed until the payload is finished, but no longer.

You'll see that I have debug code in there to start on a one-minute boundary to make the output initially easier to follow. I also gradually increase the maximum payload time so you'll eventually see the payload exceed the 30-second cycle time (an extra blank line is output so the effect is obvious).

A sample run follows (where cycles normally start 30 seconds after the previous cycle):

Tue May 26 20:56:00 AWST 2020 Sleeping for 9 seconds (max 21).
Tue May 26 20:56:30 AWST 2020 Sleeping for 19 seconds (max 22).
Tue May 26 20:57:00 AWST 2020 Sleeping for 9 seconds (max 23).
Tue May 26 20:57:30 AWST 2020 Sleeping for 7 seconds (max 24).
Tue May 26 20:58:00 AWST 2020 Sleeping for 2 seconds (max 25).
Tue May 26 20:58:30 AWST 2020 Sleeping for 8 seconds (max 26).
Tue May 26 20:59:00 AWST 2020 Sleeping for 20 seconds (max 27).
Tue May 26 20:59:30 AWST 2020 Sleeping for 25 seconds (max 28).
Tue May 26 21:00:00 AWST 2020 Sleeping for 5 seconds (max 29).
Tue May 26 21:00:30 AWST 2020 Sleeping for 6 seconds (max 30).
Tue May 26 21:01:00 AWST 2020 Sleeping for 27 seconds (max 31).
Tue May 26 21:01:30 AWST 2020 Sleeping for 25 seconds (max 32).
Tue May 26 21:02:00 AWST 2020 Sleeping for 15 seconds (max 33).
Tue May 26 21:02:30 AWST 2020 Sleeping for 10 seconds (max 34).
Tue May 26 21:03:00 AWST 2020 Sleeping for 5 seconds (max 35).
Tue May 26 21:03:30 AWST 2020 Sleeping for 35 seconds (max 36).

Tue May 26 21:04:05 AWST 2020 Sleeping for 2 seconds (max 37).
Tue May 26 21:04:35 AWST 2020 Sleeping for 20 seconds (max 38).
Tue May 26 21:05:05 AWST 2020 Sleeping for 22 seconds (max 39).
Tue May 26 21:05:35 AWST 2020 Sleeping for 18 seconds (max 40).
Tue May 26 21:06:05 AWST 2020 Sleeping for 33 seconds (max 41).

Tue May 26 21:06:38 AWST 2020 Sleeping for 31 seconds (max 42).

Tue May 26 21:07:09 AWST 2020 Sleeping for 6 seconds (max 43).

If you want to avoid the kludgy solution, this is probably better. You'll still need a cron job (or equivalent) to periodically detect if this script is running and, if not, start it. But the script itself then handles the timing.


(a) Some of my workmates would say that kludges are my specialty :-)

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

I don't think that IDE is relevant here. After all you're running a Maven and Maven doesn't have a source that will allow to compile the diamond operators. So, I think you should configure maven-compiler-plugin itself.

You can read about this here. But in general try to add the following properties:

<properties>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
</properties>

and see whether it compiles now in Maven only.

Load different application.yml in SpringBoot Test

Lu55 Option 1 how to...

Add test only application.yml inside a seperated resources folder.

+-- main
¦   +-- java
¦   +-- resources
¦       +-- application.yml
+-- test
    +-- java
    +-- resources
        +-- application.yml

In this project structure the application.yml under main is loaded if the code under main is running, the application.yml under test is used in a test.

To setup this structure add a new Package folder test/recources if not present.

Eclipse right click on your project -> Properties -> Java Build Path -> Source Tab -> (Dialog ont the rigth side) "Add Folder ..."

Inside Source Folder Selection -> mark test -> click on "Create New Folder ..." button -> type "resources" inside the Textfeld -> Click the "Finish" button.

After pushing the "Finisch" button you can see the sourcefolder {projectname}/src/test/recources (new)

Optional: Arrange folder sequence for the Project Explorer view. Klick on Order and Export Tab mark and move {projectname}/src/test/recources to bottom. Apply and Close

!!! Clean up Project !!!
Eclipse -> Project -> Clean ...

Now there is a separated yaml for test and the main application.

How to get a list of user accounts using the command line in MySQL?

I use this to sort the users, so the permitted hosts are more easy to spot:

mysql> SELECT User,Host FROM mysql.user ORDER BY User,Host;

Text file with 0D 0D 0A line breaks

This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...

In other words, it is just broken...

Why is 1/1/1970 the "epoch time"?

Epoch reference date

An epoch reference date is a point on the timeline from which we count time. Moments before that point are counted with a negative number, moments after are counted with a positive number.

Many epochs in use

Why is 1 January 1970 00:00:00 considered the epoch time?

No, not the epoch, an epoch. There are many epochs in use.

This choice of epoch is arbitrary.

Major computers systems and libraries use any of at least a couple dozen various epochs. One of the most popular epochs is commonly known as Unix Time, using the 1970 UTC moment you mentioned.

While popular, Unix Time’s 1970 may not be the most common. Also in the running for most common would be January 0, 1900 for countless Microsoft Excel & Lotus 1-2-3 spreadsheets, or January 1, 2001 used by Apple’s Cocoa framework in over a billion iOS/macOS machines worldwide in countless apps. Or perhaps January 6, 1980 used by GPS devices?

Many granularities

Different systems use different granularity in counting time.

Even the so-called “Unix Time” varies, with some systems counting whole seconds and some counting milliseconds. Many database such as Postgres use microseconds. Some, such as the modern java.time framework in Java 8 and later, use nanoseconds. Some use still other granularities.

ISO 8601

Because there is so much variance in the use of an epoch reference and in the granularities, it is generally best to avoid communicating moments as a count-from-epoch. Between the ambiguity of epoch & granularity, plus the inability of humans to perceive meaningful values (and therefore miss buggy values), use plain text instead of numbers.

The ISO 8601 standard provides an extensive set of practical well-designed formats for expressing date-time values as text. These formats are easy to parse by machine as well as easy to read by humans across cultures.

These include:

Get current language in CultureInfo

I think something like this would give you the current CultureInfo:

CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;

Is that what you're looking for?

github: server certificate verification failed

Try to connect to repositroy with url: http://github.com/<user>/<project>.git (http except https)

In your case you should clone like this:

git clone http://github.com/<user>/<project>.git

(Deep) copying an array using jQuery

I realize you're looking for a "deep" copy of an array, but if you just have a single level array you can use this:

Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.

var foo = ['a','b','c','d','e'];
var bar = foo.slice();

now foo and bar are 5 member arrays of 'a','b','c','d','e'

of course bar is a copy, not a reference... so if you did this next...

bar.push('f');
alert('foo:' + foo.join(', '));
alert('bar:' + bar.join(', '));

you would now get:

foo:a, b, c, d, e
bar:a, b, c, d, e, f

How do we change the URL of a working GitLab install?

There are detailed notes on this that helped me completely, located here.

Jonathon Reinhart has already answered with the key bit, to edit /etc/gitlab/gitlab.rb, alter the external_url and then run sudo gitlab-ctl reconfigure; sudo gitlab-ctl restart

However I needed to go a bit further and docs I linked above explained it. So what I ended up with looks like:

external_url 'https://gitlab.toilethumor.com'
nginx['ssl_certificate'] = "/www/ssl/star_toilethumor.com-chained.crt"
nginx['ssl_certificate_key'] = "/www/ssl/star_toilethumor.com.key"
nginx['proxy_set_headers'] = {
 "X-Forwarded-Proto" => "http",
 "CUSTOM_HEADER" => "VALUE"
}

Above, I've explicitly declared where my SSL goodies are on this server. And that's of course followed by

sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart

Also, when you switch the omnibus package to https, the bundled nginx will only serve on port 443. Since all my stuff is reached via reverse proxy, this part was potentially significant.

As I went through this, I screwed something up and it helpful to find the actual nginx logs, this lead me there:

sudo gitlab-ctl tail nginx

CSS background-image not working

@TheBigO, that's not correct. Spans can have background/images (tested in IE8 and Chrome as a sanity check).

The issue is that the a.btn-pToolName is marked as display: block. This causes webkit browsers to no longer show the background in the outer span. IE seems to render it how the OP is wanting.

OP chance the .btn-pTool class to be display: inline-block to make it work like a span/div hybrid (take the background, but not cause a break in the layout).

How to build and use Google TensorFlow C++ api

To get started, you should download the source code from Github, by following the instructions here (you'll need Bazel and a recent version of GCC).

The C++ API (and the backend of the system) is in tensorflow/core. Right now, only the C++ Session interface, and the C API are being supported. You can use either of these to execute TensorFlow graphs that have been built using the Python API and serialized to a GraphDef protocol buffer. There is also an experimental feature for building graphs in C++, but this is currently not quite as full-featured as the Python API (e.g. no support for auto-differentiation at present). You can see an example program that builds a small graph in C++ here.

The second part of the C++ API is the API for adding a new OpKernel, which is the class containing implementations of numerical kernels for CPU and GPU. There are numerous examples of how to build these in tensorflow/core/kernels, as well as a tutorial for adding a new op in C++.

Add another class to a div

Use Element.classList

document.getElementById('hello').classList.add('someClass');

The .add method will only add the class if it doesn't already exist on the element. So no need to worry about duplicate class names.

Can a CSS class inherit one or more other classes?

Unfortunately, CSS does not provide 'inheritance' in the way that programming languages like C++, C# or Java do. You can't declare a CSS class an then extend it with another CSS class.

However, you can apply more than a single class to an tag in your markup ... in which case there is a sophisticated set of rules that determine which actual styles will get applied by the browser.

<span class="styleA styleB"> ... </span>

CSS will look for all the styles that can be applied based on what your markup, and combine the CSS styles from those multiple rules together.

Typically, the styles are merged, but when conflicts arise, the later declared style will generally win (unless the !important attribute is specified on one of the styles, in which case that wins). Also, styles applied directly to an HTML element take precedence over CSS class styles.

Detect if checkbox is checked or unchecked in Angular.js ng-change event

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

html5 audio player - jquery toggle click play/pause?

Simply Use

$('audio').trigger('pause');

How do I import a .dmp file into Oracle?

imp system/system-password@SID file=directory-you-selected\FILE.dmp log=log-dir\oracle_load.log fromuser=infodba touser=infodba commit=Y

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Multiple HttpPost method in Web API controller

Put Route Prefix [RoutePrefix("api/Profiles")] at the controller level and put a route at action method [Route("LikeProfile")]. Don't need to change anything in global.asax file

namespace KhandalVipra.Controllers
{
    [RoutePrefix("api/Profiles")]
    public class ProfilesController : ApiController
    {
        // POST: api/Profiles/LikeProfile
        [Authorize]
        [HttpPost]
        [Route("LikeProfile")]
        [ResponseType(typeof(List<Like>))]
        public async Task<IHttpActionResult> LikeProfile()
        {
        }
    }
}

What is the difference between '/' and '//' when used for division?

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator

how to align all my li on one line?

I'm would recommend it:

<style>
    .clearfix {
       *zoom: 1;
    }
    .clearfix:before,
    .clearfix:after {
        content: " ";
        display: table;
    }
    .clearfix:after {
        clear: both;
    }
    ul.list {
       list-style: none;
    }
    ul.list li {
       display: inline-block;
    }
</style>

<ul class="list clearfix">
    <li>li-one</li>
    <li>li-two</li>
    <li>li-three</li>
    <li>li-four</li>
</ul>

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Rails 3 check if attribute changed

For rails 5.1+ callbacks

As of Ruby on Rails 5.1, the attribute_changed? and attribute_was ActiveRecord methods will be deprecated

Use saved_change_to_attribute? instead of attribute_changed?

@user.saved_change_to_street1? # => true/false

More examples here

Fire event on enter key press for a textbox

You could wrap the textbox and button in an ASP:Panel, and set the DefaultButton property of the Panel to the Id of your Submit button.

<asp:Panel ID="Panel1" runat="server" DefaultButton="SubmitButton">
    <asp:TextBox ID="TextBox1" runat="server" />
    <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</asp:Panel>

Now anytime the focus is within the Panel, the 'SubmitButton_Click' event will fire when enter is pressed.

Mercurial: how to amend the last commit?

Another solution could be use the uncommit command to exclude specific file from current commit.

hg uncommit [file/directory]

This is very helpful when you want to keep current commit and deselect some files from commit (especially helpful for files/directories have been deleted).

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

First, open regedit run as administrator see image open HKEY_LOCAL_MACHINE\SYSTEM\CurrentCurrentControlSet\Services\HTTP open Start, change value from 3 to 4 see image then restart your computer

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

This is what I ended up using. Temporarily sets target to _blank, then sets it back.

OnClientClick="var originalTarget = document.forms[0].target; document.forms[0].target = '_blank'; setTimeout(function () { document.forms[0].target = originalTarget; }, 3000);"

How to re-render flatlist?

Use the extraData property on your FlatList component.

As the documentation states:

By passing extraData={this.state} to FlatList we make sure FlatList will re-render itself when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.

How do I get the Back Button to work with an AngularJS ui-router state machine?

If you are looking for the simplest "back" button, then you could set up a directive like so:

    .directive('back', function factory($window) {
      return {
        restrict   : 'E',
        replace    : true,
        transclude : true,
        templateUrl: 'wherever your template is located',
        link: function (scope, element, attrs) {
          scope.navBack = function() {
            $window.history.back();
          };
        }
      };
    });

Keep in mind this is a fairly unintelligent "back" button because it is using the browser's history. If you include it on your landing page, it will send a user back to any url they came from prior to landing on yours.

Textarea onchange detection

Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.

<textarea id="text" cols="50" rows="5" onkeyup="check()" maxlength="15"></textarea> 
<div><span id="spn"></span> characters left</div>

function check(){
    var string = document.getElementById("url").value
    var left = 15 - string.length;
    document.getElementById("spn").innerHTML = left;
}

What is Hash and Range Primary Key?

A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.

In a simple words range + hash key = composite primary key CoreComponents of Dynamodb enter image description here

A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.

So both have a different purpose and together help to do complex query. In the above example hashkey1 can have multiple n-range. Another example of range and hashkey is game, userA(hashkey) can play Ngame(range)

enter image description here

The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.

A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.

enter image description here

https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html

Running code in main thread from another thread

A condensed code block is as follows:

   new Handler(Looper.getMainLooper()).post(new Runnable() {
       @Override
       public void run() {
           // things to do on the main thread
       }
   });

This does not involve passing down the Activity reference or the Application reference.

Kotlin Equivalent:

    Handler(Looper.getMainLooper()).post(Runnable {
        // things to do on the main thread
    })

How do I set the default Java installation/runtime (Windows)?

Stacked by this issue and have resolved it in 2020, in Windows 10. I'm using Java 8 RE and 14.1 JDK and it worked well until Eclipse upgrade to version 2020-09. After that I can't run Eclipse because it needed to use Java 11 or newer and it found only 8 version. It was because of order of environment variables of "Path":

environment variables setting

I suppose C:\Program Files (x86)\Common Files\Oracle\Java\javapath is path to link to installed JRE exe files (in my case Java 8) and the issue was resolved by move down this link after %JAVA_HOME%, what leads to Java 14.1/bin folder.

EV setting after edit

It seems that order of environment variables affects order of searched folders while executable file is requested. Thanks for your comment or better explanation.

How can I remove a commit on GitHub?

You need to know your commit hash from the commit you want to revert to. You can get it from a GitHub URL like: https://github.com/your-organization/your-project/commits/master

Let's say the hash from the commit (where you want to go back to) is "99fb454" (long version "99fb45413eb9ca4b3063e07b40402b136a8cf264"), then all you have to do is:

git reset --hard 99fb45413eb9ca4b3063e07b40402b136a8cf264
git push --force

ORA-01861: literal does not match format string

Remove the TO_DATE in the WHERE clause

TO_DATE (alarm_datetime,'DD.MM.YYYY HH24:MI:SS')

and change the code to

alarm_datetime

The error comes from to_date conversion of a date column.

Added Explanation: Oracle converts your alarm_datetime into a string using its nls depended date format. After this it calls to_date with your provided date mask. This throws the exception.

How can I load webpage content into a div on page load?

You can't inject content from another site (domain) using AJAX. The reason an iFrame is suited for these kinds of things is that you can specify the source to be from another domain.

stdcall and cdecl

Raymond Chen gives a nice overview of what __stdcall and __cdecl does.

(1) The caller "knows" to clean up the stack after calling a function because the compiler knows the calling convention of that function and generates the necessary code.

void __stdcall StdcallFunc() {}

void __cdecl CdeclFunc()
{
    // The compiler knows that StdcallFunc() uses the __stdcall
    // convention at this point, so it generates the proper binary
    // for stack cleanup.
    StdcallFunc();
}

It is possible to mismatch the calling convention, like this:

LRESULT MyWndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam);
// ...
// Compiler usually complains but there's this cast here...
windowClass.lpfnWndProc = reinterpret_cast<WNDPROC>(&MyWndProc);

So many code samples get this wrong it's not even funny. It's supposed to be like this:

// CALLBACK is #define'd as __stdcall
LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg
    WPARAM wParam, LPARAM lParam);
// ...
windowClass.lpfnWndProc = &MyWndProc;

However, assuming the programmer doesn't ignore compiler errors, the compiler will generate the code needed to clean up the stack properly since it'll know the calling conventions of the functions involved.

(2) Both ways should work. In fact, this happens quite frequently at least in code that interacts with the Windows API, because __cdecl is the default for C and C++ programs according to the Visual C++ compiler and the WinAPI functions use the __stdcall convention.

(3) There should be no real performance difference between the two.

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

Another Solution For Windows Users:

This uses Github as a bridge to get to Bitbucket, caused to the lack of publishing directly from the windows Sourcetree app.

  1. Load your local repo into the Github desktop app.
  2. Publish the repo as a private (for privacy - if desired) repo from the Github desktop app into your Github account.
  3. Open your personal / team account in Bitbucket's website
  4. Create a new Bitbucket repo by importing from Github.
  5. Delete the repo in Github.

Once this is done, everything will be loaded into Bitbucket. Your local remotes will probably need to be configured to point to Bitbucket now.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

i'm using xcode 6 and encounter this issue for one particular iphone 4

finally , i go to device => provision profile =>

and then add the profile manually and problem is fixed .

Number of rows affected by an UPDATE in PL/SQL

For those who want the results from a plain command, the solution could be:

begin
  DBMS_OUTPUT.PUT_LINE(TO_Char(SQL%ROWCOUNT)||' rows affected.');
end;

The basic problem is that SQL%ROWCOUNT is a PL/SQL variable (or function), and cannot be directly accessed from an SQL command. By using a noname PL/SQL block, this can be achieved.

... If anyone has a solution to use it in a SELECT Command, I would be interested.

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to implement reCaptcha for ASP.NET MVC?

I've successfully implemented ReCaptcha in the following way.
note: this is in VB, but can easily be converted

1] First grab a copy of the reCaptcha library

2] Then build a custom ReCaptcha HTML Helper

    ''# fix SO code coloring issue.
    <Extension()>
    Public Function reCaptcha(ByVal htmlHelper As HtmlHelper) As MvcHtmlString
        Dim captchaControl = New Recaptcha.RecaptchaControl With {.ID = "recaptcha",
                                                                  .Theme = "clean",
                                                                  .PublicKey = "XXXXXX",
                                                                  .PrivateKey = "XXXXXX"}
        Dim htmlWriter = New HtmlTextWriter(New IO.StringWriter)
        captchaControl.RenderControl(htmlWriter)
        Return MvcHtmlString.Create(htmlWriter.InnerWriter.ToString)
    End Function

3] From here you need a re-usable server side validator

Public Class ValidateCaptchaAttribute : Inherits ActionFilterAttribute
    Private Const CHALLENGE_FIELD_KEY As String = "recaptcha_challenge_field"
    Private Const RESPONSE_FIELD_KEY As String = "recaptcha_response_field"

    Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)

        If IsNothing(filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)) Then
            ''# this will push the result value into a parameter in our Action
            filterContext.ActionParameters("CaptchaIsValid") = True
            Return
        End If

        Dim captchaChallengeValue = filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)
        Dim captchaResponseValue = filterContext.HttpContext.Request.Form(RESPONSE_FIELD_KEY)

        Dim captchaValidtor = New RecaptchaValidator() With {.PrivateKey = "xxxxx",
                                                                       .RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
                                                                       .Challenge = captchaChallengeValue,
                                                                       .Response = captchaResponseValue}

        Dim recaptchaResponse = captchaValidtor.Validate()

        ''# this will push the result value into a parameter in our Action
        filterContext.ActionParameters("CaptchaIsValid") = recaptchaResponse.IsValid

        MyBase.OnActionExecuting(filterContext)
    End Sub

above this line is reusable **ONE TIME** code


below this line is how easy it is to implement reCaptcha over and over

Now that you have your re-usable code... all you need to do is add the captcha to your View.

<%: Html.reCaptcha %>

And when you post the form to your controller...

    ''# Fix SO code coloring issues
    <ValidateCaptcha()>
    <AcceptVerbs(HttpVerbs.Post)>
    Function Add(ByVal CaptchaIsValid As Boolean, ByVal [event] As Domain.Event) As ActionResult


        If Not CaptchaIsValid Then ModelState.AddModelError("recaptcha", "*")


        '#' Validate the ModelState and submit the data.
        If ModelState.IsValid Then
            ''# Post the form
        Else
            ''# Return View([event])
        End If
    End Function

Is there an equivalent method to C's scanf in Java?

Not an equivalent, but you can use a Scanner and a pattern to parse lines with three non-negative numbers separated by spaces, for example:

71 5796 2489
88 1136 5298
42 420 842

Here's the code using findAll:

new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
        .forEach(result -> {
            int fst = Integer.parseInt(result.group(1));
            int snd = Integer.parseInt(result.group(2));
            int third = Integer.parseInt(result.group(3));
            int sum = fst + snd + third;
            System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
        });

raw vs. html_safe vs. h to unescape html

The difference is between Rails’ html_safe() and raw(). There is an excellent post by Yehuda Katz on this, and it really boils down to this:

def raw(stringish)

  stringish.to_s.html_safe

end

Yes, raw() is a wrapper around html_safe() that forces the input to String and then calls html_safe() on it. It’s also the case that raw() is a helper in a module whereas html_safe() is a method on the String class which makes a new ActiveSupport::SafeBuffer instance — that has a @dirty flag in it.

Refer to "Rails’ html_safe vs. raw".

ConfigurationManager.AppSettings - How to modify and save?

You can change it manually:

private void UpdateConfigFile(string appConfigPath, string key, string value)
{
     var appConfigContent = File.ReadAllText(appConfigPath);
     var searchedString = $"<add key=\"{key}\" value=\"";
     var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
     var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
     var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
     File.WriteAllText(appConfigPath, newContent);
}

Could not resolve placeholder in string value

In my case, I was careless while merging the application.yml file, and I've unnecessary indented my properties to the right.

I've indented it like this:

spring:
    application:
       name: applicationName
............................
    myProperties:
       property1: property1value

While the code expected it to be like this:

spring:
    application:
        name: applicationName
.............................
myProperties:
    property1: property1value

Windows batch: sleep

Microsoft has a sleep function you can call directly.

    Usage:  sleep      time-to-sleep-in-seconds
            sleep [-m] time-to-sleep-in-milliseconds
            sleep [-c] commited-memory ratio (1%-100%)

You can just say sleep 1 for example to sleep for 1 second in your batch script.

IMO Ping is a bit of a hack for this use case.

How to get all properties values of a JavaScript Object (without knowing the keys)?

The question doesn't specify whether wanting inherited and non-enumerable properties also.

There is a question for getting everything, inherited properties and non-enumerable properties also, that Google cannot easily find.

If we are to get all inherited and non-enumerable properties, my solution for that is:

function getAllPropertyNames(obj) {
    let result = new Set();
    while (obj) {
        Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
        obj = Object.getPrototypeOf(obj);
    }
    return [...result];
}

And then iterate over them, just use a for-of loop:

_x000D_
_x000D_
function getAllPropertyNames(obj) {
  let result = new Set();
  while (obj) {
    Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
    obj = Object.getPrototypeOf(obj);
  }
  return [...result];
}

let obj = {
  abc: 123,
  xyz: 1.234,
  foobar: "hello"
};

for (p of getAllPropertyNames(obj)) console.log(p);
_x000D_
_x000D_
_x000D_

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

How do I find my host and username on mysql?

The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html

If MySql is running on the same computer as your webserver, you can just use "localhost" as the host

Python: 'break' outside loop

break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like

for item in some_iterable:
    ...
    if break_condition():
        break 

The break would be pretty useless if it terminated the if block rather than terminated the loop -- terminating a loop conditionally is the exact thing break is used for.

Java 8 stream reverse order

Elegant solution

List<Integer> list = Arrays.asList(1,2,3,4);
list.stream()
    .boxed() // Converts Intstream to Stream<Integer>
    .sorted(Collections.reverseOrder()) // Method on Stream<Integer>
    .forEach(System.out::println);

Can I set variables to undefined or pass undefined as an argument?

You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.

You cannot (should not?) pass undefined to a function. If you want to pass an empty value, use null instead.

The statement if(!testvar) checks for boolean true/false values, this particular one tests whether testvar evaluates to false. By definition, null and undefined shouldn't be evaluated neither as true or false, but JavaScript evaluates null as false, and gives an error if you try to evaluate an undefined variable.

To properly test for undefined or null, use these:

if(typeof(testvar) === "undefined") { ... }

if(testvar === null) { ... }

Delete column from pandas DataFrame

The best way to do this in pandas is to use drop:

df = df.drop('column_name', 1)

where 1 is the axis number (0 for rows and 1 for columns.)

To delete the column without having to reassign df you can do:

df.drop('column_name', axis=1, inplace=True)

Finally, to drop by column number instead of by column label, try this to delete, e.g. the 1st, 2nd and 4th columns:

df = df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index 

Also working with "text" syntax for the columns:

df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True)

Note: Introduced in v0.21.0 (October 27, 2017), the drop() method accepts index/columns keywords as an alternative to specifying the axis.

So we can now just do:

df.drop(columns=['B', 'C'])

How to find/identify large commits in git history?

I was unable to make use of the most popular answer because the --batch-check command-line switch to Git 1.8.3 (that I have to use) does not accept any arguments. The ensuing steps have been tried on CentOS 6.5 with Bash 4.1.2

Key Concepts

In Git, the term blob implies the contents of a file. Note that a commit might change the contents of a file or pathname. Thus, the same file could refer to a different blob depending on the commit. A certain file could be the biggest in the directory hierarchy in one commit, while not in another. Therefore, the question of finding large commits instead of large files, puts matters in the correct perspective.

For The Impatient

Command to print the list of blobs in descending order of size is:

git cat-file --batch-check < <(git rev-list --all --objects  | \
awk '{print $1}')  | grep blob  | sort -n -r -k 3

Sample output:

3a51a45e12d4aedcad53d3a0d4cf42079c62958e blob 305971200
7c357f2c2a7b33f939f9b7125b155adbd7890be2 blob 289163620

To remove such blobs, use the BFG Repo Cleaner, as mentioned in other answers. Given a file blobs.txt that just contains the blob hashes, for example:

3a51a45e12d4aedcad53d3a0d4cf42079c62958e
7c357f2c2a7b33f939f9b7125b155adbd7890be2

Do:

java -jar bfg.jar -bi blobs.txt <repo_dir>

The question is about finding the commits, which is more work than finding blobs. To know, please read on.

Further Work

Given a commit hash, a command that prints hashes of all objects associated with it, including blobs, is:

git ls-tree -r --full-tree <commit_hash>

So, if we have such outputs available for all commits in the repo, then given a blob hash, the bunch of commits are the ones that match any of the outputs. This idea is encoded in the following script:

#!/bin/bash
DB_DIR='trees-db'

find_commit() {
    cd ${DB_DIR}
    for f in *; do
        if grep -q $1 ${f}; then
            echo ${f}
        fi
    done
    cd - > /dev/null
}

create_db() {
    local tfile='/tmp/commits.txt'
    mkdir -p ${DB_DIR} && cd ${DB_DIR}
    git rev-list --all > ${tfile}

    while read commit_hash; do
        if [[ ! -e ${commit_hash} ]]; then
            git ls-tree -r --full-tree ${commit_hash} > ${commit_hash}
        fi
    done < ${tfile}
    cd - > /dev/null
    rm -f ${tfile}
}

create_db

while read id; do
    find_commit ${id};
done

If the contents are saved in a file named find-commits.sh then a typical invocation will be as under:

cat blobs.txt | find-commits.sh

As earlier, the file blobs.txt lists blob hashes, one per line. The create_db() function saves a cache of all commit listings in a sub-directory in the current directory.

Some stats from my experiments on a system with two Intel(R) Xeon(R) CPU E5-2620 2.00GHz processors presented by the OS as 24 virtual cores:

  • Total number of commits in the repo = almost 11,000
  • File creation speed = 126 files/s. The script creates a single file per commit. This occurs only when the cache is being created for the first time.
  • Cache creation overhead = 87 s.
  • Average search speed = 522 commits/s. The cache optimization resulted in 80% reduction in running time.

Note that the script is single threaded. Therefore, only one core would be used at any one time.

Android Preventing Double Click On A Button

you can also use rx bindings by jake wharton to accomplish this. here is a sample that pads 2 seconds between successive clicks:

RxView.clicks(btnSave)
                .throttleFirst(2000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept( Object v) throws Exception {
//handle onclick event here
                });

//note: ignore the Object v in this case and i think always.

python: urllib2 how to send cookie with urlopen request

Use cookielib. The linked doc page provides examples at the end. You'll also find a tutorial here.

What is cURL in PHP?

cURL

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

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

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

Sample Code

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

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

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

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

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

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

        $output = curl_exec($ch);

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

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

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

For more information, please check -

Entity Framework Core add unique constraint code-first

On EF core you cannot create Indexes using data annotations.But you can do it using the Fluent API.

Like this inside your {Db}Context.cs:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<User>()
        .HasIndex(u => u.Email)
        .IsUnique();
}

...or if you're using the overload with the buildAction:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<User>(entity => {
        entity.HasIndex(e => e.Email).IsUnique();
    });
}

You can read more about it here : Indexes

Can we have functions inside functions in C++?

You cannot define a free function inside another in C++.

How to base64 encode image in linux bash / shell

If you need input from termial, try this

lc=`echo -n "xxx_${yyy}_iOS" |  base64`

-n option will not input "\n" character to base64 command.

Event listener for when element becomes visible?

Just to comment on the DOMAttrModified event listener browser support:

Cross-browser support

These events are not implemented consistently across different browsers, for example:

  • IE prior to version 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for example, DOMNodeInserted)

  • WebKit doesn't support DOMAttrModified (see webkit bug 8191 and the workaround)

  • "mutation name events", i.e. DOMElementNameChanged and DOMAttributeNameChanged are not supported in Firefox (as of version 11), and probably in other browsers as well.

Source: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

how to show lines in common (reverse diff)?

Just for information, i made a little tool for Windows doing the same thing than "grep -F -x -f file1 file2" (As i haven't found anything equivalent to this command on Windows)

Here it is : http://www.nerdzcore.com/?page=commonlines

Usage is "CommonLines inputFile1 inputFile2 outputFile"

Source code is also available (GPL)

Most efficient way to find smallest of 3 numbers Java?

No, it's seriously not worth changing. The sort of improvements you're going to get when fiddling with micro-optimisations like this will not be worth it. Even the method call cost will be removed if the min function is called enough.

If you have a problem with your algorithm, your best bet is to look into macro-optimisations ("big picture" stuff like algorithm selection or tuning) - you'll generally get much better performance improvements there.

And your comment that removing Math.pow gave improvements may well be correct but that's because it's a relatively expensive operation. Math.min will not even be close to that in terms of cost.

Raise error in a Bash script

This depends on where you want the error message be stored.

You can do the following:

echo "Error!" > logfile.log
exit 125

Or the following:

echo "Error!" 1>&2
exit 64

When you raise an exception you stop the program's execution.

You can also use something like exit xxx where xxx is the error code you may want to return to the operating system (from 0 to 255). Here 125 and 64 are just random codes you can exit with. When you need to indicate to the OS that the program stopped abnormally (eg. an error occurred), you need to pass a non-zero exit code to exit.

As @chepner pointed out, you can do exit 1, which will mean an unspecified error.

How do I escape ampersands in XML so they are rendered as entities in HTML?

When your XML contains &amp;amp;, this will result in the text &amp;.

When you use that in HTML, that will be rendered as &.

Django ChoiceField

If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .

Example:

views.py:

def my_view(request, interview_pk):
    interview = Interview.objects.get(pk=interview_pk)
    all_rounds = interview.round_set.order_by('created_at')
    all_round_names = [rnd.name for rnd in all_rounds]
    form = forms.AddRatingForRound(all_round_names)
    return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})

forms.py

class AddRatingForRound(forms.ModelForm):

    def __init__(self, round_list, *args, **kwargs):
        super(AddRatingForRound, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))

    class Meta:
        model = models.RatingSheet
        fields = ('name', )

template:

<form method="post">
    {% csrf_token %}
    {% if interview %}
         {{ interview }}
    {% endif %}
    {% if rounds %}
    <hr>
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    {% else %}
        <h3>No rounds found</h3>
    {% endif %}

</form>

Detecting EOF in C

as a starting point you could try replacing

while(!EOF)

with

while(!feof(stdin))

How do I display local image in markdown?

Solution for Unix-like operating system.

STEP BY STEP :
  1. Create a directory named like Images and put all the images that will be rendered by the Markdown.

  2. For example, put example.png into Images.

  3. To load example.png that was located under the Images directory before.

![title](Images/example.png)

Note : Images directory must be located under the same directory of your markdown text file which has .md extension.

extracting days from a numpy.timedelta64 value

Suppose you have a timedelta series:

import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})

td_series = (z['a'] - z['b'])

One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:

td_series.astype(pd.Timedelta).apply(lambda l: l.days)

Another way is to cast the series as a timedelta64 in days, and then cast it as an int:

td_series.astype('timedelta64[D]').astype(int)

Android studio logcat nothing to show

Restarting Android Studio helped me.

How to create unique keys for React elements?

To add the latest solution for 2021...

I found that the project nanoid provides unique string ids that can be used as key while also being fast and very small.

After installing using npm install nanoid, use as follows:

import { nanoid } from 'nanoid';

// Have the id associated with the data.
const todos = [{id: nanoid(), text: 'first todo'}];

// Then later, it can be rendered using a stable id as the key.
const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
)

How to remove blank lines from a Unix file

grep . file

grep looks at your file line-by-line; the dot . matches anything except a newline character. The output from grep is therefore all the lines that consist of something other than a single newline.

How to execute a Ruby script in Terminal?

In case someone is trying to run a script in a RAILS environment, rails provide a runner to execute scripts in rails context via

rails runner my_script.rb

More details here: https://guides.rubyonrails.org/command_line.html#rails-runner

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

Then try the following:

@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody List<PatientProfileDto> getPatientDetails(
        PatientProfileDto name) {


    List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
    list = service.getPatient(name);
    return list;
}

Note that removed the annotation @RequestBody

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

Simple extension for UIApplication in Swift (cares even about moreNavigationController within UITabBarController on iPhone):

extension UIApplication {
    class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController where top.view.window != nil {
                return topViewController(top)
            } else if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }

        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }

        return base
    }
}

Simple usage:

    if let rootViewController = UIApplication.topViewController() {
        //do sth with root view controller
    }

Works perfect:-)

UPDATE for clean code:

extension UIViewController {
    var top: UIViewController? {
        if let controller = self as? UINavigationController {
            return controller.topViewController?.top
        }
        if let controller = self as? UISplitViewController {
            return controller.viewControllers.last?.top
        }
        if let controller = self as? UITabBarController {
            return controller.selectedViewController?.top
        }
        if let controller = presentedViewController {
            return controller.top
        }
        return self
    }
}

Allow 2 decimal places in <input type="number">

You can use this. react hooks

_x000D_
_x000D_
<input
                  type="number"
                  name="price"
                  placeholder="Enter price"
                  step="any"
                  required
                />
_x000D_
_x000D_
_x000D_

exception in initializer error in java when using Netbeans

I found that I had bound jFormattedCheckBox1.foreground to jCheckBox1[${selected}].... this was the problem. Thank you for your help.

It seems that a color should not be able to be bound to a boolean. I guess bindings are an advanced feature?

I found the problem by deleting all of the controls, then running, then undoing and then deleting one at a time. When I found the offending control, I examined the properties.

Install Application programmatically on Android

This can help others a lot!

First:

private static final String APP_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyAppFolderInStorage/";

private void install() {
    File file = new File(APP_DIR + fileName);

    if (file.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri downloadedApk = FileProvider.getUriForFile(getContext(), "ir.greencode", file);
            intent.setDataAndType(downloadedApk, type);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        getContext().startActivity(intent);
    } else {
        Toast.makeText(getContext(), "?File not found!", Toast.LENGTH_SHORT).show();
    }
}

Second: For android 7 and above you should define a provider in manifest like below!

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="ir.greencode"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/paths" />
    </provider>

Third: Define path.xml in res/xml folder like below! I'm using this path for internal storage if you want to change it to something else there is a few way! You can go to this link: FileProvider

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="your_folder_name" path="MyAppFolderInStorage/"/>
</paths>

Forth: You should add this permission in manifest:

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

Allows an application to request installing packages. Apps targeting APIs greater than 25 must hold this permission in order to use Intent.ACTION_INSTALL_PACKAGE.

Please make sure the provider authorities are the same!


How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

How to get last N records with activerecord?

For Rails 4 and above version:

You can try something like this If you want first oldest entry

YourModel.order(id: :asc).limit(5).each do |d|

You can try something like this if you want last latest entries..

YourModel.order(id: :desc).limit(5).each do |d|

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

How to force IE to reload javascript?

Add a date of modification of js file at the end of your URL. With PHP it would look something like this:

echo '<script type="text/javascript" src="js/something.js?' . filemtime('js/something.js') . '"></script>';

When your script will be reloaded every time you update it.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I encountered the same problem, beat my head up and found that I had changed the directory in the represotory from "/" to "/trunk" and forgot to do the "Switch" command, in TortoiseSVN!

What is the difference between Cloud Computing and Grid Computing?

I would say that the basic difference is this:

Grids are used as computing/storage platform.

We start talking about cloud computing when it offers services. I would almost say that cloud computing is higher-level grid. Now I know these are not definitions, but maybe it will make it more clear.

As far as application domains go, grids require users (developers mostly) to actually create services from low-level functions that grid offers. Cloud will offer complete blocks of functionality that you can use in your application.

Example (you want to create physical simulation of ball dropping from certain height): Grid: Study how to compute physics on a computer, create appropriate code, optimize it for certain hardware, think about paralellization, set inputs send application to grid and wait for answer

Cloud: Set diameter of a ball, material from pre-set types, height from which the ball is dropping, etc and ask for results

I would say that if you created OS for grid, you would actually create cloud OS.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

Visual c++ can't open include file 'iostream'

Make sure you have Desktop Development with C++ installed. I was experiencing the same problem because I only had Universal Windows Platform Development installed.

copying all contents of folder to another folder using batch file?

@echo off
:: variables
echo Backing up file
set /P source=Enter source folder:
set /P destination=Enter Destination folder:
set xcopy=xcopy /S/E/V/Q/F/H/I/N
%xcopy% %source% %destination%
echo files will be copy press enter to proceed
pause

Set 4 Space Indent in Emacs in Text Mode

Customizations can shadow (setq tab width 4) so either use setq-default or let Customize know what you're doing. I also had issues similar to the OP and fixed it with this alone, did not need to adjust tab-stop-list or any insert functions:

(custom-set-variables
 '(tab-width 4 't)
 )

Found it useful to add this immediately after (a tip from emacsWiki):

(defvaralias 'c-basic-offset 'tab-width)
(defvaralias 'cperl-indent-level 'tab-width)

Get user profile picture by Id

You can use the following endpoint to get the image.jfif instead of jpg:

https://graph.facebook.com/v3.2/{user-id}/picture

Note that you won't be able to see the image, only download it.

Algorithm for Determining Tic Tac Toe Game Over

Not sure if this approach is published yet. This should work for any m*n board and a player is supposed to fill "winnerPos" consecutive position. The idea is based on running window.

private boolean validateWinner(int x, int y, int player) {
    //same col
    int low = x-winnerPos-1;
    int high = low;
    while(high <= x+winnerPos-1) {
        if(isValidPos(high, y) && isFilledPos(high, y, player)) {
            high++;
            if(high - low == winnerPos) {
                return true;
            }
        } else {
            low = high + 1;
            high = low;
        }
    }

    //same row
    low = y-winnerPos-1;
    high = low;
    while(high <= y+winnerPos-1) {
        if(isValidPos(x, high) && isFilledPos(x, high, player)) {
            high++;
            if(high - low == winnerPos) {
                return true;
            }
        } else {
            low = high + 1;
            high = low;
        }
    }
    if(high - low == winnerPos) {
        return true;
    }

    //diagonal 1
    int lowY = y-winnerPos-1;
    int highY = lowY;
    int lowX = x-winnerPos-1;
    int highX = lowX;
    while(highX <= x+winnerPos-1 && highY <= y+winnerPos-1) {
        if(isValidPos(highX, highY) && isFilledPos(highX, highY, player)) {
            highX++;
            highY++;
            if(highX - lowX == winnerPos) {
                return true;
            }
        } else {
            lowX = highX + 1;
            lowY = highY + 1;
            highX = lowX;
            highY = lowY;
        }
    }

    //diagonal 2
    lowY = y+winnerPos-1;
    highY = lowY;
    lowX = x-winnerPos+1;
    highX = lowX;
    while(highX <= x+winnerPos-1 && highY <= y+winnerPos-1) {
        if(isValidPos(highX, highY) && isFilledPos(highX, highY, player)) {
            highX++;
            highY--;
            if(highX - lowX == winnerPos) {
                return true;
            }
        } else {
            lowX = highX + 1;
            lowY = highY + 1;
            highX = lowX;
            highY = lowY;
        }
    }
    if(highX - lowX == winnerPos) {
        return true;
    }
    return false;
}

private boolean isValidPos(int x, int y) {
    return x >= 0 && x < row && y >= 0 && y< col;
}
public boolean isFilledPos(int x, int y, int p) throws IndexOutOfBoundsException {
    return arena[x][y] == p;
}

Removing Duplicate Values from ArrayList

list = list.stream().distinct().collect(Collectors.toList());
This could be one of the solutions using Java8 Stream API. Hope this helps.

Event detect when css property changed using Jquery

For properties for which css transition will affect, can use transitionend event, example for z-index:

_x000D_
_x000D_
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {_x000D_
  console.log("end", e);_x000D_
  alert("z-index changed");_x000D_
});_x000D_
_x000D_
$(".changeButton").on("click", function() {_x000D_
  console.log("click");_x000D_
  document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;_x000D_
});
_x000D_
.observed-element {_x000D_
  transition: z-index 1ms;_x000D_
  -webkit-transition: z-index 1ms;_x000D_
}_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
  position: absolute;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button class="changeButton">change z-index</button>_x000D_
<div class="observed-element"></div>
_x000D_
_x000D_
_x000D_

How to check string length with JavaScript

You should bind a function to keyup event

textarea.keyup = function(){
   textarea.value.length....
} 

with jquery

$('textarea').keyup(function(){
   var length = $(this).val().length;
});

how to stop Javascript forEach?

    var f = "how to stop Javascript forEach?".split(' ');
    f.forEach(function (a,b){
        console.info(b+1);
        if (a == 'stop') {
            console.warn("\tposition: \'stop\'["+(b+1)+"] \r\n\tall length: " + (f.length)); 
            f.length = 0; //<--!!!
        }
    });

How to support placeholder attribute in IE8 and 9

You can use any one of these polyfills:

These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!

Get latitude and longitude based on location name with Google Autocomplete API

I hope this can help someone in the future.

You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script type="text/javascript">
        function initialize() {
        var address = (document.getElementById('my-address'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
      });
}
function codeAddress() {
    geocoder = new google.maps.Geocoder();
    var address = document.getElementById("my-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

      alert("Latitude: "+results[0].geometry.location.lat());
      alert("Longitude: "+results[0].geometry.location.lng());
      } 

      else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
google.maps.event.addDomListener(window, 'load', initialize);

        </script>
    </head>
    <body>
        <input type="text" id="my-address">
        <button id="getCords" onClick="codeAddress();">getLat&Long</button>
    </body>
</html>

Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.

Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).

Hope this helps, and read the documentation for more information, cheers.

Edit #1: Fiddle

Does C have a "foreach" loop construct?

Here is a full program example of a for-each macro in C99:

#include <stdio.h>

typedef struct list_node list_node;
struct list_node {
    list_node *next;
    void *data;
};

#define FOR_EACH(item, list) \
    for (list_node *(item) = (list); (item); (item) = (item)->next)

int
main(int argc, char *argv[])
{
    list_node list[] = {
        { .next = &list[1], .data = "test 1" },
        { .next = &list[2], .data = "test 2" },
        { .next = NULL,     .data = "test 3" }
    };

    FOR_EACH(item, list)
        puts((char *) item->data);

    return 0;
}

A process crashed in windows .. Crash dump location

I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:

C:\Users\All Users\Microsoft\Windows\WER\ReportQueue

Which, starting with Windows Vista, is an alias for:

C:\ProgramData\Microsoft\Windows\WER\ReportQueue

How to remove focus from single editText

Just include this line

android:selectAllOnFocus="false"

in the XML segment corresponding to the EditText layout.

Add item to array in VBScript

Slight change to the FastArray from above:

'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """" 

t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
 If i>ub Then 
    ReDim Preserve a(Int((ub+10)*1.1))
    ub = UBound(a)
 End If
 a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"

MsgBox s

There is no point in checking UBound(a) in every cycle of the for if we know exactly when it changes.

I've changed it so that it checks does UBound(a) just before the for starts and then only every time the ReDim is called

On my computer the old method took 7.52 seconds for an imax of 10 millions.

The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)

gitbash command quick reference

Git command Quick Reference

git [command] -help

Git command Manual Pages

git help [command]
git [command] --help

Autocomplete

git <tab>

Cheat Sheets

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]

This still appears to be an issue, causing package installations to be aborted with warnings about optional packages no being installed because of "Unsupported platform".

The problem relates to the "shrinkwrap" or package-lock.json which gets persisted after every package manager execution. Subsequent attempts keep failing as this file is referenced instead of package.json.

Adding these options to the npm install command should allow packages to install again.

   --no-optional argument will prevent optional dependencies from being installed.

   --no-shrinkwrap argument, which will ignore an available package lock or
                   shrinkwrap file and use the package.json instead.

   --no-package-lock argument will prevent npm from creating a package-lock.json file.

The complete command looks like this:

    npm install --no-optional --no-shrinkwrap --no-package-lock

nJoy!

HTML SELECT - Change selected option by VALUE using JavaScript

try out this....

JSFIDDEL DEMO

using javascript

?document.getElementById('sel').value = 'car';??????????

using jQuery

$('#sel').val('car');

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

This error is usually caused by the missing Visual C++ Redistributable file, which is a required dependency for most of the application on Windows Computer.

Download Visual C++ Redistributable from here and install it. After installing this, Reboot the system.

Link: Visual C++ Redistributable

What is javax.inject.Named annotation supposed to be used for?

Regarding #2, according to the JSR-330 spec:

This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.

So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Although my emphatic advice to you is to structure your sql so as to not attempt duplicate inserts (Philip Kelley's snippet is probably what you need), I want to mention that an error on a statement doesn't necessarily cause a rollback.

Unless XACT_ABORT is ON, a transaction will not automatically rollback if an error is encountered unless it's severe enough to kill the connection. XACT_ABORT defaults to OFF.

For example, the following sql successfully inserts three values into the table:

create table x ( y int not null primary key )

begin transaction
insert into x(y)
values(1)
insert into x(y)
values(2)
insert into x(y)
values(2)
insert into x(y)
values(3)
commit

Unless you're setting XACT_ABORT, an error is being raised on the client and causing the rollback. If for some horrible reason you can't avoid inserting duplicates, you ought to be able to trap the error on the client and ignore it.

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

Why do you use typedef when declaring an enum in C++?

In C, it is good style because you can change the type to something besides an enum.

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

foo(enum e_TokenType token);  /* this can only be passed as an enum */

foo(TokenType token); /* TokenType can be defined to something else later
                         without changing this declaration */

In C++ you can define the enum so that it will compile as C++ or C.

startsWith() and endsWith() functions in PHP

Not sure why this is so difficult for people. Substr does a great job and is efficient as you don't need to search the whole string if it doesn't match.

Additionally, since I'm not checking integer values but comparing strings I don't have to necessarily have to worry about the strict === case. However, === is a good habit to get into.

function startsWith($haystack,$needle) {
  substring($haystack,0,strlen($needle)) == $needle) { return true; }
   return false;
}

function endsWith($haystack,$needle) {
  if(substring($haystack,-strlen($needle)) == $needle) { return true; }
   return false;
}

or even better optimized.

function startsWith($haystack,$needle) {
  return substring($haystack,0,strlen($needle)) == $needle);
}

function endsWith($haystack,$needle) {
  return substring($haystack,-strlen($needle)) == $needle);
}

Initializing array of structures

It's called designated initializer which is introduced in C99. It's used to initialize struct or arrays, in this example, struct.

Given

struct point { 
    int x, y;
};

the following initialization

struct point p = { .y = 2, .x = 1 };

is equivalent to the C89-style

struct point p = { 1, 2 };

Proxy with urllib2

To use the default system proxies (e.g. from the http_support environment variable), the following works for the current request (without installing it into urllib2 globally):

url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()

Running Jupyter via command line on Windows

If you have installed jupyter with "python -m pip install jupyter" command instead of "$ pip install jupyter" command then follow these steps:

  1. Create a notepad
  2. Change its extension from ".txt" to ".ipynb"
  3. Right click it and click "open with"
  4. In the pop up, go to - C:\Users\<"windows_user_name">\AppData\Roaming\Python\Python38\Scripts
  5. Click on "jupyter-lab.exe"

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

How to get highcharts dates in the x axis?

Highcharts will automatically try to find the best format for the current zoom-range. This is done if the xAxis has the type 'datetime'. Next the unit of the current zoom is calculated, it could be one of:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • year

This unit is then used find a format for the axis labels. The default patterns are:

second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'

If you want the day to be part of the "hour"-level labels you should change the dateTimeLabelFormats option for that level include %d or %e. These are the available patters:

  • %a: Short weekday, like 'Mon'.
  • %A: Long weekday, like 'Monday'.
  • %d: Two digit day of the month, 01 to 31.
  • %e: Day of the month, 1 through 31.
  • %b: Short month, like 'Jan'.
  • %B: Long month, like 'January'.
  • %m: Two digit month number, 01 through 12.
  • %y: Two digits year, like 09 for 2009.
  • %Y: Four digits year, like 2009.
  • %H: Two digits hours in 24h format, 00 through 23.
  • %I: Two digits hours in 12h format, 00 through 11.
  • %l (Lower case L): Hours in 12h format, 1 through 11.
  • %M: Two digits minutes, 00 through 59.
  • %p: Upper case AM or PM.
  • %P: Lower case AM or PM.
  • %S: Two digits seconds, 00 through 59

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

Convert list of ints to one number?

if the list contains only integer:

reduce(lambda x,y: x*10+y, list)

Photoshop text tool adds punctuation to the beginning of text

This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.

How can I brew link a specific version?

The usage info:

Usage: brew switch <formula> <version>

Example:

brew switch mysql 5.5.29

You can find the versions installed on your system with info.

brew info mysql

And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers:

brew switch mysql 0

Update (15.10.2014):

The brew versions command has been removed from brew, but, if you do wish to use this command first run brew tap homebrew/boneyard.

The recommended way to install an old version is to install from the homebrew/versions repo as follows:

$ brew tap homebrew/versions
$ brew install mysql55

For detailed info on all the ways to install an older version of a formula read this answer.

Posting JSON Data to ASP.NET MVC

BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.

Example:

[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)

The BindModel function gets called three times, bombing on the first, as it tries to bind the JSON to customerId with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.

I added this block of code to the top of BindModel:

if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
    return base.BindModel(controllerContext, bindingContext);
}

The ValueProvider, fortunately, has route values figured out by the time it gets to this method.

$on and $broadcast in angular

//Your broadcast in service

(function () { 
    angular.module('appModule').factory('AppService', function ($rootScope, $timeout) {

    function refreshData() {  
        $timeout(function() {         
            $rootScope.$broadcast('refreshData');
        }, 0, true);      
    }

    return {           
        RefreshData: refreshData
    };
}); }());

//Controller Implementation
 (function () {
    angular.module('appModule').controller('AppController', function ($rootScope, $scope, $timeout, AppService) {            

       //Removes Listeners before adding them 
       //This line will solve the problem for multiple broadcast call                             
       $scope.$$listeners['refreshData'] = [];

       $scope.$on('refreshData', function() {                                                    
          $scope.showData();             
       });

       $scope.onSaveDataComplete = function() { 
         AppService.RefreshData();
       };
    }); }());

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Code I use myself:

std::string prefix = "-param=";
std::string argument = argv[1];
if(argument.substr(0, prefix.size()) == prefix) {
    std::string argumentValue = argument.substr(prefix.size());
}

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Thanks to this thread, and especially budidino because his code is what drove it home for me. Just wanted to contribute how to retrieve the JSON data from a request. Make changes to "//create request" request array part of the code to perform different requests. Ultimately, this will output the JSON onto the browser screen

<?php
    function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

function returnTweet(){
    $oauth_access_token         = "2602299919-lP6mgkqAMVwvHM1L0Cplw8idxJzvuZoQRzyMkOx";
    $oauth_access_token_secret  = "wGWny2kz67hGdnLe3Uuy63YZs4nIGs8wQtCU7KnOT5brS";
    $consumer_key               = "zAzJRrPOj5BvOsK5QhscKogVQ";
    $consumer_secret            = "Uag0ujVJomqPbfdoR2UAWbRYhjzgoU9jeo7qfZHCxR6a6ozcu1";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'burownrice',
            'count'             => '3'
        );

    $oauth = array(
        'oauth_consumer_key'        => $consumer_key,
        'oauth_nonce'               => time(),
        'oauth_signature_method'    => 'HMAC-SHA1',
        'oauth_token'               => $oauth_access_token,
        'oauth_timestamp'           => time(),
        'oauth_version'             => '1.0'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
        $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
        $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature']   = $oauth_signature;

    //  make request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        curl_close($feed);

    return $json;
}

$tweet = returnTweet();
echo $tweet;

?>

How to display length of filtered ng-repeat data

Here is worked example See on Plunker

  <body ng-controller="MainCtrl">
    <input ng-model="search" type="text">
    <br>
    Showing {{data.length}} Persons; <br>
    Filtered {{counted}}
    <ul>
      <li ng-repeat="person in data | filter:search">
        {{person.name}}
      </li>
    </ul>
  </body>

<script> 
var app = angular.module('angularjs-starter', [])

app.controller('MainCtrl', function($scope, $filter) {
  $scope.data = [
    {
      "name": "Jim", "age" : 21
    }, {
      "name": "Jerry", "age": 26
    }, {
      "name": "Alex",  "age" : 25
    }, {
      "name": "Max", "age": 22
    }
  ];

  $scope.counted = $scope.data.length; 
  $scope.$watch("search", function(query){
    $scope.counted = $filter("filter")($scope.data, query).length;
  });
});

Reverse HashMap keys and values in Java

To answer your question on how you can do it, you could get the entrySet from your map and then just put into the new map by using getValue as key and getKey as value.

But remember that keys in a Map are unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as value in the new map.

Undo a merge by pull request?

There is a better answer to this problem, though I could just break this down step-by-step.

You will need to fetch and checkout the latest upstream changes like so, e.g.:

git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar

Taking a look at the commit log, you should find something similar to this:

commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269
Merge: 9271e6e a507888
Author: Tim Tom <[email protected]>
Date:   Mon Apr 29 06:12:38 2013 -0700

    Merge pull request #123 from john/foo_and_bar

    Add foo and bar

commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e
Author: John Doe <[email protected]>
Date:   Mon Apr 29 12:13:29 2013 +0000

    Add bar

commit 470ee0f407198057d5cb1d6427bb8371eab6157e
Author: John Doe <[email protected]>
Date:   Mon Apr 29 10:29:10 2013 +0000

    Add foo

Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.

In the above example the merge commit is the top one where it says "Merged pull request #123...".

Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:

git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269

Contains case insensitive

It's 2016, and there's no clear way of how to do this? I was hoping for some copypasta. I'll have a go.

Design notes: I wanted to minimize memory usage, and therefore improve speed - so there is no copying/mutating of strings. I assume V8 (and other engines) can optimise this function.

//TODO: Performance testing
String.prototype.naturalIndexOf = function(needle) {
    //TODO: guard conditions here
    
    var haystack = this; //You can replace `haystack` for `this` below but I wan't to make the algorithm more readable for the answer
    var needleIndex = 0;
    var foundAt = 0;
    for (var haystackIndex = 0; haystackIndex < haystack.length; haystackIndex++) {
        var needleCode = needle.charCodeAt(needleIndex);
        if (needleCode >= 65 && needleCode <= 90) needleCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser
        var haystackCode = haystack.charCodeAt(haystackIndex);
        if (haystackCode >= 65 && haystackCode <= 90) haystackCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser
        
        //TODO: code to detect unicode characters and fallback to toLowerCase - when > 128?
        //if (needleCode > 128 || haystackCode > 128) return haystack.toLocaleLowerCase().indexOf(needle.toLocaleLowerCase();
        if (haystackCode !== needleCode)
        {
            foundAt = haystackIndex;
            needleIndex = 0; //Start again
        }
        else
            needleIndex++;
            
        if (needleIndex == needle.length)
            return foundAt;
    }
    
    return -1;
}

My reason for the name:

  • Should have IndexOf in the name
  • Don't add a suffix word - IndexOf refers to the following parameter. So prefix something instead.
  • Don't use "caseInsensitive" prefix would be sooooo long
  • "natural" is a good candidate, because default case sensitive comparisons are not natural to humans in the first place.

Why not...:

  • toLowerCase() - potential repeated calls to toLowerCase on the same string.
  • RegExp - awkward to search with variable. Even the RegExp object is awkward having to escape characters

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root  
--app.py     <-- file from which app will be run
--models
----user.py      <-- file with "User" model
----order.py    <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from app.py.

This concept is explained better by the answer to this thread posted by @SuperShoot

How do I find the caller of a method using stacktrace or reflection?

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

According to the Javadocs:

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

You will have to experiment to determine which index you want (probably stackTraceElements[1] or [2]).

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

App store link for "rate/review this app"

If your app has been approved for Beta and it's not live then the app review link is available but it won't be live to leave reviews.

  1. Log into iTunes Connect
  2. Click My Apps
  3. Click the App Icon your interested in
  4. Make sure your on the App Store page
  5. Go toApp Information section (it should automatically take you there)
  6. At the bottom of that page there is a blue link that says View on App Store. Click it and it will open to an a blank page. Copy what's in the url bar at the top of the page and that's your app reviews link. It will be live once the app is live.

enter image description here

Splitting a list into N parts of approximately equal length

This code is broken due to rounding errors. Do not use it!!!

assert len(chunkIt([1,2,3], 10)) == 10  # fails

Here's one that could work:

def chunkIt(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out

Testing:

>>> chunkIt(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> chunkIt(range(11), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
>>> chunkIt(range(12), 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

position fixed header in html

The position :fixed is differ from the other layout. Once you fixed the position for your header, keep in mind that you have to set the margin-top for the content div.

subtract time from date - moment js

You can create a much cleaner implementation with Moment.js Durations. No manual parsing necessary.

_x000D_
_x000D_
var time = moment.duration("00:03:15");_x000D_
var date = moment("2014-06-07 09:22:06");_x000D_
date.subtract(time);_x000D_
$('#MomentRocks').text(date.format())
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>_x000D_
<span id="MomentRocks"></span>
_x000D_
_x000D_
_x000D_

How do I resize a Google Map with JavaScript after it has loaded?

First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

google.maps.event.trigger({$id}, \"resize\");

And need the include below code in JavaScript

google.maps.event.addListenerOnce({$id}, 'idle', function(){
   setCenterMap(new google.maps.LatLng({$this->defaultLatitude}, 
   {$this->defaultLongitude}));
});

Date Difference in php on days?

I would recommend to use date->diff function, as in example below:

   $dStart = new DateTime('2012-07-26');
   $dEnd  = new DateTime('2012-08-26');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater

see http://www.php.net/manual/en/datetime.diff.php

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

Order columns through Bootstrap4

You can do two different container one with mobile order and hide on desktop screen, another with desktop order and hide on mobile screen

Understanding events and event handlers in C#

I agree with KE50 except that I view the 'event' keyword as an alias for 'ActionCollection' since the event holds a collection of actions to be performed (ie. the delegate).

using System;

namespace test{

class MyTestApp{
    //The Event Handler declaration
    public delegate void EventAction();

    //The Event Action Collection 
    //Equivalent to 
    //  public List<EventAction> EventActions=new List<EventAction>();
    //        
    public event EventAction EventActions;

    //An Action
    public void Hello(){
        Console.WriteLine("Hello World of events!");
    }
    //Another Action
    public void Goodbye(){
        Console.WriteLine("Goodbye Cruel World of events!");
    }

    public static void Main(){
        MyTestApp TestApp = new MyTestApp();

        //Add actions to the collection
        TestApp.EventActions += TestApp.Hello;
        TestApp.EventActions += TestApp.Goodbye;

        //Invoke all event actions
        if (TestApp.EventActions!= null){
            //this peculiar syntax hides the invoke 
            TestApp.EventActions();
            //using the 'ActionCollection' idea:
            // foreach(EventAction action in TestApp.EventActions)
            //     action.Invoke();
        }
    }

}   

}

Passing an integer by reference in Python

Maybe it's not pythonic way, but you can do this

import ctypes

def incr(a):
    a += 1

x = ctypes.c_int(1) # create c-var
incr(ctypes.ctypes.byref(x)) # passing by ref

PHP: convert spaces in string into %20?

Use the rawurlencode function instead.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Can we create an instance of an interface in Java?

You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,

public interface A
{
}
public class B implements A
{
}

public static void main(String[] args)
{
    A test = new B();
    //A test = new A(); // wont compile
}

What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

database user does not have the permission to do select query.

you can grant the permission to the user if you have root access to mysql

http://dev.mysql.com/doc/refman/5.1/en/grant.html

Your second query is on different database on different table.

 String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";

And the user you are connecting with does not have permission to access data from this database or this particular table.

Have you consider this thing?

Decreasing for loops in Python impossible?

This is very late, but I just wanted to add that there is a more elegant way: using reversed

for i in reversed(range(10)):
    print i

gives:

4
3
2
1
0

How to import jquery using ES6 syntax?

If you are not using any JS build tools/NPM, then you can directly include Jquery as:

import  'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;

You may skip import(Line 1) if you already included jquery using script tag under head.

Creating a textarea with auto-resize

You can use this code:

Coffescript:

jQuery.fn.extend autoHeightTextarea: ->
  autoHeightTextarea_ = (element) ->
    jQuery(element).css(
      'height': 'auto'
      'overflow-y': 'hidden').height element.scrollHeight

  @each ->
    autoHeightTextarea_(@).on 'input', ->
      autoHeightTextarea_ @

$('textarea_class_or_id`').autoHeightTextarea()

Javascript

jQuery.fn.extend({
  autoHeightTextarea: function() {
    var autoHeightTextarea_;
    autoHeightTextarea_ = function(element) {
      return jQuery(element).css({
        'height': 'auto',
        'overflow-y': 'hidden'
      }).height(element.scrollHeight);
    };
    return this.each(function() {
      return autoHeightTextarea_(this).on('input', function() {
        return autoHeightTextarea_(this);
      });
    });
  }
});

$('textarea_class_or_id`').autoHeightTextarea();

What does a circled plus mean?

I used the logic in the replies by rampion and schnaader. I will summarise how I confirmed the results. I changed the numbers to binary and then used the XOR-operation. Alternatively, you can use the Hexadecimal tables: Click here!

How can I get the executing assembly version?

Product Version may be preferred if you're using versioning via GitVersion or other versioning software.

To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion:

using System.Diagnostics;
using System.Reflection;

//...

var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion

enter image description here

Firebase cloud messaging notification not received by device

In my case, I just turn on WIFI and mobile data in the emulator and it works like a charm. cause I can't send comments, post a reply. Good luck

Extracting substrings in Go

To get substring

  1. find position of "sp"

  2. cut string with array-logical

https://play.golang.org/p/0Redd_qiZM

How to prevent multiple definitions in C?

I had similar problem and i solved it following way.

Solve as follows:

Function prototype declarations and global variable should be in test.h file and you can not initialize global variable in header file.

Function definition and use of global variable in test.c file

if you initialize global variables in header it will have following error

multiple definition of `_ test'| obj\Debug\main.o:path\test.c|1|first defined here|

Just declarations of global variables in Header file no initialization should work.

Hope it helps

Cheers

How to open a new form from another form

Try this..

//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
    this.Visible = false;     // this = is the current form
    SignUp s = new SignUp();  //SignUp is the name of  my other form
    s.Visible = true;
}

Disabling vertical scrolling in UIScrollView

You need to pass 0 in content size to disable in which direction you want.

To disable vertical scrolling

scrollView.contentSize = CGSizeMake(scrollView.contentSize.width,0);

To disable horizontal scrolling

scrollView.contentSize = CGSizeMake(0,scrollView.contentSize.height);

What is the use of System.in.read()?

Just to complement the accepted answer, you could also use System.out.read() like this:

class Example {
    public static void main(String args[])
        throws java.io.IOException { // This works! No need to use try{// ...}catch(IOException ex){// ...}         

        System.out.println("Type a letter: ");
        char letter = (char) System.in.read();
        System.out.println("You typed the letter " + letter);
    }
}

How can I set a css border on one side only?

If you want to set 4 sides separately use:

border-width: 1px 2em 5px 0; /* top right bottom left */
border-style: solid dotted inset double;
border-color: #f00 #0f0 #00f #ff0;

"detached entity passed to persist error" with JPA/EJB code

The error occurs because the object's ID is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects. If persist concludes the object is detached (which it will because the ID is set), it will return the "detached object passed to persist" error. You can find more details here and here.

However, this only applies if you have specified the primary key to be auto-generated: if the field is configured to always be set manually, then your code works.

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

What does T&& (double ampersand) mean in C++11?

The term for T&& when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.

That is because it may be either r-value or l-value.

Examples are:

// template
template<class T> foo(T&& t) { ... }

// auto
auto&& t = ...;

// typedef
typedef ... T;
T&& t = ...;

// decltype
decltype(...)&& t = ...;

More discussion can be found in the answer for: Syntax for universal references

caching JavaScript files

I have a simple system that is pure JavaScript. It checks for changes in a simple text file that is never cached. When you upload a new version this file is changed. Just put the following JS at the top of the page.

_x000D_
_x000D_
        (function(url, storageName) {_x000D_
            var fromStorage = localStorage.getItem(storageName);_x000D_
            var fullUrl = url + "?rand=" + (Math.floor(Math.random() * 100000000));_x000D_
            getUrl(function(fromUrl) {_x000D_
//                   first load_x000D_
                if (!fromStorage) {_x000D_
                    localStorage.setItem(storageName, fromUrl);_x000D_
                    return;_x000D_
                }_x000D_
//                    old file_x000D_
                if (fromStorage === fromUrl) {_x000D_
                    return;_x000D_
                }_x000D_
                // files updated_x000D_
                localStorage.setItem(storageName, fromUrl);_x000D_
                location.reload(true);_x000D_
            });_x000D_
            function getUrl(fn) {_x000D_
                var xmlhttp = new XMLHttpRequest();_x000D_
                xmlhttp.open("GET", fullUrl, true);_x000D_
                xmlhttp.send();_x000D_
                xmlhttp.onreadystatechange = function() {_x000D_
                    if (xmlhttp.readyState === XMLHttpRequest.DONE) {_x000D_
                        if (xmlhttp.status === 200 || xmlhttp.status === 2) {_x000D_
                            fn(xmlhttp.responseText);_x000D_
                        }_x000D_
                        else if (xmlhttp.status === 400) {_x000D_
                            throw 'unable to load file for cache check ' +  url;_x000D_
                        }_x000D_
                        else {_x000D_
                           throw 'unable to load file for cache check ' +  url;_x000D_
                        }_x000D_
                    }_x000D_
                };_x000D_
            }_x000D_
            ;_x000D_
        })("version.txt", "version");
_x000D_
_x000D_
_x000D_

just replace the "version.txt" with your file that is always run and "version" with the name you want to use for your local storage.

Concept behind putting wait(),notify() methods in Object class

wait and notify operations work on implicit lock, and implicit lock is something that make inter thread communication possible. And all objects have got their own copy of implicit object. so keeping wait and notify where implicit lock lives is a good decision.

Alternatively wait and notify could have lived in Thread class as well. than instead of wait() we may have to call Thread.getCurrentThread().wait(), same with notify. For wait and notify operations there are two required parameters, one is thread who will be waiting or notifying other is implicit lock of the object . both are these could be available in Object as well as thread class as well. wait() method in Thread class would have done the same as it is doing in Object class, transition current thread to waiting state wait on the lock it had last acquired.

So yes i think wait and notify could have been there in Thread class as well but its more like a design decision to keep it in object class.

Call a python function from jinja2

Use a lambda to connect the template to your main code

return render_template("clever_template", clever_function=lambda x: clever_function x)

Then you can seamlessly call the function in the template

{{clever_function(value)}}

Laravel - Return json along with http status code

It's better to do it with helper functions rather than Facades. This solution will work well from Laravel 5.7 onwards

//import dependency
use Illuminate\Http\Response;

//snippet
return \response()->json([
   'status' => '403',//sample entry
   'message' => 'ACCOUNT ACTION HAS BEEN DISABLED',//sample message
], Response::HTTP_FORBIDDEN);//Illuminate\Http\Response sets appropriate headers

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

How to convert a byte to its binary string representation

Just guessing here, but if you have a Byte then couldn't you simply invoke toString() on the object to get the value? Or, glancing at the api, using byteValue()?

how can I enable scrollbars on the WPF Datagrid?

Put the DataGrid in a Grid, DockPanel, ContentControl or directly in the Window. A vertically-oriented StackPanel will give its children whatever vertical space they ask for - even if that means it is rendered out of view.

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)

turning it back to 1.0.7 solved the problem instantly.

have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.

anyway, this problem is fixed when using AngularJS vs 1.0.7.

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

How to make a .jar out from an Android Studio project

Simply add this to your java module's build.gradle. It will include dependent libraries in archive.

mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

This will result in [module_name]/build/libs/[module_name].jar file.

Convert pandas data frame to series

Another way -

Suppose myResult is the dataFrame that contains your data in the form of 1 col and 23 rows

# label your columns by passing a list of names
myResult.columns = ['firstCol']

# fetch the column in this way, which will return you a series
myResult = myResult['firstCol']

print(type(myResult))

In similar fashion, you can get series from Dataframe with multiple columns.

Best way to parse RSS/Atom feeds with PHP

If feed isn't well-formed XML, you're supposed to reject it, no exceptions. You're entitled to call feed creator a bozo.

Otherwise you're paving way to mess that HTML ended up in.

Installing jQuery?

If you want to use a package manager,

You can use bower:

bower install jquery-ui

How to Apply Mask to Image in OpenCV?

You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.

How can I reverse a NSArray in Objective-C?

There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator method on NSArray, and the allObjects method of NSEnumerator:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

allObjects is documented as returning an array with the objects that have not yet been traversed with nextObject, in order:

This array contains all the remaining objects of the enumerator in enumerated order.

Override hosts variable of Ansible playbook from the command line

I'm using another approach that doesn't need any inventory and works with this simple command:

ansible-playbook site.yml -e working_host=myhost

To perform that, you need a playbook with two plays:

  • first play runs on localhost and add a host (from given variable) in a known group in inmemory inventory
  • second play runs on this known group

A working example (copy it and runs it with previous command):

- hosts: localhost
  connection: local
  tasks:
  - add_host:
      name: "{{ working_host }}"
      groups: working_group
    changed_when: false

- hosts: working_group
  gather_facts: false
  tasks:
  - debug:
      msg: "I'm on {{ ansible_host }}"

I'm using ansible 2.4.3 and 2.3.3

How to parse SOAP XML?

why don't u try using an absolute xPath

//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment

or since u know that it is a payment and payment doesn't have any attributes just select directly from payment

//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment/*

How can I count the number of elements of a given value in a matrix?

assume w contains week numbers ([1:7])

n = histc(M,w)

if you do not know the range of numbers in M:

n = histc(M,unique(M))

It is such as a SQL Group by command!

Smooth scroll without the use of jQuery

With using the following smooth scrolling is working fine:

_x000D_
_x000D_
html {_x000D_
  scroll-behavior: smooth;_x000D_
}
_x000D_
_x000D_
_x000D_

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

How to stop C# console applications from closing automatically?

Console.ReadLine() to wait for the user to Enter or Console.ReadKey to wait for any key.

Use 'import module' or 'from module import'?

I've just discovered one more subtle difference between these two methods.

If module foo uses a following import:

from itertools import count

Then module bar can by mistake use count as though it was defined in foo, not in itertools:

import foo
foo.count()

If foo uses:

import itertools

the mistake is still possible, but less likely to be made. bar needs to:

import foo
foo.itertools.count()

This caused some troubles to me. I had a module that by mistake imported an exception from a module that did not define it, only imported it from other module (using from module import SomeException). When the import was no longer needed and removed, the offending module was broken.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

Try to set :

default_socket_timeout = 120

in your php.ini file.

Convert String into a Class Object

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.


If you did this:

SomeClass object = ...
String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.


If you did something like this:

SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)


If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

How to change the color of winform DataGridview header?

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

How to combine date from one field with time from another field - MS SQL Server

Convert both field into DATETIME :

SELECT CAST(@DateField as DATETIME) + CAST(@TimeField AS DATETIME)

and if you're using Getdate() use this first:

DECLARE @FechaActual DATETIME = CONVERT(DATE, GETDATE());
SELECT CAST(@FechaActual as DATETIME) + CAST(@HoraInicioTurno AS DATETIME)

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

How to un-commit last un-pushed git commit without losing the changes

PLease make sure to backup your changes before running these commmand in a separate folder

git checkout branch_name

Checkout on your branch

git merge --abort

Abort the merge

git status

Check status of the code after aborting the merge

git reset --hard origin/branch_name

these command will reset your changes and align your code with the branch_name (branch) code.

127 Return code from $?

If the IBM mainframe JCL has some extra characters or numbers at the end of the name of unix script being called then it can throw such error.

Java reflection: how to get field value from an object, not knowing its class

Assuming a simple case, where your field is public:

List list; // from your method
for(Object x : list) {
    Class<?> clazz = x.getClass();
    Field field = clazz.getField("fieldName"); //Note, this can throw an exception if the field doesn't exist.
    Object fieldValue = field.get(x);
}

But this is pretty ugly, and I left out all of the try-catches, and makes a number of assumptions (public field, reflection available, nice security manager).

If you can change your method to return a List<Foo>, this becomes very easy because the iterator then can give you type information:

List<Foo> list; //From your method
for(Foo foo:list) {
    Object fieldValue = foo.fieldName;
}

Or if you're consuming a Java 1.4 interface where generics aren't available, but you know the type of the objects that should be in the list...

List list;
for(Object x: list) {
   if( x instanceof Foo) {
      Object fieldValue = ((Foo)x).fieldName;
   }
}

No reflection needed :)

Passing multiple argument through CommandArgument of Button in Asp.net

After poking around it looks like Kelsey is correct.

Just use a comma or something and split it when you want to consume it.