Programs & Examples On #Rails routing

The component of the Ruby on Rails framework responsible for mapping between HTTP requests and application resources (including static files and controller actions).

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

(Edit: Forget my previous babble...)

Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.

About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController (e.g. "UsersController" is the controller of the model "User").

If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.

How to synchronize or lock upon variables in Java?

For this functionality you are better off not using a lock at all. Try an AtomicReference.

public class Sample {
    private final AtomicReference<String> msg = new AtomicReference<String>();

    public void setMsg(String x) {
        msg.set(x);
    }

    public String getMsg() {
        return msg.getAndSet(null);
    }
}

No locks required and the code is simpler IMHO. In any case, it uses a standard construct which does what you want.

How to try convert a string to a Guid

new Guid(string)

You could also look at using a TypeConverter.

Computed / calculated / virtual / derived columns in PostgreSQL

Well, not sure if this is what You mean but Posgres normally support "dummy" ETL syntax. I created one empty column in table and then needed to fill it by calculated records depending on values in row.

UPDATE table01
SET column03 = column01*column02; /*e.g. for multiplication of 2 values*/
  1. It is so dummy I suspect it is not what You are looking for.
  2. Obviously it is not dynamic, you run it once. But no obstacle to get it into trigger.

How to position a Bootstrap popover?

Popover's Viewport (Bootstrap v3)

The best solution that will work for you in all occassions, especially if your website has a fluid width, is to use the viewport option of the Bootstrap Popover.

This will make the popover take width inside a selector you have assigned. So if the trigger button is on the right of that container, the bootstrap arrow will also appear on the right while the popover is inside that area. See jsfiddle.net

You can also use padding if you want some space from the edge of container. If you want no padding just use viewport: '.container'

$('#popoverButton').popover({
   container: 'body',
   placement: "bottom",
   html: true,   
   viewport: { selector: '.container', padding: 5 },
   content: '<strong>Hello Wooooooooooooooooooooooorld</strong>'
 });

in the following html example:

<div class="container">
   <button type="button" id="popoverButton">Click Me!</button>
</div>

and with CSS:

.container {
  text-align:right;
  width: 100px;
  padding: 20px;
  background: blue;
}

Popover's Boundary (Bootstrap v4)

Similar to viewport, in Bootstrap version 4, popover introduced the new option boundary

https://getbootstrap.com/docs/4.1/components/popovers/#options

How to get UTC timestamp in Ruby?

time = Time.zone.now()

It will work as

irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC

Lost connection to MySQL server during query?

Usually that happens when you exhaust one resource for the db session, such as memory, and mysql closes the connection.

Can you break the CSV file into smaller ones and process them? or do commit every 100 rows? The idea is that the transaction you're running shouldn't try to insert a large amount of data.

I forgot to add, this error is related to the configuration property max_allowed_packet, but I can't remember the details of what to change.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I got the same error in 1.10.2. In my case, I wanted to make clicking on the background overlay hide the currently visible dialog, regardless of which element it was based upon. Therefore I had this:

$('body').on("click", ".ui-widget-overlay", function () {
    $(".ui-dialog").dialog('destroy');
});

This used to be working, so I think they must have removed support in JQUI for calling .dialog() on the popup itself at some point.

My workaround looks like this:

$('body').on("click", ".ui-widget-overlay", function () {
    $('#' + $(".ui-dialog").attr('aria-describedby')).dialog('destroy');
});

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

How to see data from .RData file?

If you have a lot of variables in your Rdata file and don't want them to clutter your global environment, create a new environment and load all of the data to this new environment.

load(file.path("C:/Users/isfar.RData"), isfar_env <- new.env() )

# Access individual variables in the RData file using '$' operator
isfar_env$var_name 

# List all of the variable names in RData:
ls(isfar_env)

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

How to import a jar in Eclipse

first of all you will go to your project what you are created and next right click in your mouse and select properties in the bottom and select build in path in the left corner and add external jar file add click apply .that's it

Sql Server return the value of identity column after insert statement

Here goes a bunch of different ways to get the ID, including Scope_Identity:

https://stackoverflow.com/a/42655/1504882

fatal: The current branch master has no upstream branch

If you constantly get the following git error message after attempting a git push with a new local branch:

fatal: The current branch has no upstream branch.

To push the current branch and set the remote as upstream, use

git push --set-upstream origin <branchname>

Then the issue is that you have not configured git to always create new branches on the remote from local ones.

The permanent fix if you always want to just create that new branch on the remote to mirror and track your local branch is:

git config --global push.default current

Now you can git push without any errors!

https://vancelucas.com/blog/how-to-fix-git-fatal-the-current-branch-has-no-upstream-branch/

Making an iframe responsive

Remove iframe height and width specified in pixels and use percentage

iframe{  max-width: 100%;}

Stop a youtube video with jquery?

if you are using sometimes playerID.stopVideo(); doesnot work, here is a trick,

 function stopVideo() {
           playerID.seekTo(0);
    playerID.stopVideo();
}

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.

As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are

  1. define objects in the parent for your model, then reference a property of that object in the child: parentObj.someProp
  2. use $parent.parentScopeProperty (not always possible, but easier than 1. where possible)
  3. define a function on the parent scope, and call it from the child (not always possible)

New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use

<input type="text" ng-model="someObj.prop1">

<!--rather than
<input type="text" ng-model="prop1">`
-->


L-o-n-g answer:

JavaScript Prototypal Inheritance

Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes

It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.

Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:

prototypal inheritance

(Note that to save space, I show the anArray object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)

If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:

childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'

Suppose we then do this:

childScope.aString = 'child string'

The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.

property hiding

Suppose we then do this:

childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'

The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)

follow the prototype chain

Suppose we then do this:

childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }

The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.

more property hiding

Takeaways:

  • If we read childScope.propertyX, and childScope has propertyX, then the prototype chain is not consulted.
  • If we set childScope.propertyX, the prototype chain is not consulted.

One last scenario:

delete childScope.anArray
childScope.anArray[1] === 22  // true

We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.

after removing a child property


Angular Scope Inheritance

The contenders:

  • The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-controller, directive with scope: true, directive with transclude: true.
  • The following creates a new scope which does not inherit prototypically: directive with scope: { ... }. This creates an "isolate" scope instead.

Note, by default, directives do not create new scope -- i.e., the default is scope: false.

ng-include

Suppose we have in our controller:

$scope.myPrimitive = 50;
$scope.myObject    = {aNumber: 11};

And in our HTML:

<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>

<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>

Each ng-include generates a new child scope, which prototypically inherits from the parent scope.

ng-include child scopes

Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.

ng-include with a primitive

Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.

ng-include with an object

We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:

<input ng-model="$parent.myPrimitive">

Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).

ng-include with $parent

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.

For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,

// in the parent scope
$scope.setMyPrimitive = function(value) {
     $scope.myPrimitive = value;
}

Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)

See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.

ng-switch

ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.

See also AngularJS, bind scope of a switch-case?

ng-repeat

Ng-repeat works a little differently. Suppose we have in our controller:

$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects    = [{num: 101}, {num: 202}]

And in our HTML:

<ul><li ng-repeat="num in myArrayOfPrimitives">
       <input ng-model="num">
    </li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
       <input ng-model="obj.num">
    </li>
<ul>

For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:

childScope = scope.$new();  // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value;  // creates a new childScope property

If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num property that is independent of the myArrayOfPrimitives array:

ng-repeat with primitives

This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.

So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num) does change the object the parent scope references. So in the second ng-repeat above, we have:

ng-repeat with objects

(I colored one line gray just so that it is clear where it is going.)

This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.

See also Difficulty with ng-model, ng-repeat, and inputs and https://stackoverflow.com/a/13782671/215945

ng-controller

Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply. However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/ A service should be used to share data between controllers instead.

(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)

directives

  1. default (scope: false) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.
  2. scope: true - the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.
  3. scope: { ... } - the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope. Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp in the isolated scope: <div my-directive> and scope: { localProp: '@parentProp' }. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp> and scope: { localProp: '@theParentProp' }.
    Isolate scope's __proto__ references Object. Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
    For the picture below we have
    <my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2"> and
    scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
    Also, assume the directive does this in its linking function: scope.someIsolateProp = "I'm isolated"
    isolated scope
    For more information on isolate scopes see http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
  4. transclude: true - the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
    For the picture below, assume the same directive as above with this addition: transclude: true
    transcluded scope

This fiddle has a showScope() function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.


Summary

There are four types of scopes:

  1. normal prototypal scope inheritance -- ng-include, ng-switch, ng-controller, directive with scope: true
  2. normal prototypal scope inheritance with a copy/assignment -- ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
  3. isolate scope -- directive with scope: {...}. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.
  4. transcluded scope -- directive with transclude: true. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.

Diagrams were generated with "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.

Undefined index with $_POST

I know that this is old post but someone can help:

function POST($index, $default=NULL){
        if(isset($_POST[$index]))
        {
            if(!empty(trim($_POST[$index])))    
                return $_POST[$index];
        }
        return $default;
    }

This code above are my basic POST function what I use anywhere. Here you can put filters, regular expressions, etc. Is faster and clean. My advanced POST function is more complicate to accept and check arrays, string type, default values etc. Let's your imagination work here.

You easy can check username like this:

$username = POST("username");
if($username!==null){
    echo "{$username} is in the house.";
}

Also I added $default string that you can define some default value if POST is not active or content not exists.

echo "<h1>".POST("title", "Stack Overflow")."</h1>";

Play with it.

pull access denied repository does not exist or may require docker login

If you don't have an image with that name locally, docker will try to pull it from docker hub, but there's no such image on docker hub. Or simply try "docker login".

How to use Fiddler to monitor WCF service

Consolidating the caveats mentioned in comments/answers for several use cases.

Mostly, see http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigureDotNETApp

  • Start Fiddler before your app
  • In a console app, you might not need to specify the proxyaddress:

    <proxy bypassonlocal="False" usesystemdefault="True" />
    
  • In a web application / something hosted in IIS, you need to add the proxyaddress:

    <proxy bypassonlocal="False" usesystemdefault="True" proxyaddress="http://127.0.0.1:8888" />
    
  • When .NET makes a request (through a service client or HttpWebRequest, etc) it will always bypass the Fiddler proxy for URLs containing localhost, so you must use an alias like the machine name or make up something in your 'hosts' file (which is why something like localhost.fiddler or http://HOSTNAME works)
  • If you specify the proxyaddress, you must remove it from your config if Fiddler isn't on, or any requests your app makes will throw an exception like:

    No connection could be made because the target machine actively refused it 127.0.0.1:8888

  • Don't forget to use config transformations to remove the proxy section in production

What is the difference between Serialization and Marshaling?

Marshalling is the rule to tell compiler how the data will be represented on another environment/system; For example;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;

as you can see two different string values represented as different value types.

Serialization will only convert object content, not representation (will stay same) and obey rules of serialization, (what to export or no). For example, private values will not be serialized, public values yes and object structure will stay same.

jQuery $(document).ready and UpdatePanels?

Upgrade to jQuery 1.3 and use:

$(function() {

    $('div._Foo').live("mouseover", function(e) {
        // Do something exciting
    });

});

Note: live works with most events, but not all. There is a complete list in the documentation.

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

Asynchronous Function Call in PHP

cURL is going to be your only real choice here (either that, or using non-blocking sockets and some custom logic).

This link should send you in the right direction. There is no asynchronous processing in PHP, but if you're trying to make multiple simultaneous web requests, cURL multi will take care of that for you.

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

  1. find your php.ini
  2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir)
  3. make sure the directive extension=php_mbstring.dll is set (uncommented)

If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.

Remove composer

curl -sS https://getcomposer.org/installer | sudo php
sudo mv composer.phar /usr/local/bin/composer
export PATH="$HOME/.composer/vendor/bin:$PATH"

If you have installed by this way simply

Delete composer.phar from where you've putted it.

In this case path will be /usr/local/bin/composer

Note: There is no need to delete the exported path.

Convert data.frame columns from factors to characters

This function does the trick

df <- stacomirtools::killfactor(df)

Change the Theme in Jupyter Notebook?

For Dark Mode Only: -

I have used Raleway Font for styling

To C:\User\UserName\.jupyter\custom\custom.css file

append the given styles, this is specifically for Dark Mode for jupyter notebook...

This should be your current custom.css file: -

/* This file contains any manual css for this page that needs to override the global styles.
    This is only required when different pages style the same element differently. This is just
    a hack to deal with our current css styles and no new styling should be added in this file.*/

#ipython-main-app {
    position: relative;
}

#jupyter-main-app {
    position: relative;
}

Content to be append starts now

.header-bar {
    display: none;
}

#header-container img {
    display: none;
}

#notebook_name {
    margin-left: 0px !important;
}

#header-container {
    padding-left: 0px !important
}

html,
body {
    overflow: hidden;
    font-family: OpenSans;
}

#header {
    background-color: #212121 !important;
    color: #fff;
    padding-top: 20px;
    padding-bottom: 50px;
}

.navbar-collapse {
    background-color: #212121 !important;
    color: #fff;
    border: none !important
}

#menus {
    border: none !important;
    color: white !important;
}

#menus .dropdown-toggle {
    color: white !important;
}

#filelink {
    color: white !important;
    text-align: centerimportant;
    padding-left: 7px;
    text-decoration: none !important;
}

.navbar-default .navbar-nav>.open>a,
.navbar-default .navbar-nav>.open>a:hover,
.navbar-default .navbar-nav>.open>a:focus {
    background-color: #191919 !important;
    color: #eee !important;
    text-align: left !important;
}

.dropdown-menu,
.dropdown-menu a,
.dropdown-submenu a {
    background-color: #191919;
    color: #fff !important;
}

.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-submenu>a:after {
    background-color: #212121;
    color: #fff !important;
}

.btn-default {
    color: #fff !important;
    background-color: #212121 !important;
    border: none !important;
}

.dropdown {
    text-align: left !important;
}

.form-control.select-xs {
    background-color: #191919 !important;
    color: #eee !important;
    border: none;
    outline: none;
}

#modal_indicator {
    display: none;
}

#kernel_indicator {
    color: #fff;
}

#notification_trusted,
#notification_notebook {
    background-color: #212121;
    color: #eee !important;
    border: none;
    border-bottom: 1px solid #eee;
}

#logout {
    background-color: #191919;
    color: #eee;
}

#maintoolbar-container {
    padding-top: 0px !important;
}

.notebook_app {
    background-color: #222222;
}

::-webkit-scrollbar {
    display: none;
}

#notebook-container {
    background-color: #212121;
}

div.cell.selected,
div.cell.selected.jupyter-soft-selected {
    border: none !important;
}

.cm-keyword {
    color: orange !important;
}

.input_area {
    background-color: #212121 !important;
    color: white !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
}

.cm-def {
    color: #5bc0de !important;
}

.cm-variable {
    color: yellow !important;
}

.output_subarea.output_text.output_result pre,
.output_subarea.output_text.output_stream.output_stdout pre {
    color: white !important;
}

.CodeMirror-line {
    color: white !important;
}

.cm-operator {
    color: white !important;
}

.cm-number {
    color: lightblue !important;
}

.inner_cell {
    border: 1px thin #eee;
    border-radius: 50px !important;
}

.CodeMirror-lines {
    border-radius: 20px;
}

.prompt.input_prompt {
    color: #5cb85c !important;
}

.prompt.output_prompt {
    color: lightblue;
}

.cm-string {
    color: #6872ac !important;
}

.cm-builtin {
    color: #f0ad4e !important;
}

.run_this_cell {
    color: lightblue !important;
}

.input_area {
    border-radius: 20px;
}

.output_png {
    background-color: white;
}

.CodeMirror-cursor {
    border-left: 1.4px solid white;
}

.box-flex1.output_subarea.raw_input_container {
    color: white;
}

input.raw_input {
    color: black !important;
}

div.output_area pre {
    color: white
}

h1,
h2,
h3,
h4,
h5,
h6 {
    color: white !important;
    font-weight: bolder !important;
}

.CodeMirror-gutter.CodeMirror-linenumber,
.CodeMirror-gutters {
    background-color: #212121 !important;
}


span.filename:hover {
    color: #191919 !important;
    height: auto !important;
}

#site {
    background-color: #191919 !important;
    color: white !important;
}

#tabs li.active a {
    background-color: #212121 !important;
    color: white !important;
}

#tabs li {
    background-color: #191919 !important;
    color: white !important;
    border-top: 1px thin #eee;
}

#notebook_list_header {
    background-color: #212121 !important;
    color: white !important;
}

#running .panel-group .panel {
    background-color: #212121 !important;
    color: white !important;
}

#accordion.panel-heading {
    background-color: #212121 !important;
}

#running .panel-group .panel .panel-heading {
    background-color: #212121;
    color: white
}

.item_name {
    color: white !important;
    cursor: pointer !important;
}

.list_item:hover {
    background-color: #212121 !important;
}

.item_icon.icon-fixed-width {
    color: white !important;
}

#texteditor-backdrop {
    background-color: #191919 !important;
    border-top: 1px solid #eee;
}

.CodeMirror {
    background-color: #212121 !important;
}

#texteditor-backdrop #texteditor-container .CodeMirror-gutter,
#texteditor-backdrop #texteditor-container .CodeMirror-gutters {
    background-color: #212121 !important;
}

.celltoolbar {
    background-color: #212121 !important;
    border: none !important;
}

Dark Mode for Jupyter Notebook

Dark Mode for Jupyter Notebook

Angular2 - Focusing a textbox on component load

Using simple autofocus HTML5 attribute works for 'on load' scenario

 <input autofocus placeholder="enter text" [(ngModel)]="test">

or

<button autofocus (click)="submit()">Submit</button>

http://www.w3schools.com/TAgs/att_input_autofocus.asp

Angular 5 Service to read local .json file

For Angular 7, I followed these steps to directly import json data:

In tsconfig.app.json:

add "resolveJsonModule": true in "compilerOptions"

In a service or component:

import * as exampleData from '../example.json';

And then

private example = exampleData;

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

SELECT date1 - date2
  FROM some_table

returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So

SELECT (date1 - date2) * 24 * 60 difference_in_minutes
  FROM some_table

should be what you're looking for

Vagrant ssh authentication failure

Mac Solution:

  1. Added local ssh id_rsa key to vagrant private key

    vi /Users//.vagrant/machines/default/virtualbox/private_key

    /Users//.ssh/id_rsa

  2. copied public key /Users//.ssh/id_rsa.pub on vagrant box authorized_keys

ssh vagrant@localhost -p 2222 (password: vagrant) ls -la cd .ssh

  1. chmod 0600 ~/.ssh/authorized_keys

  2. vagrant reload

Problem resolved.

Thanks to

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

Instead of using fake dates like 0000-00-00 00:00:00 or 0001-01-01 00:00:00 (the latter should be accepted as it is a valid date), change your database schema, to allow NULL values.

ALTER TABLE table_name MODIFY COLUMN date TIMESTAMP NULL

How to get a dependency tree for an artifact?

I created an online tool to do this. Simply paste any dependency in pom file format, and the dependency tree for that artifact is generated, based on the central maven repository.

In SQL, how can you "group by" in ranges?

Because the column being sorted on (Range) is a string, string/word sorting is used instead of numeric sorting.

As long as the strings have zeros to pad out the number lengths the sorting should still be semantically correct:

SELECT t.range AS ScoreRange,
       COUNT(*) AS NumberOfOccurrences
  FROM (SELECT CASE
                    WHEN score BETWEEN 0 AND 9 THEN '00-09'
                    WHEN score BETWEEN 10 AND 19 THEN '10-19'
                    ELSE '20-99'
               END AS Range
          FROM Scores) t
 GROUP BY t.Range

If the range is mixed, simply pad an extra zero:

SELECT t.range AS ScoreRange,
       COUNT(*) AS NumberOfOccurrences
  FROM (SELECT CASE
                    WHEN score BETWEEN 0 AND 9 THEN '000-009'
                    WHEN score BETWEEN 10 AND 19 THEN '010-019'
                    WHEN score BETWEEN 20 AND 99 THEN '020-099'
                    ELSE '100-999'
               END AS Range
          FROM Scores) t
 GROUP BY t.Range

hibernate could not get next sequence value

The Database that we are using should be mentioned under search_path in Postgres SQL Configuration file. This can be done by editing Postgressql configuration file by setting search_path along with database name for example: TESTDB.

  1. Find postgressql.conf file under data folder of Postgres SQL datbase.
  2. Set search_path = "$user", public, TESTDB;
  3. Restart the Postgres SQL service to affect the change.

It worked for me after making the above change.

Jquery Hide table rows

html

<tr><td><a href="" onclick=hideRow(event)></a></td></tr>

jquery

function hideRow(event){
  $(event.target || event.srcElement).parents('tr').hide();
}

Groovy Shell warning "Could not open/create prefs root node ..."

If anyone is trying to solve this on a 64-bit version of Windows, you might need to create the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

A Simple, 2d cross-platform graphics library for c or c++?

[In no particular order.] However, if you have any other requirements, let us know. BTW: I am not just posting results of a Google query here, I have used all of these (and SDL -- wrote my first few games in SDL :) and I'd say without a set of requirements, it's very difficult to choose among the ones listed.

How to find out mySQL server ip address from phpmyadmin

You can ssh to your server and run this command

 ln -s /usr/share/phpmyadmin /var/www/phpmyadmin

It worked for me..

How do I add Git version control (Bitbucket) to an existing source code folder?

User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:

  1. Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:

    Create repository on Bitbucket

  2. Fill in the form, click next and then you automatically go to this page:

    Create repository from scratch or add existing files

  3. Choose to add existing files and you go to this page:

    Enter image description here

  4. You use those commands and you upload the existing files to Bitbucket. After that, the files are online.

How do I protect Python code?

Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like py2exe, the layout of the executable is well-known, and the Python byte-codes are well understood.

Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.

If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.

Multiple Python versions on the same machine?

How to install different Python versions is indeed OS dependent.

However, if you're on linux, you can use a tool like pythonbrew or pythonz to help you easily manage and switch between different versions.

ImportError: No module named sklearn.cross_validation

train_test_split is part of the module sklearn.model_selection, hence, you may need to import the module from model_selection

Code:

from sklearn.model_selection import train_test_split

..The underlying connection was closed: An unexpected error occurred on a receive

Setting the HttpWebRequest.KeepAlive to false didn't work for me.

Since I was accessing a HTTPS page I had to set the Service Point Security Protocol to Tls12.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Notice that there are other SecurityProtocolTypes: SecurityProtocolType.Ssl3, SecurityProtocolType.Tls, SecurityProtocolType.Tls11

So if the Tls12 doesn't work for you, try the three remaining options.

Also notice that you can set multiple protocols. This is preferable on most cases.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

Edit: Since this is a choice of security standards it's obviously best to go with the latest (TLS 1.2 as of writing this), and not just doing what works. In fact, SSL3 has been officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well. source: @aske-b

How to efficiently use try...catch blocks in PHP

There is no any problem to write multiple lines of execution withing a single try catch block like below

try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}

The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Firstly uninstall the existing npm package: npm uninstall -g create-react-app (-g if you installed globally) Secondly: npm cache clean --force Thirdly: npm install -g create-react-app@latest and create-react-app my-app again.

Setting std=c99 flag in GCC

Instead of calling /usr/bin/gcc, use /usr/bin/c99. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc after having added the -std=c99 flag, which is precisely what you want.

How to loop through array in jQuery?


(Update: My other answer here lays out the non-jQuery options much more thoroughly. The third option below, jQuery.each, isn't in it though.)


Four options:

Generic loop:

var i;
for (i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

or in ES2015+:

for (let i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

Advantages: Straight-forward, no dependency on jQuery, easy to understand, no issues with preserving the meaning of this within the body of the loop, no unnecessary overhead of function calls (e.g., in theory faster, though in fact you'd have to have so many elements that the odds are you'd have other problems; details).

ES5's forEach:

As of ECMAScript5, arrays have a forEach function on them which makes it easy to loop through the array:

substr.forEach(function(item) {
    // do something with `item`
});

Link to docs

(Note: There are lots of other functions, not just forEach; see the answer referenced above for details.)

Advantages: Declarative, can use a prebuilt function for the iterator if you have one handy, if your loop body is complex the scoping of a function call is sometimes useful, no need for an i variable in your containing scope.

Disadvantages: If you're using this in the containing code and you want to use this within your forEach callback, you have to either A) Stick it in a variable so you can use it within the function, B) Pass it as a second argument to forEach so forEach sets it as this during the callback, or C) Use an ES2015+ arrow function, which closes over this. If you don't do one of those things, in the callback this will be undefined (in strict mode) or the global object (window) in loose mode. There used to be a second disadvantage that forEach wasn't universally supported, but here in 2018, the only browser you're going to run into that doesn't have forEach is IE8 (and it can't be properly polyfilled there, either).

ES2015+'s for-of:

for (const s of substr) { // Or `let` if you want to modify it in the loop body
    // do something with `s`
}

See the answer linked at the top of this answer for details on how that works.

Advantages: Simple, straightforward, offers a contained-scope variable (or constant, in the above) for the entry from the array.

Disadvantages: Not supported in any version of IE.

jQuery.each:

jQuery.each(substr, function(index, item) {
    // do something with `item` (or `this` is also `item` if you like)
});

(Link to docs)

Advantages: All of the same advantages as forEach, plus you know it's there since you're using jQuery.

Disadvantages: If you're using this in the containing code, you have to stick it in a variable so you can use it within the function, since this means something else within the function.

You can avoid the this thing though, by either using $.proxy:

jQuery.each(substr, $.proxy(function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}, this));

...or Function#bind:

jQuery.each(substr, function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}.bind(this));

...or in ES2015 ("ES6"), an arrow function:

jQuery.each(substr, (index, item) => {
    // do something with `item` (`this` is the same as it was outside)
});

What NOT to do:

Don't use for..in for this (or if you do, do it with proper safeguards). You'll see people saying to (in fact, briefly there was an answer here saying that), but for..in does not do what many people think it does (it does something even more useful!). Specifically, for..in loops through the enumerable property names of an object (not the indexes of an array). Since arrays are objects, and their only enumerable properties by default are the indexes, it mostly seems to sort of work in a bland deployment. But it's not a safe assumption that you can just use it for that. Here's an exploration: http://jsbin.com/exohi/3

I should soften the "don't" above. If you're dealing with sparse arrays (e.g., the array has 15 elements in total but their indexes are strewn across the range 0 to 150,000 for some reason, and so the length is 150,001), and if you use appropriate safeguards like hasOwnProperty and checking the property name is really numeric (see link above), for..in can be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated.

Creating executable files in Linux

No need to hack your editor, or switch editors.

Instead we can come up with a script to watch your development directories and chmod files as they're created. This is what I've done in the attached bash script. You probably want to read through the comments and edit the 'config' section as fits your needs, then I would suggest putting it in your $HOME/bin/ directory and adding its execution to your $HOME/.login or similar file. Or you can just run it from the terminal.

This script does require inotifywait, which comes in the inotify-tools package on Ubuntu,

sudo apt-get install inotify-tools

Suggestions/edits/improvements are welcome.

#!/usr/bin/env bash

# --- usage --- #
# Depends: 'inotifywait' available in inotify-tools on Ubuntu
# 
# Edit the 'config' section below to reflect your working directory, WORK_DIR,
# and your watched directories, WATCH_DIR. Each directory in WATCH_DIR will
# be logged by inotify and this script will 'chmod +x' any new files created
# therein. If SUBDIRS is 'TRUE' this script will watch WATCH_DIRS recursively.
# I recommend adding this script to your $HOME/.login or similar to have it
# run whenever you log into a shell, eg 'echo "watchdirs.sh &" >> ~/.login'.
# This script will only allow one instance of itself to run at a time.

# --- config --- #

WORK_DIR="$HOME/path/to/devel" # top working directory (for cleanliness?)
WATCH_DIRS=" \
    $WORK_DIR/dirA \
    $WORK_DIR/dirC \
    "                          # list of directories to watch
SUBDIRS="TRUE"                 # watch subdirectories too
NOTIFY_ARGS="-e create -q"     # watch for create events, non-verbose


# --- script starts here --- #
# probably don't need to edit beyond this point

# kill all previous instances of myself
SCRIPT="bash.*`basename $0`"
MATCHES=`ps ax | egrep $SCRIPT | grep -v grep | awk '{print $1}' | grep -v $$`
kill $MATCHES >& /dev/null

# set recursive notifications (for subdirectories)
if [ "$SUBDIRS" = "TRUE" ] ; then
    RECURSE="-r"
else
    RECURSE=""
fi

while true ; do
    # grab an event
    EVENT=`inotifywait $RECURSE $NOTIFY_ARGS $WATCH_DIRS`

    # parse the event into DIR, TAGS, FILE
    OLDIFS=$IFS ; IFS=" " ; set -- $EVENT
    E_DIR=$1
    E_TAGS=$2
    E_FILE=$3
    IFS=$OLDIFS

    # skip if it's not a file event or already executable (unlikely)
    if [ ! -f "$E_DIR$E_FILE" ] || [ -x "$E_DIR$E_FILE" ] ; then
        continue
    fi

    # set file executable
    chmod +x $E_DIR$E_FILE
done

Show hide div using codebehind

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner:

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

Then to show again:

myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

... and to show:

myDiv.show();

Objective-C and Swift URL encoding

NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                             NULL,
                             (CFStringRef)yourString, 
                             NULL, 
                             CFSTR("/:"), 
                             kCFStringEncodingUTF8);

You will need to release or autorelease str yourself.

How to auto-indent code in the Atom editor?

I prefer using atom-beautify, CTRL+ALT+B (in linux, may be in windows also) handles better al kind of formats and it is also customizable per file format.

more details here: https://atom.io/packages/atom-beautify

Convert xlsx to csv in Linux with command line

In bash, I used this libreoffice command to convert all my xlsx files in the current directory:

for i   in *.xlsx; do  libreoffice --headless --convert-to csv "$i" ; done

It takes care of spaces in the filename.

Tried again some years later, and it didn't work. This thread gives some tips, but the quickiest solution was to run as root (or running a sudo libreoffice). Not elegant, but quick.

Use the command scalc.exe in Windows

C# Dictionary get item by index

you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

CSS get height of screen resolution

To get the screen resolution use should use Javascript instead of CSS: Use screen.height for height and screen.width for width.

Creating java date object from year,month,day

Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use

c.set(year, month - 1, day, 0, 0);  

How do I join two lines in vi?

In vi, J (that's Shift + J) or :join should do what you want, for the most part. Note that they adjust whitespace. In particular, you'll end up with a space between the two joined lines in many cases, and if the second line is indented that indentation will be removed prior to joining.

In Vim you can also use gJ (G, then Shift + J) or :join!. These will join lines without doing any whitespace adjustments.

In Vim, see :help J for more information.

Passing string parameter in JavaScript function

Change your code to

document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")

Convert datetime to Unix timestamp and convert it back in python

You've missed the time zone info (already answered, agreed)

arrow package allows to avoid this torture with datetimes; It is already written, tested, pypi-published, cross-python (2.6 — 3.xx).

All you need: pip install arrow (or add to dependencies)

Solution for your case

dt = datetime(2013,9,1,11)
arrow.get(dt).timestamp
# >>> 1378033200

bc = arrow.get(1378033200).datetime
print(bc)
# >>> datetime.datetime(2013, 9, 1, 11, 0, tzinfo=tzutc())
print(bc.isoformat())
# >>> '2013-09-01T11:00:00+00:00'

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

'ls' is not recognized as an internal or external command, operable program or batch file

We can use ls and many other Linux commands in Windows cmd. Just follow these steps.

Steps:

1) Install Git in your computer - https://git-scm.com/downloads.

2) After installing Git, go to the folder in which Git is installed. Mostly it will be in C drive and then Program Files Folder.

3) In Program Files folder, you will find the folder named Git, find the bin folder which is inside usr folder in the Git folder.

In my case, the location for bin folder was - C:\Program Files\Git\usr\bin

4) Add this location (C:\Program Files\Git\usr\bin) in path variable, in system environment variables.

5) You are done. Restart cmd and try to run ls and other Linux commands.

Adding Python Path on Windows 7

You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)

You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%.

Why use armeabi-v7a code over armeabi code?

EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.

armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.

armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.

Regular expression for matching HH:MM time format

You can use following regex :

^[0-2]?[0-3]:[0-5][0-9]$

Only modification I have made is leftmost digit is optional. Rest of the regex is same.

1030 Got error 28 from storage engine

I had the same issue in AWS RDS. It was due to the Freeable Space (Hard Drive Storage Space) was Full. You need to increase your space, or remove some data.

How do you express binary literals in Python?

For reference—future Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B:

>>> 0b101111
47

You can also use the new bin function to get the binary representation of a number:

>>> bin(173)
'0b10101101'

Development version of the documentation: What's New in Python 2.6

Check string length in PHP

$message is propably not a string at all, but an array. Use $message[0] to access the first element.

jQuery get the id/value of <li> element after click function

If You Have Multiple li elements inside an li element then this will definitely help you, and i have checked it and it works....

<script>
$("li").on('click', function() {
          alert(this.id);
          return false;
      });
</script>

Using --add-host or extra_hosts with docker-compose

This is in the feature backlog for Compose but it doesn't look like work has been started yet. Github issue.

Is __init__.py not required for packages in Python 3.3+

Based on my experience, even with python 3.3+, an empty __init__.py is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo, it didn't work until I created an empty __init__.py under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.

Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py in your package folder.

Function ereg_replace() is deprecated - How to clear this bug?

Switch to preg_replaceDocs and update the expression to use preg syntax (PCRE) instead of ereg syntax (POSIX) where there are differencesDocs (just as it says to do in the manual for ereg_replaceDocs).

Postgres FOR LOOP

Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.

Example with plpgsql:

DO
$do$
BEGIN 
   FOR i IN 1..25 LOOP
      INSERT INTO playtime.meta_random_sample
         (col_i, col_id)                       -- declare target columns!
      SELECT  i,     id
      FROM   tbl
      ORDER  BY random()
      LIMIT  15000;
   END LOOP;
END
$do$;

For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:

INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM   generate_series(1,25) i
CROSS  JOIN LATERAL (
   SELECT i, id
   FROM   tbl
   ORDER  BY random()
   LIMIT  15000
   ) t;

About generate_series():

About optimizing performance of random selections:

How to fill 100% of remaining height?

I know this is an old question, but nowadays there is a super easy form to do that, which is CCS Grid, so let me put the divs as example:

<div id="full">
  <div id="header">Contents of 1</div>
  <div id="someid">Contents of 2</div>
</div>

then the CSS code:

.full{
  width:/*the width you need*/;
  height:/*the height you need*/;
  display:grid;
  grid-template-rows: minmax(100px,auto) 1fr;
 }

And that's it, the second row, scilicet, the someide, will take the rest of the height because of the property 1fr, and the first div will have a min of 100px and a max of whatever it requires.

I must say CSS has advanced a lot to make easier programmers lives.

Recover SVN password from local cache

In ~/.subversion/auth/svn.simple/ you should find a file with a long hexadecimal name. The password is in there in plaintext.

If there is more than one file you'll need to find that one that references the server you need the password for.

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

If you want to delete a user with sql, you need to delete the related data in these tables: columns_priv, db, procs_priv, tables_priv. Then execute flush privileges;

jQuery validation plugin: accept only alphabetical characters?

 $('.AlphabetsOnly').keypress(function (e) {
        var regex = new RegExp(/^[a-zA-Z\s]+$/);
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            return false;
        }
    });

SQL WHERE condition is not equal to?

I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:

 AND (isdelete is NULL or isdelete = 0)

All shards failed

first thing first, all shards failed exception is not as dramatic as it sounds, it means shards were failed while serving a request(query or index), and there could be multiple reasons for it like

  1. Shards are actually in non-recoverable state, if your cluster and index state are in Yellow and RED, then it is one of the reason.
  2. Due to some shard recovery happening in background, shards didn't respond.
  3. Due to bad syntax of your query, ES responds in all shards failed.

In order to fix the issue, you need to filter it in one of the above category and based on that appropriate fix is required.

The one mentioned in the question, is clearly in the first bucket as cluster health is RED, means one or more primary shards are missing, and my this SO answer will help you fix RED cluster issue, which will fix the all shards exception in this case.

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \
  https://example.com/

jQuery - find table row containing table cell containing specific text

You can use filter() to do that:

var tableRow = $("td").filter(function() {
    return $(this).text() == "foo";
}).closest("tr");

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

When you're working with strings in PHP you'll need to pay special attention to the formation, using " or '

$string = 'Hello, world!';
$string = "Hello, world!";

Both of these are valid, the following is not:

$string = "Hello, world';

You must also note that ' inside of a literal started with " will not end the string, and vice versa. So when you have a string which contains ', it is generally best practice to use double quotation marks.

$string = "It's ok here";

Escaping the string is also an option

$string = 'It\'s ok here too';

More information on this can be found within the documentation

Effectively use async/await with ASP.NET Web API

You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()

The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries() does it's work.

If you can implement ReturnAllCountries() to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries() is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

SQL: how to use UNION and order by a specific select?

SELECT id, 1 AS sort_order
  FROM b
UNION
SELECT id, 2 AS sort_order
  FROM a
MINUS
SELECT id, 2 AS sort_order
  FROM b
ORDER BY 2;

favicon not working in IE

May be this help others.

For me ICON was not getting displayed in IE, even after following all steps.

Finally I found a note in MSDN Troubleshooting Shortcut Icons.

Verify that Internet Explorer can store the shortcut icon in the Temporary Internet Files folder. If you have set Internet Explorer to not keep a cache, then it will not be able to store the icon and will display the default Internet Explorer shortcut icon instead.

I was using IE in "In Private" mode, once I verified in normal mode.... Fav Icon displayed properly.

read.csv warning 'EOF within quoted string' prevents complete reading of file

I had the similar problem: EOF -warning and only part of data was loading with read.csv(). I tried the quotes="", but it only removed the EOF -warning.

But looking at the first row that was not loading, I found that there was a special character, an arrow ? (hexadecimal value 0x1A) in one of the cells. After deleting the arrow I got the data to load normally.

How to remove the arrows from input[type="number"] in Opera

I've been using some simple CSS and it seems to remove them and work fine.

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    appearance: none;_x000D_
    margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

This tutorial from CSS Tricks explains in detail & also shows how to style them

Android java.lang.NoClassDefFoundError

Try going to Project -> Properties -> Java Build Path -> Order & Export And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.

Import Android volley to Android Studio

step 1:- Download volley.jar file.

step 2:- Go to your project and set the display menu from Android to Project then go to

app -> libs-> paste your volley.jar file here

step 3:- Right click on the volley.jar file and click on "add as library". and its all done.

equivalent to push() or pop() for arrays?

For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:

array = push(array, item);

The drawbacks are that

  • the whole array has to be copied each time you push, and
  • the original array Object is not changed, so you have to update the variable(s) as appropriate.

Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    for (int i = 0; i < array.length; i++)
        longer[i] = array[i];
    longer[array.length] = push;
    return longer;
}

This alternative is more efficient, shorter & harder to read:

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    System.arraycopy(array, 0, longer, 0, array.length);
    longer[array.length] = push;
    return longer;
}

Easiest way to use SVG in Android?

Rather than adding libraries which increases your apk size, I will suggest you to convert Svg to drawable using http://inloop.github.io/svg2android/ . and add vectorDrawables.useSupportLibrary = true in gradle,

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You can use this tool to create appropriate c# classes:

http://jsonclassgenerator.codeplex.com/

and when you will have classes created you can simply convert string to object:

    public static T ParseJsonObject<T>(string json) where T : class, new()
    {
        JObject jobject = JObject.Parse(json);
        return JsonConvert.DeserializeObject<T>(jobject.ToString());
    }

Here that classes: http://ge.tt/2KGtbPT/v/0?c

Just fix namespaces.

Permission denied when launch python script via bash

You should be able to run the script typing:

$ chmod 755 ./scripts/replace-md5sums.py
$ ./scripts/replace-md5sums.py

There are times where the user you are currently logged with just don't have the permission to change file mode bits. In such cases if you have the root password you can change the file permission this way:

$ sudo chmod 755 ./scripts/replace-md5sums.py

Apache VirtualHost and localhost

localhost will always redirect to 127.0.0.1. You can trick this by naming your other VirtualHost to other local loop-back address, such as 127.0.0.2. Make sure you also change the corresponding hosts file to implement this.

For example, my httpd-vhosts.conf looks like this:

<VirtualHost 127.0.0.2:80>
    DocumentRoot "D:/6. App Data/XAMPP Shared/htdocs/intranet"
    ServerName intranet.dev
    ServerAlias www.intranet.dev
    ErrorLog "logs/intranet.dev-error.log"
    CustomLog "logs/intranet.dec-access.log" combined

    <Directory "D:/6. App Data/XAMPP Shared/htdocs/intranet">
        Options Indexes FollowSymLinks ExecCGI Includes
        Order allow,deny
        Allow from all
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

(Notice that in <VirtualHost> section I typed 127.0.0.2:80. It means that this block of VirtualHost will only affects requests to IP address 127.0.0.2 port 80, which is the default port for HTTP.

To route the name intranet.dev properly, my hosts entry line is like this:

127.0.0.2 intranet.dev

This way, it will prevent you from creating another VirtualHost block for localhost, which is unnecessary.

Why do people hate SQL cursors so much?

The "overhead" with cursors is merely part of the API. Cursors are how parts of the RDBMS work under the hood. Often CREATE TABLE and INSERT have SELECT statements, and the implementation is the obvious internal cursor implementation.

Using higher-level "set-based operators" bundles the cursor results into a single result set, meaning less API back-and-forth.

Cursors predate modern languages that provide first-class collections. Old C, COBOL, Fortran, etc., had to process rows one at a time because there was no notion of "collection" that could be used widely. Java, C#, Python, etc., have first-class list structures to contain result sets.

The Slow Issue

In some circles, the relational joins are a mystery, and folks will write nested cursors rather than a simple join. I've seen truly epic nested loop operations written out as lots and lots of cursors. Defeating an RDBMS optimization. And running really slowly.

Simple SQL rewrites to replace nested cursor loops with joins and a single, flat cursor loop can make programs run in 100th the time. [They thought I was the god of optimization. All I did was replace nested loops with joins. Still used cursors.]

This confusion often leads to an indictment of cursors. However, it isn't the cursor, it's the misuse of the cursor that's the problem.

The Size Issue

For really epic result sets (i.e., dumping a table to a file), cursors are essential. The set-based operations can't materialize really large result sets as a single collection in memory.

Alternatives

I try to use an ORM layer as much as possible. But that has two purposes. First, the cursors are managed by the ORM component. Second, the SQL is separated from the application into a configuration file. It's not that the cursors are bad. It's that coding all those opens, closes and fetches is not value-add programming.

LINQ Aggregate algorithm explained

Definition

Aggregate method is an extension method for generic collections. Aggregate method applies a function to each item of a collection. Not just only applies a function, but takes its result as initial value for the next iteration. So, as a result, we will get a computed value (min, max, avg, or other statistical value) from a collection.

Therefore, Aggregate method is a form of safe implementation of a recursive function.

Safe, because the recursion will iterate over each item of a collection and we can’t get any infinite loop suspension by wrong exit condition. Recursive, because the current function’s result is used as a parameter for the next function call.

Syntax:

collection.Aggregate(seed, func, resultSelector);
  • seed - initial value by default;
  • func - our recursive function. It can be a lambda-expression, a Func delegate or a function type T F(T result, T nextValue);
  • resultSelector - it can be a function like func or an expression to compute, transform, change, convert the final result.

How it works:

var nums = new[]{1, 2};
var result = nums.Aggregate(1, (result, n) => result + n); //result = (1 + 1) + 2 = 4
var result2 = nums.Aggregate(0, (result, n) => result + n, response => (decimal)response/2.0); //result2 = ((0 + 1) + 2)*1.0/2.0 = 3*1.0/2.0 = 3.0/2.0 = 1.5

Practical usage:

  1. Find Factorial from a number n:

int n = 7;
var numbers = Enumerable.Range(1, n);
var factorial = numbers.Aggregate((result, x) => result * x);

which is doing the same thing as this function:

public static int Factorial(int n)
{
   if (n < 1) return 1;

   return n * Factorial(n - 1);
}
  1. Aggregate() is one of the most powerful LINQ extension method, like Select() and Where(). We can use it to replace the Sum(), Min(). Max(), Avg() functionality, or to change it by implementing addition context:
    var numbers = new[]{3, 2, 6, 4, 9, 5, 7};
    var avg = numbers.Aggregate(0.0, (result, x) => result + x, response => (double)response/(double)numbers.Count());
    var min = numbers.Aggregate((result, x) => (result < x)? result: x);
  1. More complex usage of extension methods:
    var path = @“c:\path-to-folder”;

    string[] txtFiles = Directory.GetFiles(path).Where(f => f.EndsWith(“.txt”)).ToArray<string>();
    var output = txtFiles.Select(f => File.ReadAllText(f, Encoding.Default)).Aggregate<string>((result, content) => result + content);

    File.WriteAllText(path + “summary.txt”, output, Encoding.Default);

    Console.WriteLine(“Text files merged into: {0}”, output); //or other log info

Get index of array element faster than O(n)

Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).

You can use binary search (if your array is ordered and the values you store in the array are comparable in some way). For that to work you need to be able to tell the binary search whether it should be looking "to the left" or "to the right" of the current element. But I believe there is nothing wrong with storing the index at insertion time and then using it if you are getting the element from the same array.

Adding onClick event dynamically using jQuery

Or you can use an arrow function to define it:

$(document).ready(() => {
  $('#bfCaptchaEntry').click(()=>{
    
  });
});

For better browser support:

$(document).ready(function() {
  $('#bfCaptchaEntry').click(function (){
    
  });
});

cocoapods - 'pod install' takes forever

Try clearing your CocoaPods cache, re-download and re-install all pods as described here

rm -rf "${HOME}/Library/Caches/CocoaPods"

rm -rf "\`pwd\`/Pods/"

pod update

Create hyperlink to another sheet

Something like the following will loop through column A in the Control sheet and turn the values in the cells into Hyperlinks. Not something I've had to do before so please excuse bugs:

Sub CreateHyperlinks()

Dim mySheet As String
Dim myRange As Excel.Range
Dim cell As Excel.Range
Set myRange = Excel.ThisWorkbook.Sheets("Control").Range("A1:A5") '<<adjust range to suit

For Each cell In myRange
    Excel.ThisWorkbook.Sheets("Control").Hyperlinks.Add Anchor:=cell, Address:="", SubAddress:=cell.Value & "!A1" '<<from recorded macro
Next cell

End Sub

What is the difference between Cygwin and MinGW?

Cygwin is an attempt to create a complete UNIX/POSIX environment on Windows. To do this it uses various DLLs. While these DLLs are covered by GPLv3+, their license contains an exception that does not force a derived work to be covered by the GPLv3+. MinGW is a C/C++ compiler suite which allows you to create Windows executables without dependency on such DLLs - you only need the normal MSVC runtimes, which are part of any normal Microsoft Windows installation.

You can also get a small UNIX/POSIX like environment, compiled with MinGW called MSYS. It doesn't have anywhere near all the features of Cygwin, but is ideal for programmers wanting to use MinGW.

What is (x & 1) and (x >>= 1)?

x & 1 is equivalent to x % 2.

x >> 1 is equivalent to x / 2

So, these things are basically the result and remainder of divide by two.

Characters allowed in GET parameter

From RFC 1738 on which characters are allowed in URLs:

Only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

The reserved characters are ";", "/", "?", ":", "@", "=" and "&", which means you would need to URL encode them if you wish to use them.

What is the difference between screenX/Y, clientX/Y and pageX/Y?

I don't like and understand things, which can be explained visually, by words.

enter image description here

"unable to locate adb" using Android Studio

  1. on your android studio at the top right corner beside the search icon you can find the SDK Manager.
  2. view android SDK location (this will show you your sdk path)
  3. navigate to file explorer on your system, and locate the file path, this should be found something like Windows=> c://Users/johndoe/AppData/local/android (you can now see the sdk.) Mac=>/Users/johndoe/Library/Android/sdk
  4. check the platform tools folder and see if you would see anything like adb.exe (it should be missing probably because it was corrupted and your antivirus or windows defender has quarantined it)
  5. delete the platform tools folder
  6. go back to android studio and from where you left off navigate to sdk tools (this should be right under android sdk location)
  7. uncheck android sdk platform-tools and select ok. (this will uninstall the platform tools from your ide) wait till it is done and then your gradle will sync.
  8. after sync is complete, go back and check the box of android sdk platform-tools (this will install a fresh one with new adb.exe) wait till it is done and sync project and then you are good to go.

I hope this saves someone some hours of pain.

PySpark: withColumn() with two conditions and three outcomes

You'll want to use a udf as below

from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf

def func(fruit1, fruit2):
    if fruit1 == None or fruit2 == None:
        return 3
    if fruit1 == fruit2:
        return 1
    return 0

func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))

How to make a loop in x86 assembly language?

mov cx,3

loopstart:
   do stuff
   dec cx          ;Note:  decrementing cx and jumping on result is
   jnz loopstart   ;much faster on Intel (and possibly AMD as I haven't
                   ;tested in maybe 12 years) rather than using loop loopstart

How to delete history of last 10 commands in shell?

With Bash 5 you can now do a range...Hooray!:

history -d 511-520

or counting backwards 10:

history -d -10--1

Excerpt from Bash 5 Man Page:

'history'

Options, if supplied, have the following meanings:

'-d OFFSET' Delete the history entry at position OFFSET. If OFFSET is positive, it should be specified as it appears when the history is displayed. If OFFSET is negative, it is interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of '-1' refers to the current 'history -d' command.

'-d START-END' Delete the history entries between positions START and END, inclusive. Positive and negative values for START and END are interpreted as described above.

Here is my solution for Bash 4. It iteratively deletes a single entry or a range of history starting with lowest index.

delHistory () {
    count=$(( ${2:-$1} - $1 ))
    while [[ $count -ge 0 ]]; do
        history -d "$1"
        ((count--))
    done
}

delHistory 511 520

How to extract duration time from ffmpeg output?

For those who want to perform the same calculations with no additional software in Windows, here is the script for command line script:

set input=video.ts

ffmpeg -i "%input%" 2> output.tmp

rem search "  Duration: HH:MM:SS.mm, start: NNNN.NNNN, bitrate: xxxx kb/s"
for /F "tokens=1,2,3,4,5,6 delims=:., " %%i in (output.tmp) do (
    if "%%i"=="Duration" call :calcLength %%j %%k %%l %%m
)
goto :EOF

:calcLength
set /A s=%3
set /A s=s+%2*60
set /A s=s+%1*60*60
set /A VIDEO_LENGTH_S = s
set /A VIDEO_LENGTH_MS = s*1000 + %4
echo Video duration %1:%2:%3.%4 = %VIDEO_LENGTH_MS%ms = %VIDEO_LENGTH_S%s

Same answer posted here: How to crop last N seconds from a TS video

Insert into ... values ( SELECT ... FROM ... )

For Microsoft SQL Server, I will recommend learning to interpret the SYNTAX provided on MSDN. With Google it's easier than ever, to look for syntax.

For this particular case, try

Google: insert site:microsoft.com

The first result will be http://msdn.microsoft.com/en-us/library/ms174335.aspx

scroll down to the example ("Using the SELECT and EXECUTE options to insert data from other tables") if you find it difficult to interpret the syntax given at the top of the page.

[ WITH <common_table_expression> [ ,...n ] ]
INSERT 
{
        [ TOP ( expression ) [ PERCENT ] ] 
        [ INTO ] 
        { <object> | rowset_function_limited 
          [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
        }
    {
        [ ( column_list ) ] 
        [ <OUTPUT Clause> ]
        { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n     ] 
        | derived_table       <<<<------- Look here ------------------------
        | execute_statement   <<<<------- Look here ------------------------
        | <dml_table_source>  <<<<------- Look here ------------------------
        | DEFAULT VALUES 
        }
    }
}
[;]

This should be applicable for any other RDBMS available there. There is no point in remembering all the syntax for all products IMO.

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is not restricted to Tomcat’s Java process, but passed to all JVM processes running on the same machine.

Use CATALINA_OPTS if you specifically want to pass JVM arguments to Tomcat's servlet engine.

How do I get a list of all subdomains of a domain?

robotex tools which are free will let you do this but they make you enter the ip of the domain first:

  1. find out the ip (there's a good ff plugin which does this but I can't post the link cos this is my first post here!)
  2. do an ip search on robotex: http://www.robtex.com/ip/
  3. in the results page that follows click on the domain you're interested in>
  4. you are taken to a page that lists all subdomains + a load of other information such as mail server info

What is the use of the @ symbol in PHP?

Like already some answered before: The @ operator suppresses all errors in PHP, including notices, warnings and even critical errors.

BUT: Please, really do not use the @ operator at all.

Why?

Well, because when you use the @ operator for error supression, you have no clue at all where to start when an error occurs. I already had some "fun" with legacy code where some developers used the @ operator quite often. Especially in cases like file operations, network calls, etc. Those are all cases where lots of developers recommend the usage of the @ operator as this sometimes is out of scope when an error occurs here (for example a 3rdparty API could be unreachable, etc.).

But what's the point to still not use it? Let's have a look from two perspectives:

As a developer: When @ is used, I have absolutely no idea where to start. If there are hundreds or even thousands of function calls with @ the error could be like everyhwere. No reasonable debugging possible in this case. And even if it is just a 3rdparty error - then it's just fine and you're done fast. ;-) Moreover, it's better to add enough details to the error log, so developers are able to decide easily if a log entry is something that must be checked further or if it's just a 3rdparty failure that is out of the developer's scope.

As a user: Users don't care at all what the reason for an error is or not. Software is there for them to work, to finish a specific task, etc. They don't care if it's the developer's fault or a 3rdparty problem. Especially for the users, I strongly recommend to log all errors, even if they're out of scope. Maybe you'll notice that a specific API is offline frequently. What can you do? You can talk to your API partner and if they're not able to keep it stable, you should probably look for another partner.

In short: You should know that there exists something like @ (knowledge is always good), but just do not use it. Many developers (especially those debugging code from others) will be very thankful.

How do I create delegates in Objective-C?

In my point of view create separate class for that delegate method and you can use where you want.

in my Custom DropDownClass.h

typedef enum
{
 DDSTATE,
 DDCITY
}DropDownType;

@protocol DropDownListDelegate <NSObject>
@required
- (void)dropDownDidSelectItemWithString:(NSString*)itemString     DropDownType:(DropDownType)dropDownType;
@end
@interface DropDownViewController : UIViewController
{
 BOOL isFiltered;
}
@property (nonatomic, assign) DropDownType dropDownType;
@property (weak) id <DropDownListDelegate> delegate;
@property (strong, nonatomic) NSMutableArray *array1DropDown;
@property (strong, nonatomic) NSMutableArray *array2DropDown;

after that in.m file create array with objects,

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat rowHeight = 44.0f;
return rowHeight;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return isFiltered?[self.array1DropDown count]:[self.array2DropDown count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

if (self.delegate) {
    if (self.dropDownType == DDCITY) {
        cell.textLabel.text = [self.array1DropDown objectAtIndex:indexPath.row];
    }
    else if (self.dropDownType == DDSTATE) {
        cell.textLabel.text = [self.array2DropDown objectAtIndex:indexPath.row];
    }
}
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [self dismissViewControllerAnimated:YES completion:^{
    if(self.delegate){
        if(self.dropDownType == DDCITY){
            [self.delegate dropDownDidSelectItemWithString:[self.array1DropDown objectAtIndex:indexPath.row] DropDownType:self.dropDownType];
        }
        else if (self.dropDownType == DDSTATE) {
            [self.delegate dropDownDidSelectItemWithString:[self.array2DropDown objectAtIndex:indexPath.row] DropDownType:self.dropDownType];
        }
    }
}];
}

Here all are set for Custom delegate class.after that you can use this delegate method where you want.for example...

in my another viewcontroller import after that

create action for calling delegate method like this

- (IBAction)dropDownBtn1Action:(id)sender {
DropDownViewController *vehicleModelDropView = [[DropDownViewController alloc]init];
vehicleModelDropView.dropDownType = DDCITY;
vehicleModelDropView.delegate = self;
[self presentViewController:vehicleModelDropView animated:YES completion:nil];
}

after that call delegate method like this

- (void)dropDownDidSelectItemWithString:(NSString *)itemString DropDownType:(DropDownType)dropDownType {
switch (dropDownType) {
    case DDCITY:{
        if(itemString.length > 0){
            //Here i am printing the selected row
            [self.dropDownBtn1 setTitle:itemString forState:UIControlStateNormal];
        }
    }
        break;
    case DDSTATE: {
        //Here i am printing the selected row
        [self.dropDownBtn2 setTitle:itemString forState:UIControlStateNormal];
    }

    default:
        break;
}
}

How to temporarily exit Vim and go back

You can also do that by :sus to fall into shell and back by fg.

How to set focus on an input field after rendering?

<input type="text" autoFocus />

always try the simple and basic solution first, works for me.

JavaScript for handling Tab Key press

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

What is mapDispatchToProps?

It's basically a shorthand. So instead of having to write:

this.props.dispatch(toggleTodo(id));

You would use mapDispatchToProps as shown in your example code, and then elsewhere write:

this.props.onTodoClick(id);

or more likely in this case, you'd have that as the event handler:

<MyComponent onClick={this.props.onTodoClick} />

There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

Lucene is nice and all, but their stop word set is awful. I had to manually add a ton of stop words to StopAnalyzer.ENGLISH_STOP_WORDS_SET just to get it anywhere near usable.

I haven't used Sphinx but I know people swear by its speed and near-magical "ease of setup to awesomeness" ratio.

release Selenium chromedriver.exe from memory

I am using Protractor with directConnect. Disabling the "--no-sandbox" option fixed the issue for me.

// Capabilities to be passed to the webdriver instance.
capabilities: {
  'directConnect': true,
  'browserName': 'chrome',
  chromeOptions: {
      args: [
        //"--headless",
        //"--hide-scrollbars",
        "--disable-software-rasterizer",
        '--disable-dev-shm-usage',
        //"--no-sandbox",
        "incognito",
        "--disable-gpu",
        "--window-size=1920x1080"]
  }
},

How to add an extra language input to Android?

I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.

How do I get a value of a <span> using jQuery?

VERY IMPORTANT Additional info on difference between .text() and .html():

If your selector selects more than one item, e.g you have two spans like so <span class="foo">bar1</span> <span class="foo">bar2</span> ,

then

$('.foo').text(); appends the two texts and give you that; whereas

$('.foo').html(); gives you only one of those.

Initialising a multidimensional array in Java

Java doesn't have "true" multidimensional arrays.

For example, arr[i][j][k] is equivalent to ((arr[i])[j])[k]. In other words, arr is simply an array, of arrays, of arrays.

So, if you know how arrays work, you know how multidimensional arrays work!


Declaration:

int[][][] threeDimArr = new int[4][5][6];

or, with initialization:

int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

Access:

int x = threeDimArr[1][0][1];

or

int[][] row = threeDimArr[1];

String representation:

Arrays.deepToString(threeDimArr);

yields

"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"

Useful articles

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

How to use clock() in C++

you can measure how long your program works. The following functions help measure the CPU time since the start of the program:

  • C++ (double)clock() / CLOCKS PER SEC with ctime included.
  • python time.clock() returns floating-point value in seconds.
  • Java System.nanoTime() returns long value in nanoseconds.

my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics

so you can add this line of code after your algorithm

cout << (double)clock() / CLOCKS_PER_SEC ;

Expected Output: the output representing the number of clock ticks per second

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is non-standard and only supported by Internet Explorer on Windows.

There is no native cross browser way to write to the file system without using plugins, even the draft File API gives read only access.

If you want to work cross platform, then you need to look at such things as signed Java applets (keeping in mind that that will only work on platforms for which the Java runtime is available).

How to create many labels and textboxes dynamically depending on the value of an integer variable?

I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.

Simple way to do it would be:

int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
    TextBox[] textBoxes = new TextBox[n];
    Label[] labels = new Label[n];

    for (int i = 0; i < n; i++)
    {
        textBoxes[i] = new TextBox();
        // Here you can modify the value of the textbox which is at textBoxes[i]

        labels[i] = new Label();
        // Here you can modify the value of the label which is at labels[i]
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(textBoxes[i]);
        this.Controls.Add(labels[i]);
    }
}

The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.

To do it using a User Control simply do this.

Okay, first of all go and create a new user control and put a text box and label in it.

Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:

public string GetTextBoxValue() 
{ 
    return this.txtSomeTextBox.Text; 
} 

public string GetLabelValue() 
{ 
    return this.lblSomeLabel.Text; 
} 

public void SetTextBoxValue(string newText) 
{ 
    this.txtSomeTextBox.Text = newText; 
} 

public void SetLabelValue(string newText) 
{ 
    this.lblSomeLabel.Text = newText; 
}

Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):

private void btnDisplay_Click(object sender, EventArgs e)
{
    MyUserControl[] controls = new MyUserControl[n];

    for (int i = 0; i < n; i++)
    {
        controls[i] = new MyUserControl();

        controls[i].setTextBoxValue("some value to display in text");
        controls[i].setLabelValue("some value to display in label");
        // Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(controls[i]);
    }
}

Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:

public TextBox myTextBox;
public Label myLabel;

In the constructor of the user control do this:

myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;

Then in your program if you want to modify the text value of either just do this.

control[i].myTextBox.Text = "some random text"; // Same applies to myLabel

Hope it helped :)

Dump all tables in CSV format using 'mysqldump'

This command will create two files in /path/to/directory table_name.sql and table_name.txt.

The SQL file will contain the table creation schema and the txt file will contain the records of the mytable table with fields delimited by a comma.

mysqldump -u username -p -t  -T/path/to/directory dbname table_name --fields-terminated-by=','

Parsing a JSON array using Json.Net

Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage

And you can convert the entire object to a string, filename.json is expected to be located in documents folder.

        var text = File.ReadAllText("filename.json");
        var json = JsonValue.Parse(text);

        while (JsonValue.Null != null)
        {
            Console.WriteLine(json.ToString());

        }
        Console.ReadLine();

How to add external fonts to android application

One more point in addition to the above answers. When using a font inside a fragment, the typeface instantiation should be done in the onAttach method ( override ) as given below:

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}

Reason:
There is a short span of time before a fragment is attached to an activity. If CreateFromAsset method is called before attaching fragment to an activity an error occurs.

How many files can I put in a directory?

It absolutely depends on the filesystem. Many modern filesystems use decent data structures to store the contents of directories, but older filesystems often just added the entries to a list, so retrieving a file was an O(n) operation.

Even if the filesystem does it right, it's still absolutely possible for programs that list directory contents to mess up and do an O(n^2) sort, so to be on the safe side, I'd always limit the number of files per directory to no more than 500.

how to sync windows time from a ntp time server in command

Use net time net time \\timesrv /set /yes

after your comment try this one in evelated prompt :

w32tm /config /update /manualpeerlist:yourtimerserver

Get the Last Inserted Id Using Laravel Eloquent

You can do this:

$result=app('db')->insert("INSERT INTO table...");

$lastInsertId=app('db')->getPdo()->lastInsertId();

How to add/subtract dates with JavaScript?

startdate.setDate(startdate.getDate() - daysToSubtract);


startdate.setDate(startdate.getDate() + daysToAdd);

Portable way to get file size (in bytes) in shell?

You first Perl example doesn't look unreasonable to me.

It's for reasons like this that I migrated from writing shell scripts (in bash/sh etc.) to writing all but the most trivial scripts in Perl. I found that I was having to launch Perl for particular requirements, and as I did that more and more, I realised that writing the scripts in Perl was probably a more powerful (in terms of the language and the wide array of libraries available via CPAN) and more efficient way to achieve what I wanted.

Note that other shell-scripting languages (e.g. python/ruby) will no doubt have similar facilities, and you may want to evaluate these for your purposes. I only discuss Perl since that's the language I use and am familiar with.

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Clear variable in python

I used a few options mentioned above :

del self.left

or setting value to None using

self.left = None

It's important to know the differences and put a few exception handlers in place when you use set the value to None. If you're printing the value of the conditional statements using a template, say,

print("The value of the variable is {}".format(self.left))

you might see the value of the variable printing "The value of the variable is None". Thus, you'd have to put a few exception handlers there :

if self.left:
    #Then only print stuff

The above command will only print values if self.left is not None

Non-invocable member cannot be used like a method?

I had the same issue and realized that removing the parentheses worked. Sometimes having someone else read your code can be useful if you have been the only one working on it for some time.

E.g.

  cmd.CommandType = CommandType.Text(); 

Replace: cmd.CommandType = CommandType.Text;

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

ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.

For this error you can also define a version range:

yarn add typescript@">=3.4.0 <3.6.0" --save-dev --save-exact

or for npm

npm install typescript@">=3.4.0 <3.6.0" --save-dev --save-exact

After installing the correct typescript version:

  1. Delete node_modules folder
  2. Run yarn install or npm install
  3. Compile and cross your fingers xD

How to extract epoch from LocalDate and LocalDateTime?

'Millis since unix epoch' represents an instant, so you should use the Instant class:

private long toEpochMilli(LocalDateTime localDateTime)
{
  return localDateTime.atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();
}

Get single listView SelectedItem

I do this like that:

if (listView1.SelectedItems.Count > 0)
{
     var item = listView1.SelectedItems[0];
     //rest of your logic
}

What charset does Microsoft Excel use when saving files?

OOXML files like those that come from Excel 2007 are encoded in UTF-8, according to wikipedia. I don't know about CSV files, but it stands to reason it would use the same format...

How to restore the dump into your running mongodb

mongodump: To dump all the records:

mongodump --db databasename

To limit the amount of data included in the database dump, you can specify --db and --collection as options to mongodump. For example:

mongodump --collection myCollection --db test

This operation creates a dump of the collection named myCollection from the database 'test' in a dump/ subdirectory of the current working directory. NOTE: mongodump overwrites output files if they exist in the backup data folder.


mongorestore: To restore all data to the original database:

1) mongorestore --verbose \path\dump

or restore to a new database:

2) mongorestore --db databasename --verbose \path\dump\<dumpfolder>

Note: Both requires mongod instances.

jquery dialog save cancel button styling

In jQueryUI 1.8.9 using className rather than classes works.

$('#element').dialog({
  buttons:{
    "send":{
      text:'Send',
      className:'save'
    },
    "cancel":{
      text:'Cancel',
      className:'cancel'
    }
  });

Is there an easy way to convert jquery code to javascript?

This will get you 90% of the way there ; )

window.$ = document.querySelectorAll.bind(document)

For Ajax, the Fetch API is now supported on the current version of every major browser. For $.ready(), DOMContentLoaded has near universal support. You Might Not Need jQuery gives equivalent native methods for other common jQuery functions.

Zepto offers similar functionality but weighs in at 10K zipped. There are custom Ajax builds for jQuery and Zepto as well as some micro frameworks, but jQuery/Zepto have solid support and 10KB is only ~1 second on a 56K modem.

Force re-download of release dependency using Maven

I just deleted my ~/.m2/repository and that forced a re-download ;)

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

How to turn off gcc compiler optimization to enable buffer overflow

Urm, all of the answers so far have been wrong with Rook's answer being correct.

Entering:

echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

Followed by:

gcc -fno-stack-protector -z execstack -o bug bug.c

Disables ASLR, SSP/Propolice and Ubuntu's NoneXec (which was placed in 9.10, and fairly simple to work around see the mprotect(2) technique to map pages as executable and jmp) should help a little, however these "security features" are by no means infallible. Without the `-z execstack' flag, pages have non-executable stack markings.

How to convert a NumPy array to PIL image applying matplotlib colormap

The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:

import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')

np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.

Are HTTPS headers encrypted?

HTTP version 1.1 added a special HTTP method, CONNECT - intended to create the SSL tunnel, including the necessary protocol handshake and cryptographic setup.
The regular requests thereafter all get sent wrapped in the SSL tunnel, headers and body inclusive.

Git error: "Please make sure you have the correct access rights and the repository exists"

Very common mistake was done by me. I copied using clip command xclip -sel clip < ~/.ssh/id_rsa.pub, but during pasting into github key input box, I removed last newline using backspace, which actually changed the public key.

So, always copy & paste ssh public key as it is without removing last newline.

Can a foreign key be NULL and/or duplicate?

Short answer: Yes, it can be NULL or duplicate.

I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is.

Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK.

Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it.

Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK.

Pass Model To Controller using Jquery/Ajax

Looks like your IndexPartial action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost action method and use jQuery post to post data to that. GET has limitation on the query string value.

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

Your script should be

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

Assuming Name and Location are properties of your DashboardViewModel class and SomeDivToShowTheResult is the id of a div in your page where you want to load the content coming from the partialview.

Sending complex objects?

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

For the above js model to be transformed to your method parameter, Your View Model should be like this.

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

And in your action method, specify [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

Java executors: how to be notified, without blocking, when a task completes?

ThreadPoolExecutor also has beforeExecute and afterExecute hook methods that you can override and make use of. Here is the description from ThreadPoolExecutor's Javadocs.

Hook methods

This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.

How to suspend/resume a process in Windows?

Without any external tool you can simply accomplish this on Windows 7 or 8, by opening up the Resource monitor and on the CPU or Overview tab right clicking on the process and selecting Suspend Process. The Resource monitor can be started from the Performance tab of the Task manager.

batch file Copy files with certain extensions from multiple directories into one directory

Just use the XCOPY command with recursive option

xcopy c:\*.doc k:\mybackup /sy

/s will make it "recursive"

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

Incrementing a date in JavaScript

Getting the next 5 days:

var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();


for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}

R - Markdown avoiding package loading messages

You can use include=FALSE to exclude everything in a chunk.

```{r include=FALSE}
source("C:/Rscripts/source.R")
```

If you only want to suppress messages, use message=FALSE instead:

```{r message=FALSE}
source("C:/Rscripts/source.R")
```

Enforcing the type of the indexed members of a Typescript object?

@Ryan Cavanaugh's answer is totally ok and still valid. Still it worth to add that as of Fall'16 when we can claim that ES6 is supported by the majority of platforms it almost always better to stick to Map whenever you need associate some data with some key.

When we write let a: { [s: string]: string; } we need to remember that after typescript compiled there's not such thing like type data, it's only used for compiling. And { [s: string]: string; } will compile to just {}.

That said, even if you'll write something like:

class TrickyKey  {}

let dict: {[key:TrickyKey]: string} = {}

This just won't compile (even for target es6, you'll get error TS1023: An index signature parameter type must be 'string' or 'number'.

So practically you are limited with string or number as potential key so there's not that much of a sense of enforcing type check here, especially keeping in mind that when js tries to access key by number it converts it to string.

So it is quite safe to assume that best practice is to use Map even if keys are string, so I'd stick with:

let staff: Map<string, string> = new Map();

std::enable_if to conditionally compile a member function

SFINAE only works if substitution in argument deduction of a template argument makes the construct ill-formed. There is no such substitution.

I thought of that too and tried to use std::is_same< T, int >::value and ! std::is_same< T, int >::value which gives the same result.

That's because when the class template is instantiated (which happens when you create an object of type Y<int> among other cases), it instantiates all its member declarations (not necessarily their definitions/bodies!). Among them are also its member templates. Note that T is known then, and !std::is_same< T, int >::value yields false. So it will create a class Y<int> which contains

class Y<int> {
    public:
        /* instantiated from
        template < typename = typename std::enable_if< 
          std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< true >::type >
        int foo();

        /* instantiated from

        template < typename = typename std::enable_if< 
          ! std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< false >::type >
        int foo();
};

The std::enable_if<false>::type accesses a non-existing type, so that declaration is ill-formed. And thus your program is invalid.

You need to make the member templates' enable_if depend on a parameter of the member template itself. Then the declarations are valid, because the whole type is still dependent. When you try to call one of them, argument deduction for their template arguments happen and SFINAE happens as expected. See this question and the corresponding answer on how to do that.

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Using jQuery to see if a div has a child with a certain class

You can use the find function:

if($('#popup').find('p.filled-text').length !== 0)
   // Do Stuff

Array.size() vs Array.length

.size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.

If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.

Convert a bitmap into a byte array

I believe you may simply do:

ImageConverter converter = new ImageConverter();
var bytes = (byte[])converter.ConvertTo(img, typeof(byte[]));

Remove "whitespace" between div element

use line-height: 0px;

WORKING DEMO

The CSS Code:

div{line-height:0;}

This will affect generically to all your Div's. If you want your existing parent div only to have no spacing, you can apply the same into it.

Finding sum of elements in Swift array

this is my approach about this. however I believe that the best solution is the answer from the user username tbd

var i = 0 
var sum = 0
let example = 0
for elements in multiples{
    i = i + 1
    sum = multiples[ (i- 1)]
    example = sum + example
}

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Iterate through string array in Java

You have to maintain the serial how many times you are accessing the array.Use like this

int lookUpTime=0;

    for(int i=lookUpTime;i<lookUpTime+2 && i<elements.length();i++)
     {
    // do something with elements[i]
    }

lookUpTime++;

Create ArrayList from array

Java 9

In Java 9, you can use List.of static factory method in order to create a List literal. Something like the following:

List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));

This would return an immutable list containing three elements. If you want a mutable list, pass that list to the ArrayList constructor:

new ArrayList<>(List.of(// elements vararg))

JEP 269: Convenience Factory Methods for Collections

JEP 269 provides some convenience factory methods for Java Collections API. These immutable static factory methods are built into the List, Set, and Map interfaces in Java 9 and later.

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

HTML5 and frameborder

style="border:none; scrolling:no; frameborder:0;  marginheight:0; marginwidth:0; "

How to unpack and pack pkg file?

In addition to what @abarnert said, I today had to find out that the default cpio utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the cpio read error: bad file format message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:

find ./Foo.app | cpio -o --format odc | gzip -c > Payload

Table column sizing

Updated 2018

Make sure your table includes the table class. This is because Bootstrap 4 tables are "opt-in" so the table class must be intentionally added to the table.

http://codeply.com/go/zJLXypKZxL

Bootstrap 3.x also had some CSS to reset the table cells so that they don't float..

table td[class*=col-], table th[class*=col-] {
    position: static;
    display: table-cell;
    float: none;
}

I don't know why this isn't is Bootstrap 4 alpha, but it may be added back in the final release. Adding this CSS will help all columns to use the widths set in the thead..

Bootstrap 4 Alpha 2 Demo


UPDATE (as of Bootstrap 4.0.0)

Now that Bootstrap 4 is flexbox, the table cells will not assume the correct width when adding col-*. A workaround is to use the d-inline-block class on the table cells to prevent the default display:flex of columns.

Another option in BS4 is to use the sizing utils classes for width...

<thead>
     <tr>
           <th class="w-25">25</th>
           <th class="w-50">50</th>
           <th class="w-25">25</th>
     </tr>
</thead>

Bootstrap 4 Alpha 6 Demo

Lastly, you could use d-flex on the table rows (tr), and the col-* grid classes on the columns (th,td)...

<table class="table table-bordered">
        <thead>
            <tr class="d-flex">
                <th class="col-3">25%</th>
                <th class="col-3">25%</th>
                <th class="col-6">50%</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-sm-3">..</td>
                <td class="col-sm-3">..</td>
                <td class="col-sm-6">..</td>
            </tr>
        </tbody>
    </table>

Bootstrap 4.0.0 (stable) Demo

Note: Changing the TR to display:flex can alter the borders

How can I convert a dictionary into a list of tuples?

What you want is dict's items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can't be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

Git error on git pull (unable to update local ref)

This happened to me on OSX where I use a case insensitive file system. Somehow another developer pushed a branch with the same name but different case: My-Branch vs my-branch.

I already had My-Branch checked out and got the error "unable to update local ref" when I did a pull probably because the file system thinks My-Branch == my-branch.

Since we use Github I could solve the problem by deleting one of the branches via Github's GUI.

How do I get a HttpServletRequest in my spring beans?

If FlexContext is not available:

Solution 1: inside method (>= Spring 2.0 required)

HttpServletRequest request = 
        ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();

Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

@Autowired
private HttpServletRequest request;

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

How to free memory in Java?

*"I personally rely on nulling variables as a placeholder for future proper deletion. For example, I take the time to nullify all elements of an array before actually deleting (making null) the array itself."

This is unnecessary. The way the Java GC works is it finds objects that have no reference to them, so if I have an Object x with a reference (=variable) a that points to it, the GC won't delete it, because there is a reference to that object:

a -> x

If you null a than this happens:

a -> null
     x

So now x doesn't have a reference pointing to it and will be deleted. The same thing happens when you set a to reference to a different object than x.

So if you have an array arr that references to objects x, y and z and a variable a that references to the array it looks like that:

a -> arr -> x
         -> y
         -> z

If you null a than this happens:

a -> null
     arr -> x
         -> y
         -> z

So the GC finds arr as having no reference set to it and deletes it, which gives you this structure:

a -> null
     x
     y
     z

Now the GC finds x, y and z and deletes them aswell. Nulling each reference in the array won't make anything better, it will just use up CPU time and space in the code (that said, it won't hurt further than that. The GC will still be able to perform the way it should).

How do you specify the Java compiler version in a pom.xml file?

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <fork>true</fork>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin> 

making matplotlib scatter plots from dataframes in Python's pandas

Try passing columns of the DataFrame directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100

In [5]: df
Out[5]: 
       col1      col2  col3
0 -1.000075 -0.759910   100
1  0.510382  0.972615   200
2  1.872067 -0.731010   500
3  0.131612  1.075142  1000
4  1.497820  0.237024  1700

Vary scatter point size based on another column

plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)

enter image description here

Vary scatter point color based on another column

colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)

enter image description here

Scatter plot with legend

However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter once for each point type.

cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300') 
plt.legend()

enter image description here

Update

From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull method: df[df.col3.isnull()]

To split a list of points into many types, take a look at numpy select, which is a vectorized if-then-else implementation and accepts an optional default value. For example:

df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
                         [0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
    subset = df[df.subset == label]
    plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()

enter image description here

How can I get the source code of a Python function?

I believe that variable names aren't stored in pyc/pyd/pyo files, so you can not retrieve the exact code lines if you don't have source files.

SQL Last 6 Months

For MS SQL Server, you can use:

where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)

What is the easiest way to parse an INI file in Java?

You could try JINIFile. Is a translation of the TIniFile from Delphi, but for java

https://github.com/SubZane/JIniFile

How do I capture the output of a script if it is being ran by the task scheduler?

With stderr (where most of the errors go to):

cmd /c yourscript.cmd > logall.txt 2>&1

Using Address Instead Of Longitude And Latitude With Google Maps API

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

Trying to get property of non-object in

<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>

or

$sidemenus = mysql_fetch_array($results);

then

<?php echo $sidemenu['mname']."<br />";?>

Detect if the app was launched/opened from a push notification

You can use:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

to handle the remote push notifications.

Check here the documentation

How to list all the files in android phone by using adb shell?

Open cmd type adb shell then press enter. Type ls to view files list.

How do I specify different layouts for portrait and landscape orientations?

Or use this:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:scrollbars="vertical" 
            android:layout_height="wrap_content" 
            android:layout_width="fill_parent">

  <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

     <!-- Add your UI elements inside the inner most linear layout -->

  </LinearLayout>
</ScrollView>

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.

How to grant remote access permissions to mysql server for user?

Those SQL grants the others are sharing do work. If you're still unable to access the database, it's possible that you just have a firewall restriction for the port. It depends on your server type (and any routers in between) as to how to open up the connection. Open TCP port 3306 inbound, and give it a similar access rule for external machines (all/subnet/single IP/etc.).

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

How to print pandas DataFrame without index

The line below would hide the index column of DataFrame when you print

df.style.hide_index()

Update: tested w Python 3.7

Using XPATH to search text containing &nbsp;

Search for &nbsp; or only nbsp - did you try this?