Programs & Examples On #Scopes

How to read connection string in .NET Core?

In 3.1 there is a section already defined for "ConnectionStrings"

System.Configuration.ConnnectionStringSettings

Define:

  "ConnectionStrings": {
    "ConnectionString": "..."
  }

Register:

public void ConfigureServices(IServiceCollection services)
{
     services.Configure<ConnectionStringSettings>(Configuration.GetSection("ConnectionStrings"));
}

Inject:

public class ObjectModelContext : DbContext, IObjectModelContext
{

     private readonly ConnectionStringSettings ConnectionStringSettings;

    ...

     public ObjectModelContext(DbContextOptions<ObjectModelContext> options, IOptions<ConnectionStringSettings> setting) : base(options)
    {
          ConnectionStringSettings = setting.Value;
    }

    ...
}

Use:

   public static void ConfigureContext(DbContextOptionsBuilder optionsBuilder, ConnectionStringSettings connectionStringSettings)
    {
        if (optionsBuilder.IsConfigured == false)
        {
            optionsBuilder.UseLazyLoadingProxies()
                          .UseSqlServer(connectionStringSettings.ConnectionString);
        }
    }

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

Adding to exebook's response, the mathematics usage of the keyword let also encapsulates well the scoping implications of let when used in Javascript/ES6. Specifically, just as the following ES6 code is not aware of the assignment in braces of toPrint when it prints out the value of 'Hello World',

let toPrint = 'Hello World.';
{
    let toPrint = 'Goodbye World.';
}
console.log(toPrint); // Prints 'Hello World'

let as used in formalized mathematics (especially the writing of proofs) indicates that the current instance of a variable exists only for the scope of that logical idea. In the following example, x immediately gains a new identity upon entering the new idea (usually these are concepts necessary to prove the main idea) and reverts immediately to the old x upon the conclusion of the sub-proof. Of course, just as in coding, this is considered somewhat confusing and so is usually avoided by choosing a different name for the other variable.

Let x be so and so...

  Proof stuff

 New Idea { Let x be something else ... prove something } Conclude New Idea

 Prove main idea with old x

Using an authorization header with Fetch in React Native

completed = (id) => {
    var details = {
        'id': id,

    };

    var formBody = [];
    for (var property in details) {
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch(markcompleted, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formBody
    })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson, 'res JSON');
            if (responseJson.status == "success") {
                console.log(this.state);
                alert("your todolist is completed!!");
            }
        })
        .catch((error) => {
            console.error(error);
        });
};

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

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

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

Java ElasticSearch None of the configured nodes are available

If you are using java Transport client 1.check 9300 is access able /open. 2.check the node and cluster name ,this should be the correct,you can check the node and cluster name by type ip:port in your browser. 3.Check the versions of your jar and Es installed version.

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>
</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
    <my-dir>
        <div class="ng-binding">hello</div>
    </my-dir>
</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'
    };
});

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

Sequelize, convert entity to plain object

For those coming across this question more recently, .values is deprecated as of Sequelize 3.0.0. Use .get() instead to get the plain javascript object. So the above code would change to:

var nodedata = node.get({ plain: true });

Sequelize docs here

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

Laravel Eloquent inner join with multiple conditions

This is not politically correct but works

   ->leftJoin("players as p","n.item_id", "=", DB::raw("p.id_player and n.type='player'"))

How to replace all strings to numbers contained in each string in Notepad++?

Find: value="([\d]+|[\d])"

Replace: \1

It will really return you

4
403
200
201
116
15

js:

a='value="4"\nvalue="403"\nvalue="200"\nvalue="201"\nvalue="116"\nvalue="15"';
a = a.replace(/value="([\d]+|[\d])"/g, '$1');
console.log(a);

What is the problem with shadowing names defined in outer scopes?

A good workaround in some cases may be to move the variables and code to another function:

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Faced the same issue and resolved by upgrading my Maven from 3.0.4 to 3.1.1. Please try with v3.1.1 or any higher version if available

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Accessing controller method means accessing a method on parent scope from directive controller/link/scope.

If the directive is sharing/inheriting the parent scope then it is quite straight forward to just invoke a parent scope method.

Little more work is required when you want to access parent scope method from Isolated directive scope.

There are few options (may be more than listed below) to invoke a parent scope method from isolated directives scope or watch parent scope variables (option#6 specially).

Note that I used link function in these examples but you can use a directive controller as well based on requirement.

Option#1. Through Object literal and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChanged({selectedItems:selectedItems})" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/rgKUsYGDo9O3tewL6xgr?p=preview

Option#2. Through Object literal and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged({selectedItems:scope.selectedItems});  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/BRvYm2SpSpBK9uxNIcTa?p=preview

Option#3. Through Function reference and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChanged()(selectedItems)" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems:'=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/Jo6FcYfVXCCg3vH42BIz?p=preview

Option#4. Through Function reference and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged()(scope.selectedItems);  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/BSqx2J1yCY86IJwAnQF1?p=preview

Option#5: Through ng-model and two way binding, you can update parent scope variables.. So, you may not require to invoke parent scope functions in some cases.

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter ng-model="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=ngModel'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/hNui3xgzdTnfcdzljihY?p=preview

Option#6: Through $watch and $watchCollection It is two way binding for items in all above examples, if items are modified in parent scope, items in directive would also reflect the changes.

If you want to watch other attributes or objects from parent scope, you can do that using $watch and $watchCollection as given below

html

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{user}}!</p>
  <p>directive is watching name and current item</p>
  <table>
    <tr>
      <td>Id:</td>
      <td>
        <input type="text" ng-model="id" />
      </td>
    </tr>
    <tr>
      <td>Name:</td>
      <td>
        <input type="text" ng-model="name" />
      </td>
    </tr>
    <tr>
      <td>Model:</td>
      <td>
        <input type="text" ng-model="model" />
      </td>
    </tr>
  </table>

  <button style="margin-left:50px" type="buttun" ng-click="addItem()">Add Item</button>

  <p>Directive Contents</p>
  <sd-items-filter ng-model="selectedItems" current-item="currentItem" name="{{name}}" selected-items-changed="selectedItemsChanged" items="items"></sd-items-filter>

  <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}}</p>
</body>

</html>

script app.js

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

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@',
      currentItem: '=',
      items: '=',
      selectedItems: '=ngModel'
    },
    template: '<select ng-model="selectedItems" multiple="multiple" style="height: 140px; width: 250px;"' +
      'ng-options="item.id as item.name group by item.model for item in items | orderBy:\'name\'">' +
      '<option>--</option> </select>',
    link: function(scope, element, attrs) {
      scope.$watchCollection('currentItem', function() {
        console.log(JSON.stringify(scope.currentItem));
      });
      scope.$watch('name', function() {
        console.log(JSON.stringify(scope.name));
      });
    }
  }
})

 app.controller('MainCtrl', function($scope) {
  $scope.user = 'World';

  $scope.addItem = function() {
    $scope.items.push({
      id: $scope.id,
      name: $scope.name,
      model: $scope.model
    });
    $scope.currentItem = {};
    $scope.currentItem.id = $scope.id;
    $scope.currentItem.name = $scope.name;
    $scope.currentItem.model = $scope.model;
  }

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
  }]
});

You can always refer AngularJs documentation for detailed explanations about directives.

Spring Bean Scopes

The Spring documentation describes the following standard scopes:

singleton: (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype: Scopes a single bean definition to any number of object instances.

request: Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session: Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Additional custom scopes can also be created and configured using a CustomScopeConfigurer. An example would be the flow scope added by Spring Webflow.

By the way, you argues that you always used prototype what I find strange. The standard scope is singleton and in the application I develop, I rarely need the prototype scope. You should maybe take a look at this.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

We tried everything listed so far and it still failed. The error also mentioned

(default-war) on project utilsJava: Error assembling WAR: webxml attribute is required

The solution that finally fixed it was adding this to POM:

<failOnMissingWebXml>false</failOnMissingWebXml>

As mentioned here Error assembling WAR - webxml attribute is required

Our POM now contains this:

<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>${project.artifactId}</warName>
<attachClasses>true</attachClasses>
</configuration>
</plugin>  

unable to remove file that really exists - fatal: pathspec ... did not match any files

I know this is not the OP's problem, but I ran into the same error with an entirely different basis, so I just wanted to drop it here in case anyone else has the same. This is Windows-specific, and I assume does not affect Linux users.

I had a LibreOffice doc file, call it final report.odt. I later changed its case to Final Report.odt. In Windows, this doesn't even count as a rename. final report.odt, Final Report.odt, FiNaL RePoRt.oDt are all the same. In Linux, these are all distinct.

When I eventually went to git rm "Final Report.odt" and got the "pathspec did not match any files" error. Only when I use the original casing at the time the file was added -- git rm "final report.odt" -- did it work.

Lesson learned: to change the case I should have instead done:

git mv "final report.odt" temp.odt
git mv temp.odt "Final Report.odt"

Again, that wasn't the problem for the OP here; and wouldn't affect a Linux user, as his posts shows he clearly is. I'm just including it for others who may have this problem in Windows git and stumble onto this question.

Use underscore inside Angular controllers

If you don't mind using lodash try out https://github.com/rockabox/ng-lodash it wraps lodash completely so it is the only dependency and you don't need to load any other script files such as lodash.

Lodash is completely off of the window scope and no "hoping" that it's been loaded prior to your module.

AngularJS is rendering <br> as text not as a newline

You can use \n to concatenate words and then apply this style to container div.

style="white-space: pre;"

More info can be found at https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

_x000D_
_x000D_
<p style="white-space: pre;">_x000D_
    This is normal text._x000D_
</p>_x000D_
<p style="white-space: pre;">_x000D_
    This _x000D_
  text _x000D_
  contains _x000D_
  new lines._x000D_
</p>
_x000D_
_x000D_
_x000D_

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

Accidentally committed .idea directory files into git

You can remove it from the repo and commit the change.

git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"

After that, you can push it to the remote and every checkout/clone after that will be ok.

How to overload functions in javascript?

In javascript you can implement the function just once and invoke the function without the parameters myFunc() You then check to see if options is 'undefined'

function myFunc(options){
 if(typeof options != 'undefined'){
  //code
 }
}

Requested bean is currently in creation: Is there an unresolvable circular reference?

In general, the way to deal with circular dependencies is to use setter injection.

I tried the setter injection code that you posted, and it worked for me. I would imagine the reason you are getting the exception is because Bean1 and Bean2 are in the com.myapp.beans package, and you don't have component scanning enabled for that package.

You'd need to add the following to your spring configuration:

<context:component-scan base-package="com.bullethq.accounts.web"/>

or move the beans to a package which is being automatically scanned by Spring.

How to refresh token with Google API client?

You need to save the access token to file or database as a json string during the initial authorization request, and set the access type to offline $client->setAccessType("offline")

Then, during subsequent api requests, grab the access token from your file or db and pass it to the client:

$accessToken = json_decode($row['token'], true);
$client->setAccessToken($accessToken);

Now you need to check if the token has expired:

if ($client->isAccessTokenExpired()) {
    // access token has expired, use the refresh token to obtain a new one
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    // save the new token to file or db
    // ...json_encode($client->getAccessToken())

The fetchAccessTokenWithRefreshToken() function will do the work for you and provide a new access token, save it back to your file or database.

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How to chain scope queries with OR instead of AND?

According to this pull request, Rails 5 now supports the following syntax for chaining queries:

Post.where(id: 1).or(Post.where(id: 2))

There's also a backport of the functionality into Rails 4.2 via this gem.

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

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

What does Ruby have that Python doesn't, and vice versa?

What Ruby has over Python are its scripting language capabilities. Scripting language in this context meaning to be used for "glue code" in shell scripts and general text manipulation.

These are mostly shared with Perl. First-class built-in regular expressions, $-Variables, useful command line options like Perl (-a, -e) etc.

Together with its terse yet epxressive syntax it is perfect for these kind of tasks.

Python to me is more of a dynamically typed business language that is very easy to learn and has a neat syntax. Not as "cool" as Ruby but neat. What Python has over Ruby to me is the vast number of bindings for other libs. Bindings to Qt and other GUI libs, many game support libraries and and and. Ruby has much less. While much used bindings e.g. to Databases are of good quality I found niche libs to be better supported in Python even if for the same library there is also a Ruby binding.

So, I'd say both languages have its use and it is the task that defines which one to use. Both are easy enough to learn. I use them side-by-side. Ruby for scripting and Python for stand-alone apps.

What's the difference between utf8_general_ci and utf8_unicode_ci?

For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_0900_ai_ci.

All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.

_unicode_ci and _general_ci are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _0900_ai_ci for equivalent rules based on Unicode 9.0 - and with no equivalent _general_ci variant. People reading this now should probably use one of these newer collations instead of either _unicode_ci or _general_ci. The description of those older collations below is provided for interest only.

MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4 instead of utf8 for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.

Key differences

  • utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

  • utf8mb4_general_ci is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.

    On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.

Benefits of utf8mb4_unicode_ci over utf8mb4_general_ci

utf8mb4_unicode_ci, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.

As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_ci sorting in MySQL, but there are still a few differences:

  • For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8mb4_general_ci sorts them as single characters (presumably like "s" and "e" respectively).

  • Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_ci handles these properly.

In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_ci sorting. The suitability of utf8mb4_general_ci will depend heavily on the language used. For some languages, it'll be quite inadequate.

What should you use?

There is almost certainly no reason to use utf8mb4_general_ci anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.

In the past, some people recommended to use utf8mb4_general_ci except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.

There's an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It's trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ci is a compromise that's probably not needed for speed reasons and probably also not suitable for accuracy reasons.

One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.

What the parts mean

Firstly, ci is for case-insensitive sorting and comparison. This means it's suitable for textual data, and case is not important. The other types of collation are cs (case-sensitive) for textual data where case is important, and bin, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.

Next, unicode or general refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with unicode and general being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that unicode uses rules from Unicode 4.0. Recent versions of MySQL add the rulesets unicode_520 using rules from Unicode 5.2, and 0900 (dropping the "unicode_" part) using rules from Unicode 9.0.

And lastly, utf8mb4 is of course the character encoding used internally. In this answer I'm talking only about Unicode based encodings.

How to find all duplicate from a List<string>?

Using LINQ, ofcourse. The below code would give you dictionary of item as string, and the count of each item in your sourc list.

var item2ItemCount = list.GroupBy(item => item).ToDictionary(x=>x.Key,x=>x.Count());

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

The easiest way to get Primary Key and Foreign Key for a table is:

/*  Get primary key and foreign key for a table */
USE DatabaseName;

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE CONSTRAINT_NAME LIKE 'PK%' AND
TABLE_NAME = 'TableName'

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE CONSTRAINT_NAME LIKE 'FK%' AND
TABLE_NAME = 'TableName'

Command-line Git on Windows

These instructions worked for a Windows 8 with a msysgit/TortoiseGit installation, but should be applicable for other types of git installations on Windows.

  • Go to Control Panel\System and Security\System
  • Click on Advanced System Settings on the left which opens System Properties.
  • Click on the Advanced Tab
  • Click on the Environment Variables button at the bottom of the dialog box.
  • Edit the System Variable called PATH.
  • Append these two paths to the list of existing paths already present in the system variable. The tricky part was two paths were required. These paths may vary for your PC. ;C:\msysgit\bin\;C:\msysgit\mingw\bin\
  • Close the CMD prompt window if it is open already. CMD needs to restart to get the updated Path variable.
  • Try typing git in the command line, you should see a list of the git commands scroll down the screen.

python pandas extract year from datetime: df['year'] = df['date'].year is not working

This works:

df['date'].dt.year

Now:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month

gives this data frame:

        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

How do I escape a string inside JavaScript code inside an onClick handler?

First, it would be simpler if the onclick handler was set this way:

<a id="someLinkId"href="#">Select</a>
<script type="text/javascript">
  document.getElementById("someLinkId").onClick = 
   function() {
      SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;
    };

</script>

Then itemid and itemname need to be escaped for JavaScript (that is, " becomes \", etc.).

If you are using Java on the server side, you might take a look at the class StringEscapeUtils from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.

FPDF utf-8 encoding (HOW-TO)

This answer didn't work for me, I needed to run html decode on the string also. See

iconv('UTF-8', 'windows-1252', html_entity_decode($str));

Props go to emfi from html_entity_decode in FPDF(using tFPDF extention)

The FastCGI process exited unexpectedly

In my case I had wrong constellation of configurations:

  • error reporting disabled
  • typo error in the configuration

After enabling the error_reporting it was clear the session_path was pointed to a wrong folder.

"Sad but true"

How can I add NSAppTransportSecurity to my info.plist file?

To explain a bit more about ParaSara's answer: App Transport security will become mandatory and trying to turn it off may get your app rejected.

As a developer, you can turn App Transport security off if your networking code doesn't work with it, and you want to continue other development before fixing any problems. Say in a team of five, four can continue working on other things while one fixes all the problems. You can also turn App Transport security off as a debugging tool if you have networking problems and you want to check if they are caused by App Transport security. As soon as you know you should turn it on again immediately.

The solution that you must use in the future is not to use http at all, unless you use a third party server that doesn't support https. If your own server doesn't support https, Apple will have a problem with that. Even with third party servers, I wouldn't bet that Apple accepts it.

Same with the various checks for server security. At some point Apple will only accept justifiable exceptions.

But mostly, consider this: You are endangering the privacy of your customers. That's a big no-no in my book. Don't do that. Fix your code, don't ask for permission to run unsafe code.

How do I include a file over 2 directories back?

You can do ../../directory/file.txt - This goes two directories back.

../../../ - this goes three. etc

Python safe method to get value of nested dictionary

A solution I've used that is similar to the double get but with the additional ability to avoid a TypeError using if else logic:

    value = example_dict['key1']['key2'] if example_dict.get('key1') and example_dict['key1'].get('key2') else default_value

However, the more nested the dictionary the more cumbersome this becomes.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

Add a property to a JavaScript object using a variable as the name?

ajavascript have two type of annotation for fetching javascript Object properties:

Obj = {};

1) (.) annotation eg. Obj.id this will only work if the object already have a property with name 'id'

2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.

so for below example:

A new property will be created always when you write Obj[name]. And if the property already exist with the same name it will override it.

const obj = {}
    jQuery(itemsFromDom).each(function() {
      const element = jQuery(this)
      const name = element.attr('id')
      const value = element.attr('value')
      // This will work
      obj[name]= value;
    })

How to create EditText with cross(x) button at end of it?

2020 solution via Material Design Components for Android:

Add Material Components to your gradle setup:

Look for latest version from here: https://maven.google.com/

implementation 'com.google.android.material:material:1.1.0'

or if you havent updated to using AndroidX libs, you can add it this way:

implementation 'com.android.support:design:28.0.0'

Then

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_text"
    app:endIconMode="clear_text">

  <com.google.android.material.textfield.TextInputEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>

Pay attention to: app:endIconMode="clear_text"

As discussed here Material design docs

MySQL Update Inner Join tables query

Try this:

UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

Update:

Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:

mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> UPDATE business AS b
    -> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
    -> SET b.mapx = g.latitude,
    ->   b.mapy = g.longitude
    -> WHERE  (b.mapx = '' or b.mapx = 0) and
    ->   g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

See? No syntax error. I tested against MySQL 5.5.8.

Is there a Mutex in Java?

I think you should try with :

While Semaphore initialization :

Semaphore semaphore = new Semaphore(1, true);

And in your Runnable Implementation

try 
{
   semaphore.acquire(1);
   // do stuff

} 
catch (Exception e) 
{
// Logging
}
finally
{
   semaphore.release(1);
}

Clear icon inside input text

<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="type here" />
   <input type="reset" value="" alt="clear" />
</form>

<style>
   input[type="text"]
   {
      height: 38px;
      font-size: 15pt;
   }

   input[type="text"]:invalid + input[type="reset"]{
     display: none;
   } 

   input[type="reset"]
   {
      background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
      background-position: center center;
      background-repeat: no-repeat;
      height: 38px;
      width: 38px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -9px;
      left: -44px;
   }
</style>

How to check if String is null

You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:

textBox1.Text = s ?? "Is null";

The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.

More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015

textBox1.Text = customer?.orders?[0].description ?? "n/a";

This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.

More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

What is declarative programming?

I'd explain it as DP is a way to express

  • A goal expression, the conditions for - what we are searching for. Is there one, maybe or many?
  • Some known facts
  • Rules that extend the know facts

...and where there is a deduct engine usually working with a unification algorithm to find the goals.

How can I safely create a nested directory?

For a one-liner solution, you can use IPython.utils.path.ensure_dir_exists():

from IPython.utils.path import ensure_dir_exists
ensure_dir_exists(dir)

From the documentation: Ensure that a directory exists. If it doesn’t exist, try to create it and protect against a race condition if another process is doing the same.

Figuring out whether a number is a Double in Java

Since this is the first question from Google I'll add the JavaScript style typeof alternative here as well:

myObject.getClass().getName() // String

Graphical DIFF programs for linux

I use Guiffy and it works well.
alt text
(source: guiffy.org)

Windows Explorer "Command Prompt Here"

I use StExBar, a Windows Explorer extension that gives you a command prompt button in explorer along with some other cool features (copy path, copy file name & more).

https://tools.stefankueng.com/StExBar.html

EDIT: I just found out (been using it for more than a year and did not know this) that Ctrl+M will do it with StExBar. How's that for fast!

How to parse the AndroidManifest.xml file inside an .apk package

You can use axml2xml.pl tool developed a while ago within android-random project. It will generate the textual manifest file (AndroidManifest.xml) from the binary one.

I'm saying "textual" and not "original" because like many reverse-engineering tools this one isn't perfect and the result will not be complete. I presume either it was never feature complete or simply not forward-compatible (with newer binary encoding scheme). Whatever the reason, axml2xml.pl tool will not be able to extract all the attribute values correctly. Such attributes are minSdkVersion, targetSdkVersion and basically all attributes that are referencing resources (like strings, icons, etc.), i.e. only class names (of activities, services, etc.) are extracted correctly.

However, you can still find these missing information by running aapt tool on the original Android app file (.apk):

aapt l -a <someapp.apk>

Only allow specific characters in textbox

    private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
        {
            e.Handled = true;
        }
    }

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

You should copy the image files from the "drawable-24" folder to the "drawable" folder.

What's the difference between OpenID and OAuth?

I am currently working on OAuth 2.0 and OpenID connect spec. So here is my understanding: Earlier they were:

  1. OpenID was proprietary implementation of Google allowing third party applications like for newspaper websites you can login using google and comment on an article and so on other usecases. So essentially, no password sharing to newspaper website. Let me put up a definition here, this approach in enterprise approach is called Federation. In Federation, You have a server where you authenticate and authorize (called IDP, Identity Provider) and generally the keeper of User credentials. the client application where you have business is called SP or Service Provider. If we go back to same newspaper website example then newspaper website is SP here and Google is IDP. In enterprise this problem was earlier solved using SAML. that time XML used to rule the software industry. So from webservices to configuration, everything used to go to XML so we have SAML, a complete Federation protocol
  2. OAuth: OAuth saw it's emergence as an standard looking at all these kind of proprietary approaches and so we had OAuth 1.o as standard but addressing only authorization. Not many people noticed but it kind of started picking up. Then we had OAuth 2.0 in 2012. CTOs, Architects really started paying attention as world is moving towards Cloud computing and with computing devices moving towards mobile and other such devices. OAuth kind of looked upon as solving major problem where software customers might give IDP Service to one company and have many services from different vendors like salesforce, SAP, etc. So integration here really looks like federation scenario bit one big problem, using SAML is costly so let's explore OAuth 2.o. Ohh, missed one important point that during this time, Google sensed that OAuth actually doesn't address Authentication, how will IDP give user data to SP (which is actually wonderfully addressed in SAML) and with other loose ends like:

    a. OAuth 2.o doesn't clearly say, how client registration will happen b. it doesn't mention anything about the interaction between SP (Resource Server) and client application (like Analytics Server providing data is Resource Server and application displaying that data is Client)

There are already wonderful answers given here technically, I thought of giving of giving brief evolution perspective

Submitting a form by pressing enter without a submit button

Another solution without the submit button:

HTML

<form>
  <input class="submit_on_enter" type="text" name="q" placeholder="Search...">
</form>

jQuery

$(document).ready(function() {

  $('.submit_on_enter').keydown(function(event) {
    // enter has keyCode = 13, change it if you want to use another button
    if (event.keyCode == 13) {
      this.form.submit();
      return false;
    }
  });

});

Add 'x' number of hours to date

You may use something like the strtotime() function to add something to the current timestamp. $new_time = date("Y-m-d H:i:s", strtotime('+5 hours')).

If you need variables in the function, you must use double quotes then like strtotime("+{$hours} hours"), however better you use strtotime(sprintf("+%d hours", $hours)) then.

Array versus linked-list

First of all, in C++ linked-lists shouldn't be much more trouble to work with than an array. You can use the std::list or the boost pointer list for linked lists. The key issues with linked lists vs arrays are extra space required for pointers and terrible random access. You should use a linked list if you

  • you don't need random access to the data
  • you will be adding/deleting elements, especially in the middle of the list

dataframe: how to groupBy/count then filter on count in Scala

When you pass a string to the filter function, the string is interpreted as SQL. Count is a SQL keyword and using count as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).

You can easily avoid this by using a column expression instead of a String:

df.groupBy("x").count()
  .filter($"count" >= 2)
  .show()

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

how to make a cell of table hyperlink

I have seen this before when people are trying to build a calendar. You want the cell linked but do not want to mess with anything else inside of it, try this and it might solve your problem.

<tr>
<td onClick="location.href='http://www.stackoverflow.com';">
Cell content goes here
</td>
</tr>

Cycles in an Undirected Graph

A connected, undirected graph G that has no cycles is a tree! Any tree has exactly n - 1 edges, so we can simply traverse the edge list of the graph and count the edges. If we count n - 1 edges then we return “yes” but if we reach the nth edge then we return “no”. This takes O (n) time because we look at at most n edges.

But if the graph is not connected,then we would have to use DFS. We can traverse through the edges and if any unexplored edges lead to the visited vertex then it has cycle.

What is the meaning of <> in mysql query?

In MySQL, <> means Not Equal To, just like !=.

mysql> SELECT '.01' <> '0.01';
        -> 1
mysql> SELECT .01 <> '0.01';
        -> 0
mysql> SELECT 'zapp' <> 'zappp';
        -> 1

see the docs for more info

What's the UIScrollView contentInset property for?

It's used to add padding in UIScrollView

Without contentInset, a table view is like this:

enter image description here

Then set contentInset:

tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

The effect is as below:

enter image description here

Seems to be better, right?

And I write a blog to study the contentInset, criticism is welcome.

Cannot make a static reference to the non-static method fxn(int) from the type Two

Since the main method is static and the fxn() method is not, you can't call the method without first creating a Two object. So either you change the method to:

public static int fxn(int y) {
    y = 5;
    return y;
}

or change the code in main to:

Two two = new Two();
x = two.fxn(x);

Read more on static here in the Java Tutorials.

How to establish a connection pool in JDBC?

Don't reinvent the wheel.

Try one of the readily available 3rd party components:

  • Apache DBCP - This one is used internally by Tomcat, and by yours truly.
  • c3p0

Apache DBCP comes with different example on how to setup a pooling javax.sql.DataSource. Here is one sample that can help you get started.

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

For those who are still having trouble with this, try separating the two lines as below.

override func viewDidLoad() {
    self.navigationController!.interactivePopGestureRecognizer!.delegate = self
    ...

override func viewWillAppear(_ animated: Bool) {
    self.navigationController!.interactivePopGestureRecognizer!.isEnabled = true
    ...

Obviously, in my app,

interactivePopGestureRecognizer!.isEnabled

got reset to false before the view was shown for some reason.

How to generate .env file for laravel?

This is an old thread, but as it still gets viewed and recently active "26" days ago as of this post, here is a quick solution.

There is no .env file initially, you must duplicate .env.example as .env.

In windows, you can open a command prompt aka the CLI and paste the exact code below while inside the root directory of the project. Must include the ( at the start line without space.

(
echo APP_NAME=Laravel
echo APP_ENV=local
echo APP_KEY=
echo APP_DEBUG=true
echo APP_URL=http://localhost
echo.
echo LOG_CHANNEL=stack
echo.
echo DB_CONNECTION=mysql
echo DB_HOST=127.0.0.1
echo DB_PORT=3306
echo DB_DATABASE=homestead
echo DB_USERNAME=homestead
echo DB_PASSWORD=secret
echo.
echo BROADCAST_DRIVER=log
echo CACHE_DRIVER=file
echo SESSION_DRIVER=file
echo SESSION_LIFETIME=120
echo QUEUE_DRIVER=sync
echo.
echo REDIS_HOST=127.0.0.1
echo REDIS_PASSWORD=null
echo REDIS_PORT=6379
echo.
echo MAIL_DRIVER=smtp
echo MAIL_HOST=smtp.mailtrap.io
echo MAIL_PORT=2525
echo MAIL_USERNAME=null
echo MAIL_PASSWORD=null
echo MAIL_ENCRYPTION=null
echo.
echo PUSHER_APP_ID=
echo PUSHER_APP_KEY=
echo PUSHER_APP_SECRET=
echo PUSHER_APP_CLUSTER=mt1
echo.
echo MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
echo MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
)>".env"

Just press enter to exit the prompt and you should have the .env file with the default settings created in the same directory you typed above CLI command.

Hope this helps.

How to fix Python Numpy/Pandas installation?

This worked for me under 10.7.5 with EPD_free-7.3-2 from Enthought:

Install EPD free, then follow the step in the following link to create .bash_profile file.

http://redfinsolutions.com/blog/creating-bashprofile-your-mac

And add the following to the file.

PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:$(PATH)}"
export PATH

Execute the following command in Terminal

$ sudo easy_install pandas

When finished, launch PyLab and type:

In [1]: import pandas

In [2]: plot(arange(10))

This should open a plot with a diagonal straight line.

How to print an exception in Python 3?

Here is the way I like that prints out all of the error stack.

import logging

try:
    1 / 0
except Exception as _e:
    # any one of the follows:
    # print(logging.traceback.format_exc())
    logging.error(logging.traceback.format_exc())

The output looks as the follows:

ERROR:root:Traceback (most recent call last):
  File "/PATH-TO-YOUR/filename.py", line 4, in <module>
    1 / 0
ZeroDivisionError: division by zero

LOGGING_FORMAT :

LOGGING_FORMAT = '%(asctime)s\n  File "%(pathname)s", line %(lineno)d\n  %(levelname)s [%(message)s]'

getting the difference between date in days in java

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }

How to ORDER BY a SUM() in MySQL?

Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.

Try this:

SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname

OR this:

SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2

And you can always do a derived query like this:

SELECT
   f1, f2
FROM
    (
        SELECT SUM(x+y) as f1, foo as F2
        FROM tablename 
        GROUP BY f2
    ) as table1
ORDER BY 
    f1

Many possibilities!

Error: "Could Not Find Installable ISAM"

Just use Jet OLEDB: in your connection string. it solved for me.

an example is below:

"Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=E:\Database.mdb;Jet OLEDB:Database Password=b10w"

C#: How to access an Excel cell?

Simple.

To open a workbook. Use xlapp.workbooks.Open()

where you have previously declared and instanitated xlapp as so.. Excel.Application xlapp = new Excel.Applicaton();

parameters are correct.

Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.

Skip first couple of lines while reading lines in Python file

Use a slice, like below:

with open('yourfile.txt') as f:
    lines_after_17 = f.readlines()[17:]

If the file is too big to load in memory:

with open('yourfile.txt') as f:
    for _ in range(17):
        next(f)
    for line in f:
        # do stuff

How to upload a file to directory in S3 bucket using boto

You should mention the content type as well to omit the file accessing issue.

import os
image='fly.png'
s3_filestore_path = 'images/fly.png'
filename, file_extension = os.path.splitext(image)
content_type_dict={".png":"image/png",".html":"text/html",
               ".css":"text/css",".js":"application/javascript",
               ".jpg":"image/png",".gif":"image/gif",
               ".jpeg":"image/jpeg"}

content_type=content_type_dict[file_extension]
s3 = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'),
                  region_name='ap-south-1',
                  aws_access_key_id=S3_KEY,
                  aws_secret_access_key=S3_SECRET)
s3.put_object(Body=image, Bucket=S3_BUCKET, Key=s3_filestore_path, ContentType=content_type)

SOAP client in .NET - references or examples?

I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.

That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):

  • Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
  • Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
  • Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
  • One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
  • Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.

</rant> :)

Generic Interface

Here's another suggestion:

public interface Service<T> {
   T execute();
}

using this simple interface you can pass arguments via constructor in the concrete service classes:

public class FooService implements Service<String> {

    private final String input1;
    private final int input2;

    public FooService(String input1, int input2) {
       this.input1 = input1;
       this.input2 = input2;
    }

    @Override
    public String execute() {
        return String.format("'%s%d'", input1, input2);
    }
}

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

What is the --save option for npm install?

You can also use -S, -D or -P which are equivalent of saving the package to an app dependency, a dev dependency or prod dependency. See more NPM shortcuts below:

-v: --version
-h, -?, --help, -H: --usage
-s, --silent: --loglevel silent
-q, --quiet: --loglevel warn
-d: --loglevel info
-dd, --verbose: --loglevel verbose
-ddd: --loglevel silly
-g: --global
-C: --prefix
-l: --long
-m: --message
-p, --porcelain: --parseable
-reg: --registry
-f: --force
-desc: --description
-S: --save
-P: --save-prod
-D: --save-dev
-O: --save-optional
-B: --save-bundle
-E: --save-exact
-y: --yes
-n: --yes false
ll and la commands: ls --long

This list of shortcuts can be obtained by running the following command:

$ npm help 7 config

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

How do I apply a diff patch on Windows?

Just use:

patch -p0 < path-file.patch

remember execute this command only from the folder location where you created the patch.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

Tensorflow 2.0 Compatible Answer: In Tensorflow Version >= 2.0, the command for Initializing all the Variables if we use Graph Mode, to fix the FailedPreconditionError is shown below:

tf.compat.v1.global_variables_initializer

This is just a shortcut for variables_initializer(global_variables())

It returns an Op that initializes global variables in the graph.

Ubuntu apt-get unable to fetch packages

I tried using :

sudo do-release-upgrade

and then use :

sudo apt-get update

after that you will be able to install any packages.

If this did not worked for you try to change the network conf in apt.conf

List of all unique characters in a string?

I have an idea. Why not use the ascii_lowercase constant?

For example, running the following code:

# string module, contains constant ascii_lowercase which is all the lowercase
# letters of the English alphabet
import string
# Example value of s, a string
s = 'aaabcabccd'
# Result variable to store the resulting string
result = ''
# Goes through each letter in the alphabet and checks how many times it appears.
# If a letter appears at least oce, then it is added to the result variable
for letter in string.ascii_letters:
    if s.count(letter) >= 1:
        result+=letter

# Optional three lines to convert result variable to a list for sorting
# and then back to a string
result = list(result)
result.sort()
result = ''.join(result)

print(result)

Will print 'abcd'

There you go, all duplicates removed and optionally sorted

Exporting the values in List to excel

Fast way - ArrayToExcel (github)

byte[] excel = myList.ToExcel();
File.WriteAllBytes("result.xlsx", excel);

Any easy way to use icons from resources?

Forms maintain separate resource files (SomeForm.Designer.resx) added via the designer. To use icons embedded in another resource file requires codes. (this.Icone = Project.Resources.SomeIcon;)

What is difference between Lightsail and EC2?

In lightsail a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP are all offered as a package. Whereas in normal case you provision an EC2 instance and then setup the rest of these things.Also Bandwidth included in the price, no security groups to set up, no need to worry about EBS volumes sizing.

How to access the last value in a vector?

I use the tail function:

tail(vector, n=1)

The nice thing with tail is that it works on dataframes too, unlike the x[length(x)] idiom.

Which @NotNull Java annotation should I use?

I very much like the Checker Framework, which is an implementation of type annotations (JSR-308) which is used to implement defect checkers like a nullness checker. I haven't really tried any others to offer any comparison, but I've been happy with this implementation.

I'm not affiliated with the group that offers the software, but I am a fan.

Four things I like about this system:

  1. It has a defect checkers for nullness (@Nullable), but also has ones for immutability and interning (and others). I use the first one (nullness) and I'm trying to get into using the second one (immutability/IGJ). I'm trying out the third one, but I'm not certain about using it long term yet. I'm not convinced of the general usefulness of the other checkers yet, but its nice to know that the framework itself is a system for implementing a variety of additional annotations and checkers.

  2. The default setting for nullness checking works well: Non-null except locals (NNEL). Basically this means that by default the checker treats everyhing (instance variables, method parameters, generic types, etc) except local variables as if they have a @NonNull type by default. Per the documentation:

    The NNEL default leads to the smallest number of explicit annotations in your code.

    You can set a different default for a class or for a method if NNEL doesn't work for you.

  3. This framework allows you to use with without creating a dependency on the framework by enclosing your annotations in a comment: e.g. /*@Nullable*/. This is nice because you can annotate and check a library or shared code, but still be able to use that library/shared coded in another project that doesn't use the framework. This is a nice feature. I've grown accustom to using it, even though I tend to enable the Checker Framework on all my projects now.

  4. The framework has a way to annotate APIs you use that aren't already annotated for nullness by using stub files.

What is the difference between server side cookie and client side cookie?

All cookies are client and server

There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.

But essentially it's the same cookie.

But, behavior can change

A cookie is basically a name=value pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server). Those attributes can be about lifetime, context and various security settings.

HTTP-only (is not server-only)

One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!

So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.

Alternatives to achieve 'only-ness'

If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.

Is there a way to get version from package.json in nodejs code?

Option 1

Best practice is to version from package.json using npm environment variables.

process.env.npm_package_version

more information on: https://docs.npmjs.com/using-npm/config.html

This will work only when you start your service using NPM command.

Quick Info: you can read any values in pacakge.json using process.env.npm_package_[keyname]

Option 2

Setting version in environment variable using https://www.npmjs.com/package/dotenv as .env file and reading it as process.env.version

Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

Getting cursor position in Python

win32gui.GetCursorPos(point)

This retrieves the cursor's position, in screen coordinates - point = (x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()

Retrieves information about the global cursor.

Links:

I am assuming that you would be using python win32 API bindings or pywin32.

Java Could not reserve enough space for object heap error

Double click Liferay CE Server -> add -XX:MaxHeapSize=512m to Memory args -> Start server! Enjoy...

It's work for me!

Why do we need the "finally" clause in Python?

You can use finally to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)

myfile = open("test.txt", "w")

try:
    myfile.write("the Answer is: ")
    myfile.write(42)   # raises TypeError, which will be propagated to caller
finally:
    myfile.close()     # will be executed before TypeError is propagated

In this example you'd be better off using the with statement, but this kind of structure can be used for other kinds of resources.

A few years later, I wrote a blog post about an abuse of finally that readers may find amusing.

Git says remote ref does not exist when I delete remote branch

I followed the solution by poke with a minor adjustment in the end. My steps follow
- git fetch --prune;
- git branch -a printing the following
    master
    branch
    remotes/origin/HEAD -> origin/master
    remotes/origin/master
    remotes/origin/branch (remote branch to remove)
- git push origin --delete branch.
Here, the branch to remove is not named as remotes/origin/branch but simply branch. And the branch is removed.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

Actually it is the issue related to the app store. I have upload many build some time it takes time depend upon the size of the ipa and at which time you are uploading it to the App Store. Please use Application Loader 3.0 or higher to upload the build.

Struct with template variables in C++

You don't need to do an explicit typedef for classes and structs. What do you need the typedef for? Further, the typedef after a template<...> is syntactically wrong. Simply use:

template <class T>
struct array {
  size_t x;
  T *ary;
} ;

Changing the background color of a drop down list transparent in html

You can actualy fake the transparency of option DOMElements with the following CSS:

CSS

option { 
    /* Whatever color  you want */
    background-color: #82caff;
}

See Demo

The option tag does not support rgba colors yet.

How to check if all inputs are not empty with jQuery

$('#form_submit_btn').click(function(){
    $('input').each(function() {
        if(!$(this).val()){
            alert('Some fields are empty');
           return false;
        }
    });
});

How to load URL in UIWebView in Swift?

import UIKit

class ViewController: UIViewController{

@IBOutlet weak var webView: UIWebView!



override func viewDidLoad() {
   super.viewDidLoad()
       //Func Gose Here 
      loadUrl()

   } 
 func loadUrl(){

   let url = URL(string: "Url which you want to load(www.google.com)")
   let requestObj = URLRequest(url: url! as URL)
   webView.load(requestObj)
 }

}

How to use su command over adb shell?

for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.

adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""

How to split a list by comma not space

Create a bash function

split_on_commas() {
  local IFS=,
  local WORD_LIST=($1)
  for word in "${WORD_LIST[@]}"; do
    echo "$word"
  done
}

split_on_commas "this,is a,list" | while read item; do
  # Custom logic goes here
  echo Item: ${item}
done

... this generates the following output:

Item: this
Item: is a
Item: list

(Note, this answer has been updated according to some feedback)

How add class='active' to html menu with php

             <ul>

                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>

                </ul>

Why catch and rethrow an exception in C#?

My main reason for having code like:

try
{
    //Some code
}
catch (Exception e)
{
    throw;
}

is so I can have a breakpoint in the catch, that has an instantiated exception object. I do this a lot while developing/debugging. Of course, the compiler gives me a warning on all the unused e's, and ideally they should be removed before a release build.

They are nice during debugging though.

Run Executable from Powershell script with parameters

Just adding an example that worked fine for me:

$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg

EC2 Instance Cloning

You can make an AMI of an existing instance, and then launch other instances using that AMI.

How to Toggle a div's visibility by using a button click

Bootstrap 4 provides the Collapse component for that. It's using JavaScript behind the scenes, but you don't have to write any JavaScript yourself.

This feature works for <button> and <a>.

If you use a <button>, you must set the data-toggle and data-target attributes:

<button type="button" data-toggle="collapse" data-target="#collapseExample">
  Toggle
</button>
<div class="collapse" id="collapseExample">
  Lorem ipsum
</div>

If you use a <a>, you must use set href and data-toggle:

<a data-toggle="collapse" href="#collapseExample">
  Toggle
</a>
<div class="collapse" id="collapseExample">
  Lorem ipsum
</div>

How can I open a Shell inside a Vim Window?

If you haven't found out yet, you can use the amazing screen plugin.

Conque is also exceptional but I find screen much more practical (it wont "litter" your buffer for example and you can just send the commands that you really want after editing them in your buffer)

How to find reason of failed Build without any error or warning

Delete .vs folder & restart VS, worked for me

enter image description here

How to create a file on Android Internal Storage?

Hi try this it will create directory + file inside it

File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
    mediaDir.mkdir();
}

File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();

System.out.println("Your file has been written");  

Bootstrap Carousel : Remove auto slide

data-interval="false"

Add this to the corresponding div ...

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

MongoDB has a simple web based administrative port at 28017 by default.

There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.

To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.

If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.

How to upgrade docker container after its image changed

Here's what it looks like using docker-compose when building a custom Dockerfile.

  1. Build your custom Dockerfile first, appending a next version number to differentiate. Ex: docker build -t imagename:version . This will store your new version locally.
  2. Run docker-compose down
  3. Edit your docker-compose.yml file to reflect the new image name you set at step 1.
  4. Run docker-compose up -d. It will look locally for the image and use your upgraded one.

-EDIT-

My steps above are more verbose than they need to be. I've optimized my workflow by including the build: . parameter to my docker-compose file. The steps looks this now:

  1. Verify that my Dockerfile is what I want it to look like.
  2. Set the version number of my image name in my docker-compose file.
  3. If my image isn't built yet: run docker-compose build
  4. Run docker-compose up -d

I didn't realize at the time, but docker-compose is smart enough to simply update my container to the new image with the one command, instead of having to bring it down first.

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

Android Drawing Separator/Divider Line in Layout?

Easiest Way:

Vertical divider :

<View style="@style/Divider.Vertical"/>

Vertical divider view

Horizontal divider :

<View style="@style/Divider.Horizontal"/>

Horizontal divider view

That's all yes!

Just put this in res>values>styles.xml

<style name="Divider">
    <item name="android:background">?android:attr/listDivider</item> //you can give your color here. that will change all divider color in your app.
</style>

<style name="Divider.Horizontal" parent="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item> // You can change thickness here.

</style>

<style name="Divider.Vertical" parent="Divider">
    <item name="android:layout_width">1dp</item>
    <item name="android:layout_height">match_parent</item>
</style>

How to duplicate a whole line in Vim?

You can also try <C-x><C-l> which will repeat the last line from insert mode and brings you a completion window with all of the lines. It works almost like <C-p>

Removing cordova plugins from the project

From the terminal (osx) I usually use

cordova plugin -l | xargs cordova plugins rm

Pipe, pipe everything!

To expand a bit: this command will loop through the results of cordova plugin -l and feed it to cordova plugins rm.

xargs is one of those commands that you wonder why you didn't know about before. See this tut.

How do I create a Java string from the contents of a file?

After Ctrl+F'ing after Scanner, I think that the Scanner solution should be listed too. In the easiest to read fashion it goes like this:

public String fileToString(File file, Charset charset) {
  Scanner fileReader = new Scanner(file, charset);
  fileReader.useDelimiter("\\Z"); // \Z means EOF.
  String out = fileReader.next();
  fileReader.close();
  return out;
}

If you use Java 7 or newer (and you really should) consider using try-with-resources to make the code easier to read. No more dot-close stuff littering everything. But that's mostly a stylistic choice methinks.

I'm posting this mostly for completionism, since if you need to do this a lot, there should be things in java.nio.file.Files that should do the job better.

My suggestion would be to use Files#readAllBytes(Path) to grab all the bytes, and feed it to new String(byte[] Charset) to get a String out of it that you can trust. Charsets will be mean to you during your lifetime, so beware of this stuff now.

Others have given code and stuff, and I don't want to steal their glory. ;)

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

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

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

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

utf8mb4 is a superset of utf8

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

Firestore Getting documents id from collection

For document references, not collections, you need:

// when you know the 'id'

this.afs.doc(`items/${id}`)
  .snapshotChanges().pipe(
    map((doc: any) => {
      const data = doc.payload.data();
      const id = doc.payload.id;
      return { id, ...data };
    });

as .valueChanges({ idField: 'id'}); will not work here. I assume it was not implemented since generally you search for a document by the id...

What is apache's maximum url length?

The default limit for the length of the request line is 8192 bytes = 8* 1024. It you want to change the limit, you have to add or update in your tomcat server.xml the attribut maxHttpHeaderSize.

as:

<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />

In this example I set the limite to 65536 bytes= 64*1024.

Hope this will help.

Hibernate Query By Example and Projections

The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:

http://opensource.atlassian.com/projects/hibernate/browse/HHH-817

Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.

Passing parameters to click() & bind() event in jquery?

var someParam = xxxxxxx;

commentbtn.click(function(){

    alert(someParam );
});

Case insensitive comparison of strings in shell script

For zsh the syntax is slightly different, but still shorter than most answers here:

> str1='mAtCh'
> str2='MaTcH'
> [[ "$str1:u" = "$str2:u" ]] && echo 'Strings Match!'
Strings Match!
>

This will convert both strings to uppercase before the comparison.


Another method makes use zsh's globbing flags, which allows us to directly make use of case-insensitive matching by using the i glob flag:

setopt extendedglob
[[ $str1 = (#i)$str2 ]] && echo "Match success"
[[ $str1 = (#i)match ]] && echo "Match success"

Sending credentials with cross-domain posts?

You can use the beforeSend callback to set additional parameters (The XMLHTTPRequest object is passed to it as its only parameter).

Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:

$.ajax({
    url: 'http://bar.other',
    data: { whatever:'cool' },
    type: 'GET',
    beforeSend: function(xhr){
       xhr.withCredentials = true;
    }
});

One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

Another possible cause of this is trying to use the ;x509; module on something that is not X.509.

The server certificate is X.509 format, but the private key is RSA.

So:

openssl rsa -noout -text -in privkey.pem
openssl x509 -noout -text -in servercert.pem

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

I got error "The DELETE statement conflicted with the REFERENCE constraint"

To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.

To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.

Pythonic way to combine FOR loop and IF statement

As per The Zen of Python (if you are wondering whether your code is "Pythonic", that's the place to go):

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Flat is better than nested.
  • Readability counts.

The Pythonic way of getting the sorted intersection of two sets is:

>>> sorted(set(a).intersection(xyz))
[0, 4, 6, 7, 9]

Or those elements that are xyz but not in a:

>>> sorted(set(xyz).difference(a))
[12, 242]

But for a more complicated loop you may want to flatten it by iterating over a well-named generator expression and/or calling out to a well-named function. Trying to fit everything on one line is rarely "Pythonic".


Update following additional comments on your question and the accepted answer

I'm not sure what you are trying to do with enumerate, but if a is a dictionary, you probably want to use the keys, like this:

>>> a = {
...     2: 'Turtle Doves',
...     3: 'French Hens',
...     4: 'Colly Birds',
...     5: 'Gold Rings',
...     6: 'Geese-a-Laying',
...     7: 'Swans-a-Swimming',
...     8: 'Maids-a-Milking',
...     9: 'Ladies Dancing',
...     0: 'Camel Books',
... }
>>>
>>> xyz = [0, 12, 4, 6, 242, 7, 9]
>>>
>>> known_things = sorted(set(a.iterkeys()).intersection(xyz))
>>> unknown_things = sorted(set(xyz).difference(a.iterkeys()))
>>>
>>> for thing in known_things:
...     print 'I know about', a[thing]
...
I know about Camel Books
I know about Colly Birds
I know about Geese-a-Laying
I know about Swans-a-Swimming
I know about Ladies Dancing
>>> print '...but...'
...but...
>>>
>>> for thing in unknown_things:
...     print "I don't know what happened on the {0}th day of Christmas".format(thing)
...
I don't know what happened on the 12th day of Christmas
I don't know what happened on the 242th day of Christmas

How to print multiple lines of text with Python

As far as I know, there are three different ways.

Use \n in your print:

print("first line\nSecond line")

Use sep="\n" in print:

print("first line", "second line", sep="\n")

Use triple quotes and a multiline string:

print("""
Line1
Line2
""")

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

How to extract extension from filename string in Javascript?

A variant that works with all of the following inputs:

  • "file.name.with.dots.txt"
  • "file.txt"
  • "file"
  • ""
  • null
  • undefined

would be:

var re = /(?:\.([^.]+))?$/;

var ext = re.exec("file.name.with.dots.txt")[1];   // "txt"
var ext = re.exec("file.txt")[1];                  // "txt"
var ext = re.exec("file")[1];                      // undefined
var ext = re.exec("")[1];                          // undefined
var ext = re.exec(null)[1];                        // undefined
var ext = re.exec(undefined)[1];                   // undefined

Explanation

(?:         # begin non-capturing group
  \.        #   a dot
  (         #   begin capturing group (captures the actual extension)
    [^.]+   #     anything except a dot, multiple times
  )         #   end capturing group
)?          # end non-capturing group, make it optional
$           # anchor to the end of the string

How to hide element label by element id in CSS?

If you give the label an ID, like this:

<label for="foo" id="foo_label">

Then this would work:

#foo_label { display: none;}

Your other options aren't really cross-browser friendly, unless javascript is an option. The CSS3 selector, not as widely supported looks like this:

[for="foo"] { display: none;}

Creation timestamp and last update timestamp with Hibernate and MySQL

With Olivier's solution, during update statements you may run into:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'created' cannot be null

To solve this, add updatable=false to the @Column annotation of "created" attribute:

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created", nullable = false, updatable=false)
private Date created;

Android Layout Right Align

To support older version Space can be replaced with View as below. Add this view between after left most component and before right most component. This view with weight=1 will stretch and fill the space

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

Complete sample code is given here. It has has 4 components. Two arrows will be on the right and left side. The Text and Spinner will be in the middle.

    <ImageButton
        android:id="@+id/btnGenesis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="left"
        android:src="@drawable/prev" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/lblVerseHeading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <Spinner
        android:id="@+id/spinnerVerses"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <ImageButton
        android:id="@+id/btnExodus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="right"
        android:src="@drawable/next" />
</LinearLayout>

Abstract class in Java

Simply speaking, you can think of an abstract class as like an Interface with a bit more capabilities.

You cannot instantiate an Interface, which also holds for an abstract class.

On your interface you can just define the method headers and ALL of the implementers are forced to implement all of them. On an abstract class you can also define your method headers but here - to the difference of the interface - you can also define the body (usually a default implementation) of the method. Moreover when other classes extend (note, not implement and therefore you can also have just one abstract class per child class) your abstract class, they are not forced to implement all of your methods of your abstract class, unless you specified an abstract method (in such case it works like for interfaces, you cannot define the method body).

public abstract class MyAbstractClass{
  public abstract void DoSomething();
}

Otherwise for normal methods of an abstract class, the "inheriters" can either just use the default behavior or override it, as usual.

Example:

public abstract class MyAbstractClass{

  public int CalculateCost(int amount){
     //do some default calculations
     //this can be overriden by subclasses if needed
  }

  //this MUST be implemented by subclasses
  public abstract void DoSomething();
}

Sort an Array by keys based on another Array?

Just use array_merge or array_replace. Array_merge works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:

$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';

$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);
//Or:
$properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer);

//$properOrderedArray -> array('name' => 'Tim', 'address' => '123 fake st', 'dob' => '12/08/1986', 'dontSortMe' => 'this value doesnt need to be sorted')

ps - I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.

pip broke. how to fix DistributionNotFound error?

I find this problem in my MacBook, the reason is because as @Stephan said, I use easy_install to install pip, and the mixture of both py package manage tools led to the pkg_resources.DistributionNotFound problem. The resolve is:

easy_install --upgrade pip

Remember: just use one of the above tools to manage your Py packages.

Can we pass an array as parameter in any function in PHP?

In php 5, you can also hint the type of the passed variable:

function sendemail(array $id, $userid){
  //function body
}

See type hinting.

Call to getLayoutInflater() in places not in activity

Using context object you can get LayoutInflater from following code

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

How to forward declare a template class in namespace std?

Forward declaration should have complete template arguments list specified.

Accessing localhost:port from Android emulator

If you are using IIS Express you may need to bind to all hostnames instead of just `localhost'. Check this fine answer:

https://stackoverflow.com/a/15809698/383761

Tell IIS Express itself to bind to all ip addresses and hostnames. In your .config file (typically %userprofile%\My Documents\IISExpress\config\applicationhost.config, or $(solutionDir).vs\config\applicationhost.config for Visual Studio 2015), find your site's binding element, and add

<binding protocol="http" bindingInformation="*:8080:*" />

Make sure to add it as a second binding instead of modifying the existing one or VS will just re-add a new site appended with a (1) Also, you may need to run VS as an administrator.

How do I get the first n characters of a string without checking the size or going out of bounds?

String upToNCharacters = String.format("%."+ n +"s", str);

Awful if n is a variable (so you must construct the format string), but pretty clear if a constant:

String upToNCharacters = String.format("%.10s", str);

docs

How can I make Java print quotes, like "Hello"?

System.out.print("\"Hello\"");

The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:

  • Carriage return and newline: "\r" and "\n"
  • Backslash: "\\\\"
  • Single quote: "\'"
  • Horizontal tab and form feed: "\t" and "\f"

The complete list of Java string and character literal escapes may be found in the section 3.10.6 of the JLS.

It is also worth noting that you can include arbitrary Unicode characters in your source code using Unicode escape sequences of the form "\uxxxx" where the "x"s are hexadecimal digits. However, these are different from ordinary string and character escapes in that you can use them anywhere in a Java program ... not just in string and character literals; see JLS sections 3.1, 3.2 and 3.3 for a details on the use of Unicode in Java source code.

See also:

What does LINQ return when the results are empty

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

(Dump is from LinqPad)

How can one change the timestamp of an old commit in Git?

Building on theosp's answer, I wrote a script called git-cdc (for change date commit) that I put in my PATH.

The name is important: git-xxx anywhere in your PATH allows you to type:

git xxx
# here
git cdc ... 

That script is in bash, even on Windows (since Git will be calling it from its msys environment)

#!/bin/bash
# commit
# date YYYY-mm-dd HH:MM:SS

commit="$1" datecal="$2"
temp_branch="temp-rebasing-branch"
current_branch="$(git rev-parse --abbrev-ref HEAD)"

date_timestamp=$(date -d "$datecal" +%s)
date_r=$(date -R -d "$datecal")

if [[ -z "$commit" ]]; then
    exit 0
fi

git checkout -b "$temp_branch" "$commit"
GIT_COMMITTER_DATE="$date_timestamp" GIT_AUTHOR_DATE="$date_timestamp" git commit --amend --no-edit --date "$date_r"
git checkout "$current_branch"
git rebase  --autostash --committer-date-is-author-date "$commit" --onto "$temp_branch"
git branch -d "$temp_branch"

With that, you can type:

git cdc @~ "2014-07-04 20:32:45"

That would reset author/commit date of the commit before HEAD (@~) to the specified date.

git cdc @~ "2 days ago"

That would reset author/commit date of the commit before HEAD (@~) to the same hour, but 2 days ago.


Ilya Semenov mentions in the comments:

For OS X you may also install GNU coreutils (brew install coreutils), add it to PATH (PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH") and then use "2 days ago" syntax.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Can promises have multiple arguments to onFulfilled?

Here is a CoffeeScript solution.

I was looking for the same solution and found seomething very intersting from this answer: Rejecting promises with multiple arguments (like $http) in AngularJS

the answer of this guy Florian

promise = deferred.promise

promise.success = (fn) ->
  promise.then (data) ->
   fn(data.payload, data.status, {additional: 42})
  return promise

promise.error = (fn) ->
  promise.then null, (err) ->
    fn(err)
  return promise

return promise 

And to use it:

service.get().success (arg1, arg2, arg3) ->
    # => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
    # => err

Get Folder Size from Windows Command Line

There is a built-in Windows tool for that:

dir /s 'FolderName'

This will print a lot of unnecessary information but the end will be the folder size like this:

 Total Files Listed:
       12468 File(s)    182,236,556 bytes

If you need to include hidden folders add /a.

How to round the minute of a datetime object

Pandas has a datetime round feature, but as with most things in Pandas it needs to be in Series format.

>>> ts = pd.Series(pd.date_range(Dt(2019,1,1,1,1),Dt(2019,1,1,1,4),periods=8))
>>> print(ts)
0   2019-01-01 01:01:00.000000000
1   2019-01-01 01:01:25.714285714
2   2019-01-01 01:01:51.428571428
3   2019-01-01 01:02:17.142857142
4   2019-01-01 01:02:42.857142857
5   2019-01-01 01:03:08.571428571
6   2019-01-01 01:03:34.285714285
7   2019-01-01 01:04:00.000000000
dtype: datetime64[ns]

>>> ts.dt.round('1min')
0   2019-01-01 01:01:00
1   2019-01-01 01:01:00
2   2019-01-01 01:02:00
3   2019-01-01 01:02:00
4   2019-01-01 01:03:00
5   2019-01-01 01:03:00
6   2019-01-01 01:04:00
7   2019-01-01 01:04:00
dtype: datetime64[ns]

Docs - Change the frequency string as needed.

SQL: How To Select Earliest Row

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow

grep a tab in UNIX

If using GNU grep, you can use the Perl-style regexp:

grep -P '\t' *

Can't connect to local MySQL server through socket '/tmp/mysql.sock

The socket is located in /tmp. On Unix system, due to modes & ownerships on /tmp, this could cause some problem. But, as long as you tell us that you CAN use your mysql connexion normally, I guess it is not a problem on your system. A primal check should be to relocate mysql.sock in a more neutral directory.

The fact that the problem occurs "randomly" (or not every time) let me think that it could be a server problem.

  • Is your /tmp located on a standard disk, or on an exotic mount (like in the RAM) ?

  • Is your /tmp empty ?

  • Does iotopshow you something wrong when you encounter the problem ?

"date(): It is not safe to rely on the system's timezone settings..."

This issue has been bugging me for SOME time as im trying to inject a "createbucket.php" script into composer and i keep being told my time-zone is incorrect.

In the end the only thing that fixed the issue was to: $ sudo nano /etc/php.ini

Search for timezone

[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = UTC

Ensure you remove the ;

Then finally

$ sudo service httpd restart

And you'll be good to go :)

Find records with a date field in the last 24 hours

SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);

Can't bind to 'dataSource' since it isn't a known property of 'table'

In my case the trouble was I didn't put the components that contain the datasource in the declarations of main module.

NgModule({
  imports: [
    EnterpriseConfigurationsRoutingModule,
    SharedModule
  ],
  declarations: [
    LegalCompanyTypeAssignComponent,
    LegalCompanyTypeAssignItemComponent,
    ProductsOfferedListComponent,
    ProductsOfferedItemComponent,
    CustomerCashWithdrawalRangeListComponent,
    CustomerCashWithdrawalRangeItemComponent,
    CustomerInitialAmountRangeListComponent,
    CustomerInitialAmountRangeItemComponent,
    CustomerAgeRangeListComponent,
    CustomerAgeRangeItemComponent,
    CustomerAccountCreditRangeListComponent, //<--This component contains the dataSource
    CustomerAccountCreditRangeItemComponent,
  

  ],

The component contains the dataSource:

export class CustomerAccountCreditRangeListComponent implements OnInit {

  @ViewChild(MatPaginator) set paginator(paginator: MatPaginator){
    this.dataSource.paginator = paginator;
  }
  @ViewChild(MatSort) set sort(sort: MatSort){
    this.dataSource.sort = sort;
  }

  dataSource = new MatTableDataSource(); //<--The dataSource used in HTML
  loading: any;
  resultsLength: any;
  displayedColumns: string[] = ["id", "desde", "hasta", "tipoClienteNombre", "eliminar"];
  data: any;

  constructor(
    private crud: CustomerAccountCreditRangeService,
    public snackBar: MatSnackBar,
    public dialog: MatDialog,
    private ui: UIComponentsService
  ) {
  }

This is for Angular 9

What Scala web-frameworks are available?

There's a new web framework, called Scala Web Pages. From the site:

Target Audience

The Scala Pages web framework is likely to appeal to web programmers who come from a Java background and want to program web applications in Scala. The emphasis is on OOP rather than functional programming.

Characteristics And Features

  • Adheres to model-view-controller paradigm
  • Text-based template engine
  • Simple syntax: $variable and <?scp-instruction?>
  • Encoding/content detection, able to handle international text encodings
  • Snippets instead of custom tags
  • URL Rewriting

Printing the correct number of decimal points with cout

You have to set the 'float mode' to fixed.

float num = 15.839;

// this will output 15.84
std::cout << std::fixed << "num = " << std::setprecision(2) << num << std::endl;

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

SQL query question: SELECT ... NOT IN

SELECT Reservations.idCustomer FROM Reservations (nolock)
LEFT OUTER JOIN @reservations ExcludedReservations (nolock) ON Reservations.idCustomer=ExcludedReservations.idCustomer AND DATEPART(hour, ExcludedReservations.insertDate) < 2
WHERE ExcludedReservations.idCustomer IS NULL AND Reservations.idCustomer IS NOT NULL
GROUP BY Reservations.idCustomer

[Update: Added additional criteria to handle idCustomer being NULL, which was apparently the main issue the original poster had]

include antiforgerytoken in ajax post ASP.NET MVC

Another (less javascriptish) approach, that I did, goes something like this:

First, an Html helper

public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
{
    var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
    // Above gets the following: <input name="__RequestVerificationToken" type="hidden" value="PnQE7R0MIBBAzC7SqtVvwrJpGbRvPgzWHo5dSyoSaZoabRjf9pCyzjujYBU_qKDJmwIOiPRDwBV1TNVdXFVgzAvN9_l2yt9-nf4Owif0qIDz7WRAmydVPIm6_pmJAI--wvvFQO7g0VvoFArFtAR2v6Ch1wmXCZ89v0-lNOGZLZc1" />
    var removedStart = antiForgeryInputTag.Replace(@"<input name=""__RequestVerificationToken"" type=""hidden"" value=""", "");
    var tokenValue = removedStart.Replace(@""" />", "");
    if (antiForgeryInputTag == removedStart || removedStart == tokenValue)
        throw new InvalidOperationException("Oops! The Html.AntiForgeryToken() method seems to return something I did not expect.");
    return new MvcHtmlString(string.Format(@"{0}:""{1}""", "__RequestVerificationToken", tokenValue));
}

that will return a string

__RequestVerificationToken:"P5g2D8vRyE3aBn7qQKfVVVAsQc853s-naENvpUAPZLipuw0pa_ffBf9cINzFgIRPwsf7Ykjt46ttJy5ox5r3mzpqvmgNYdnKc1125jphQV0NnM5nGFtcXXqoY3RpusTH_WcHPzH4S4l1PmB8Uu7ubZBftqFdxCLC5n-xT0fHcAY1"

so we can use it like this

$(function () {
    $("#submit-list").click(function () {
        $.ajax({
            url: '@Url.Action("SortDataSourceLibraries")',
            data: { items: $(".sortable").sortable('toArray'), @Html.AntiForgeryTokenForAjaxPost() },
            type: 'post',
            traditional: true
        });
    });
});

And it seems to work!

How to get difference between two dates in Year/Month/Week/Day?

int day=0,month=0,year=0;
DateTime smallDate = Convert.ToDateTime(string.Format("{0}", "01.01.1900"));
DateTime bigDate = Convert.ToDateTime(string.Format("{0}", "05.06.2019"));
TimeSpan timeSpan = new TimeSpan();

//timeSpan is diff between bigDate and smallDate as days
timeSpan = bigDate - smallDate;

//year is totalDays / 365 as int
year = timeSpan.Days / 365;

//smallDate.AddYears(year) is closing the difference for year because we found the year variable
smallDate = smallDate.AddYears(year);

//again subtraction because we don't need the year now
timeSpan = bigDate - smallDate;

//month is totalDays / 30 as int
month = timeSpan.Days / 30;

//smallDate.AddMonths(month) is closing the difference for month because we found the month variable
smallDate = smallDate.AddMonths(month);
if (bigDate > smallDate)
{
    timeSpan = bigDate - smallDate;
    day = timeSpan.Days;
}
//else it is mean already day is 0

can you add HTTPS functionality to a python flask web server?

  • To run https functionality or SSL authentication in flask application you first install "pyOpenSSL" python package using:

     pip install pyopenssl
    
  • Next step is to create 'cert.pem' and 'key.pem' using following command on terminal :

     openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
    
  • Copy generated 'cert.pem' and 'kem.pem' in you flask application project

  • Add ssl_context=('cert.pem', 'key.pem') in app.run()

For example:

    from flask import Flask, jsonify

    app = Flask(__name__)

    @app.route('/')

    def index():

        return 'Flask is running!'


    @app.route('/data')

    def names():

        data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}

        return jsonify(data)

  if __name__ == '__main__':

        app.run(ssl_context=('cert.pem', 'key.pem'))

MySQL SELECT LIKE or REGEXP to match multiple words in one record

The correct solution is a FullText Search (if you can use it) https://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

This nearly does what you want:

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100)+.*(Stylus|2100)+';

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*';

But this will also match "210021002100" which is not great.

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

You can able to validate following ways and understand the difference.

_x000D_
_x000D_
var j = undefined;_x000D_
console.log((typeof j == 'undefined') ? "true":"false");_x000D_
var j = null; _x000D_
console.log((j == null) ? "true":"false");_x000D_
var j = "";_x000D_
console.log((!j) ? "true":"false");_x000D_
var j = "Hi";_x000D_
console.log((!j) ? "true":"false");
_x000D_
_x000D_
_x000D_

How does OkHttp get Json string?

I am also faced the same issue

use this code:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

it definitely works

Group by in LINQ

You can also Try this:

var results= persons.GroupBy(n => new { n.PersonId, n.car})
                .Select(g => new {
                               g.Key.PersonId,
                               g.Key.car)}).ToList();

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

setInterval()

function that repeats itself in every n milliseconds

Javascript

 setInterval(function(){ Console.log("A Kiss every 5 seconds"); }, 5000);

Approximate java Equivalent

new Timer().scheduleAtFixedRate(new TimerTask(){
    @Override
    public void run(){
       Log.i("tag", "A Kiss every 5 seconds");
    }
},0,5000);

setTimeout()

function that works only after n milliseconds

Javascript

setTimeout(function(){ Console.log("A Kiss after 5 seconds"); },5000);

Approximate java Equivalent

new android.os.Handler().postDelayed(
    new Runnable() {
        public void run() {
            Log.i("tag","A Kiss after 5 seconds");
        }
}, 5000);

What does "for" attribute do in HTML <label> tag?

The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.

set environment variable in python script

There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote() to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).

shell=False is always the default where you pass an argument array.

Now the safe solutions...

Method #1

Change your own process's environment - the new environment will apply to python itself and all subprocesses.

os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Method #2

Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.

myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)

Method #3

Unix only: Execute env to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.

command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Of course if var1 contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True you must compose a command array that contain the splitted string:

command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']

Is it possible to use if...else... statement in React render function?

If you need more than one condition, so you can try this out

https://www.npmjs.com/package/react-if-elseif-else-render

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';

class Example extends Component {

  render() {
    var i = 3; // it will render '<p>Else</p>'
    return (
      <If condition={i == 1}>
        <Then>
          <p>Then: 1</p>
        </Then>
        <ElseIf condition={i == 2}>
          <p>ElseIf: 2</p>
        </ElseIf>
        <Else>
          <p>Else</p>
        </Else>
      </If>
    );
  }
}

Moving Git repository content to another repository preserving history

It looks like you're close. Assuming that it's not just a typo in your submission, step 3 should be cd repo2 instead of repo1. And step 6 should be git pull not push. Reworked list:

1. git clone repo1
2. git clone repo2
3. cd repo2
4. git remote rm origin
5. git remote add repo1
6. git pull
7. git remote rm repo1
8. git remote add newremote

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

T-SQL Subquery Max(Date) and Joins

Something like this

SELECT * 
FROM MyParts 
LEFT JOIN 
(
SELECT MAX(PriceDate), PartID FROM MyPrice group by PartID
) myprice
 ON MyParts.Partid = MyPrice.Partid 

If you know your partid or can restrict it put it inside the join.

   SELECT myprice.partid, myprice.partdate, myprice2.Price, * 
    FROM MyParts 
    LEFT JOIN 
    (
    SELECT MAX(PriceDate), PartID FROM MyPrice group by PartID
    ) myprice
     ON MyParts.Partid = MyPrice.Partid 
    Inner Join MyPrice myprice2
    on myprice2.pricedate = myprice.pricedate
    and myprice2.partid = myprice.partid

.NET Global exception handler in console application

What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.

static void Main(string[] args)
{
    try
    {
        // Start Working
    }
    catch (Exception ex)
    {
        // Output/Log Exception
    }
    finally
    {
        // Clean Up If Needed
    }
}

And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.

Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.

What is cardinality in Databases?

Cardinality refers to the uniqueness of data contained in a column. If a column has a lot of duplicate data (e.g. a column that stores either "true" or "false"), it has low cardinality, but if the values are highly unique (e.g. Social Security numbers), it has high cardinality.

How to Batch Rename Files in a macOS Terminal?

you can install rename command by using brew. just do brew install rename and use it.

Select where count of one field is greater than one

You can also do this with a self-join:

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk

Parameterize an SQL IN clause

This is possibly a half nasty way of doing it, I used it once, was rather effective.

Depending on your goals it might be of use.

  1. Create a temp table with one column.
  2. INSERT each look-up value into that column.
  3. Instead of using an IN, you can then just use your standard JOIN rules. ( Flexibility++ )

This has a bit of added flexibility in what you can do, but it's more suited for situations where you have a large table to query, with good indexing, and you want to use the parametrized list more than once. Saves having to execute it twice and have all the sanitation done manually.

I never got around to profiling exactly how fast it was, but in my situation it was needed.

Add space between HTML elements only using CSS

<span> is an inline element so you cant make spacing on them without making it block level. Try this

Horizontal

span{
    margin-right: 10px;
    float: left;
}

Vertical

span{
    margin-bottom: 10px;
}

Compatible with all browsers.

How to center a checkbox in a table cell?

How about this... http://jsfiddle.net/gSaPb/


Check out my example on jsFiddle: http://jsfiddle.net/QzPGu. Code snippet:

_x000D_
_x000D_
td {
  text-align: center;
  /* center checkbox horizontally */
  vertical-align: middle;
  /* center checkbox vertically */
}

table {
  border: 1px solid;
  width: 200px;
}

tr {
  height: 80px;
}
_x000D_
<table>
  <tr>
    <td>
      <input type="checkbox" name="myTextEditBox" value="checked" /> checkbox
    </td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Displaying tooltip on mouse hover of a text

You shouldn't use the control private tooltip, but the form one. This example works well:

public partial class Form1 : Form
{
    private System.Windows.Forms.ToolTip toolTip1;

    public Form1()
    {
        InitializeComponent();
        this.components = new System.ComponentModel.Container();
        this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);

        MyRitchTextBox myRTB = new MyRitchTextBox();
        this.Controls.Add(myRTB);

        myRTB.Location = new Point(10, 10);
        myRTB.MouseEnter += new EventHandler(myRTB_MouseEnter);
        myRTB.MouseLeave += new EventHandler(myRTB_MouseLeave);
    }


    void myRTB_MouseEnter(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Show("Hello!!!", rtb);
        }
    }

    void myRTB_MouseLeave(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Hide(rtb);
        }
    }


    public class MyRitchTextBox : RichTextBox
    {
    }

}

Mockito: List Matchers with generics

For Java 8 and above, it's easy:

when(mock.process(Matchers.anyList()));

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz):

when(mock.process(Matchers.anyListOf(Bar.class)));

How do you convert Html to plain text?

HTTPUtility.HTMLEncode() is meant to handle encoding HTML tags as strings. It takes care of all the heavy lifting for you. From the MSDN Documentation:

If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and >, are encoded as &lt; and &gt; for HTTP transmission.

HTTPUtility.HTMLEncode() method, detailed here:

public static void HtmlEncode(
  string s,
  TextWriter output
)

Usage:

String TestString = "This is a <Test String>.";
StringWriter writer = new StringWriter();
Server.HtmlEncode(TestString, writer);
String EncodedString = writer.ToString();

TypeError: tuple indices must be integers, not str

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

Presenting modal in iOS 13 fullscreen

class MyViewController: UIViewController {

    convenience init() {
        self.init(nibName:nil, bundle:nil)
        self.modalPresentationStyle = .fullScreen
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Rather than call self.modalPresentationStyle = .fullScreen for every view controller, you can subclass UIViewController and just use MyViewController everywhere.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

in webpack 4 with multiple module rules you would just do something like this in your .js rule:

{
     test: /\.(js)$/,
     loader: 'babel-loader',
     options: {
          presets: ['es2015'],    // or whatever
          plugins: [require('babel-plugin-transform-class-properties')], // or whatever
          compact: true    // or false during development
     }
},

C# Double - ToString() formatting with two decimal places but no rounding

Also note the CultureInformation of your system. Here my solution without rounding.

In this example you just have to define the variable MyValue as double. As result you get your formatted value in the string variable NewValue.

Note - Also set the C# using statement:

using System.Globalization;  

string MyFormat = "0";
if (MyValue.ToString (CultureInfo.InvariantCulture).Contains (CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator))
   {
      MyFormat += ".00";
   }

string NewValue = MyValue.ToString(MyFormat);

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I would urge against using OleDB, especially if its going to be run on a server. Its likely to cost you more in the long run - eg we had a SSIS job calling a Stored Procedure with the OleDB reading an excel file in the sptroc and kept crashing the SQL box! I took the OleDB stuff out of the sproc and it stopped crashing the server.

A better method I've found is to do it with Office 2003 and the XML files - in respect of Considerations for server-side Automation of Office. Note: Office 2003 is a minimum requirement for this to fly:

Ref for reading from Excel: http://www.roelvanlisdonk.nl/?p=924 (please do more research to find other examples)

Ref for writing a Excel spreadsheet: http://weblogs.asp.net/jgaylord/archive/2008/08/11/use-linq-to-xml-to-generate-excel-documents.aspx

public void ReadExcelCellTest()
        {
            XDocument document = XDocument.Load(@"C:\BDATA\Cars.xml");
            XNamespace workbookNameSpace = @"urn:schemas-microsoft-com:office:spreadsheet";

            // Get worksheet
            var query = from w in document.Elements(workbookNameSpace + "Workbook").Elements(workbookNameSpace + "Worksheet")
                        where w.Attribute(workbookNameSpace + "Name").Value.Equals("Settings")
                        select w;
            List<XElement> foundWoksheets = query.ToList<XElement>();
            if (foundWoksheets.Count() <= 0) { throw new ApplicationException("Worksheet Settings could not be found"); }
            XElement worksheet = query.ToList<XElement>()[0];

            // Get the row for "Seat"
            query = from d in worksheet.Elements(workbookNameSpace + "Table").Elements(workbookNameSpace + "Row").Elements(workbookNameSpace + "Cell").Elements(workbookNameSpace + "Data")
                    where d.Value.Equals("Seat")
                    select d;
            List<XElement> foundData = query.ToList<XElement>();
            if (foundData.Count() <= 0) { throw new ApplicationException("Row 'Seat' could not be found"); }
            XElement row = query.ToList<XElement>()[0].Parent.Parent;

            // Get value cell of Etl_SPIImportLocation_ImportPath setting
            XElement cell = row.Elements().ToList<XElement>()[1];

            // Get the value "Leon"
            string cellValue = cell.Elements(workbookNameSpace + "Data").ToList<XElement>()[0].Value;

            Console.WriteLine(cellValue);
        }

Unable to connect to SQL Server instance remotely

Disable the firewall and try to connect.

If that works, then enable the firewall and

Windows Defender Firewall -> Advanced Settings -> Inbound Rules(Right Click) -> New Rules -> Port -> Allow Port 1433 (Public and Private) -> Add

Do the same for Outbound Rules.

Then Try again.

How to view .img files?

As you did not mention which OS you are running, here a solution for linux: use losetup

losetup /dev/loop0 /path/to/your/file.img

Then you can mount it.

Convert IEnumerable to DataTable

Firstly you need to add a where T:class constraint - you can't call GetValue on value types unless they're passed by ref.

Secondly GetValue is very slow and gets called a lot.

To get round this we can create a delegate and call that instead:

MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );

The problem is that we don't know TProperty, but as usual on here Jon Skeet has the answer - we can use reflection to retrieve the getter delegate, but once we have it we don't need to reflect again:

public class ReflectionUtility
{
    internal static Func<object, object> GetGetter(PropertyInfo property)
    {
        // get the get method for the property
        MethodInfo method = property.GetGetMethod(true);

        // get the generic get-method generator (ReflectionUtility.GetSetterHelper<TTarget, TValue>)
        MethodInfo genericHelper = typeof(ReflectionUtility).GetMethod(
            "GetGetterHelper",
            BindingFlags.Static | BindingFlags.NonPublic);

        // reflection call to the generic get-method generator to generate the type arguments
        MethodInfo constructedHelper = genericHelper.MakeGenericMethod(
            method.DeclaringType,
            method.ReturnType);

        // now call it. The null argument is because it's a static method.
        object ret = constructedHelper.Invoke(null, new object[] { method });

        // cast the result to the action delegate and return it
        return (Func<object, object>) ret;
    }

    static Func<object, object> GetGetterHelper<TTarget, TResult>(MethodInfo method)
        where TTarget : class // target must be a class as property sets on structs need a ref param
    {
        // Convert the slow MethodInfo into a fast, strongly typed, open delegate
        Func<TTarget, TResult> func = (Func<TTarget, TResult>) Delegate.CreateDelegate(typeof(Func<TTarget, TResult>), method);

        // Now create a more weakly typed delegate which will call the strongly typed one
        Func<object, object> ret = (object target) => (TResult) func((TTarget) target);
        return ret;
    }
}

So now your method becomes:

public static DataTable ToDataTable<T>(this IEnumerable<T> items) 
    where T: class
{  
    // ... create table the same way

    var propGetters = new List<Func<T, object>>();
foreach (var prop in props)
    {
        Func<T, object> func = (Func<T, object>) ReflectionUtility.GetGetter(prop);
        propGetters.Add(func);
    }

    // Add the property values per T as rows to the datatable
    foreach (var item in items) 
    {  
        var values = new object[props.Length];  
        for (var i = 0; i < props.Length; i++) 
        {
            //values[i] = props[i].GetValue(item, null);   
            values[i] = propGetters[i](item);
        }    

        table.Rows.Add(values);  
    } 

    return table; 
} 

You could further optimise it by storing the getters for each type in a static dictionary, then you will only have the reflection overhead once for each type.

Can I update a component's props in React.js?

Props can change when a component's parent renders the component again with different properties. I think this is mostly an optimization so that no new component needs to be instantiated.

HTTP Headers for File Downloads

As explained by Alex's link you're probably missing the header Content-Disposition on top of Content-Type.

So something like this:

Content-Disposition: attachment; filename="MyFileName.ext"

How can I change the Java Runtime Version on Windows (7)?

All you need to do is set the PATH environment variable in Windows to point to where your java6 bin directory is instead of the java7 directory.

Right click My Computer > Advanced System Settings > Advanced > Environmental Variables

If there is a JAVA_HOME environment variable set this to point to the correct directory as well.

Compile a DLL in C/C++, then call it from another program

For VB6:

You need to declare your C functions as __stdcall, otherwise you get "invalid calling convention" type errors. About other your questions:

can I take arguments by pointer/reference from the VB front-end?

Yes, use ByRef/ByVal modifiers.

Can the DLL call a theoretical function in the front-end?

Yes, use AddressOf statement. You need to pass function pointer to dll before.

Or have a function take a "function pointer" (I don't even know if that's possible) from VB and call it?)

Yes, use AddressOf statement.

update (more questions appeared :)):

to load it into VB, do I just do the usual method (what I would do to load winsock.ocx or some other runtime, but find my DLL instead) or do I put an API call into a module?

You need to decaler API function in VB6 code, like next:

Private Declare Function SHGetSpecialFolderLocation Lib "shell32" _
   (ByVal hwndOwner As Long, _
    ByVal nFolder As Long, _
    ByRef pidl As Long) As Long

Get top first record from duplicate records having no unique identity

SELECT TOP 1000 MAX(tel) FROM TableName WHERE Id IN 
(
SELECT Id FROM TableName
GROUP BY Id
HAVING COUNT(*) > 1
) 
GROUP BY Id

Contain an image within a div?

Here is javascript I wrote to do just this.

function ImageTile(parentdiv, imagediv) {
imagediv.style.position = 'absolute';

function load(image) {
    //
    // Reset to auto so that when the load happens it resizes to fit our image and that
    // way we can tell what size our image is. If we don't do that then it uses the last used
    // values to auto-size our image and we don't know what the actual size of the image is.
    //
    imagediv.style.height = "auto";
    imagediv.style.width = "auto";
    imagediv.style.top = 0;
    imagediv.style.left = 0;

    imagediv.src = image;
}

//bind load event (need to wait for it to finish loading the image)
imagediv.onload = function() {
    var vpWidth = parentdiv.clientWidth;
    var vpHeight = parentdiv.clientHeight;
    var imgWidth = this.clientWidth;
    var imgHeight = this.clientHeight;

    if (imgHeight > imgWidth) {
        this.style.height = vpHeight + 'px';
        var width = ((imgWidth/imgHeight) * vpHeight);
        this.style.width = width + 'px';
        this.style.left = ((vpWidth - width)/2) + 'px';
    } else {
        this.style.width = vpWidth + 'px';
        var height = ((imgHeight/imgWidth) * vpWidth);
        this.style.height = height + 'px';
        this.style.top = ((vpHeight - height)/2) + 'px';
    }
};

return {
    "load": load
};

}

And to use it just do something like this:

 var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
 tile1.load(url);

I use this for a slideshow in which I have two of these "tiles" and I fade one out and the other in. The loading is done on the "tile" that is not visible to avoid the jarring visual affect of the resetting of the style back to "auto".

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

If your objective is to import a theme into your Wordpress then you can manually copy paste your theme into your wp-content->themes folder and extract it of course. I just encountered this and couldn't locate the php.ini file for WAMP.

How to define a preprocessor symbol in Xcode

Go to your Target or Project settings, click the Gear icon at the bottom left, and select "Add User-Defined Setting". The new setting name should be GCC_PREPROCESSOR_DEFINITIONS, and you can type your definitions in the right-hand field.

Per Steph's comments, the full syntax is:

constant_1=VALUE constant_2=VALUE

Note that you don't need the '='s if you just want to #define a symbol, rather than giving it a value (for #ifdef statements)

Is there a link to the "latest" jQuery library on Google APIs?

Up until jQuery 1.11.1, you could use the following URLs to get the latest version of jQuery:

For example:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will forever be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; Don't use jquery-latest.js.

Both hosts support https as well as http, so change the protocol as you see fit (or use a protocol relative URI)

See also: https://developers.google.com/speed/libraries/devguide

Get type of a generic parameter in Java with reflection

One construct, I once stumbled upon looked like

Class<T> persistentClass = (Class<T>)
   ((ParameterizedType)getClass().getGenericSuperclass())
      .getActualTypeArguments()[0];

So there seems to be some reflection-magic around that I unfortunetly don't fully understand... Sorry.

How to split a string in shell and get the last field

A solution using the read builtin:

IFS=':' read -a fields <<< "1:2:3:4:5"
echo "${fields[4]}"

Or, to make it more generic:

echo "${fields[-1]}" # prints the last item

How to send SMS in Java

You can you LOGICA SMPP Java API for sending and Recieving SMS in Java application. LOGICA SMPP is well proven api in telecom application. Logica API also provide you with signalling capicity on TCP/IP connection.

You can directly integrate with various telecom operator accross the world.

how to check if a form is valid programmatically using jQuery Validation Plugin

@mikemaccana answer is useful.

And I also used https://github.com/ryanseddon/H5F. Found on http://microjs.com. It's some kind of polyfill and you can use it as follows (jQuery is used in example):

if ( $('form')[0].checkValidity() ) {
    // the form is valid
}

MongoDB not equal to

Real life example; find all but not current user:

var players = Players.find({ my_x: player.my_x,  my_y: player.my_y, userId: {$ne: Meteor.userId()} }); 

How to view log output using docker-compose run?

If you want to see output logs from all the services in your terminal.

docker-compose logs -t -f --tail <no of lines> 

Eg.: Say you would like to log output of last 5 lines from all service

docker-compose logs -t -f --tail 5

If you wish to log output from specific services then it can be done as below:

docker-compose logs -t -f --tail <no of lines> <name-of-service1> <name-of-service2> ... <name-of-service N>

Usage:

Eg. say you have API and portal services then you can do something like below :

docker-compose logs -t -f --tail 5 portal api

Where 5 represents last 5 lines from both logs.

Ref: https://docs.docker.com/v17.09/engine/admin/logging/view_container_logs/

Get input value from TextField in iOS alert in Swift

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")
}

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

Save file/open file dialog box, using Swing & Netbeans GUI editor

I think you face three problems:

  1. understanding the FileChooser
  2. writing/reading files
  3. understanding extensions and file formats

ad 1. Are you sure you've connected the FileChooser to a correct panel/container? I'd go for a simple tutorial on this matter and see if it works. That's the best way to learn - by making small but large enough steps forward. Breaking down an issue into such parts might be tricky sometimes ;)

ad. 2. After you save or open the file you should have methods to write or read the file. And again there are pretty neat examples on this matter and it's easy to understand topic.

ad. 3. There's a difference between a file having extension and file format. You can change the format of any file to anything you want but that doesn't affect it's contents. It might just render the file unreadable for the application associated with such extension. TXT files are easy - you read what you write. XLS, DOCX etc. require more work and usually framework is the best way to tackle these.

Difference between "and" and && in Ruby?

and has lower precedence than &&.

But for an unassuming user, problems might occur if it is used along with other operators whose precedence are in between, for example, the assignment operator:

def happy?() true; end
def know_it?() true; end

todo = happy? && know_it? ? "Clap your hands" : "Do Nothing"

todo
# => "Clap your hands"

todo = happy? and know_it? ? "Clap your hands" : "Do Nothing"

todo
# => true

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

What is the difference between java and core java?

Core java is a sun term.It mentions the USE,it means it contains only basics of java and some principles and also contain some packages details.

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Delete forked repo from GitHub

There are multiple answers pointing out, that editing/deleting the fork doesn't affect the original repository. Those answers are correct. I will try to add something to that answer and explain why in my answer.

A fork is just a copy of a repository with a fork relationship.

As you can copy a file or a directory locally to another place and delete the copy, it won't affect the original.

Fork relationship means, that you can easily tell github that it should send a pull request (with your changes) from your fork to the original repository because github knows that your repository is a copy of the original repository(with a few changes on both sides).

Just for anybodies information, a pull request(or merge request) contains code that has been changed in the fork and is submitted to the original repository. Users with push/write access(may be different in other git servers) on the original repository are allowed to merge the changes of the pull request into the original repository(copy the changes of the PR to the original repository).

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.

Adding local .aar files to Gradle build using "flatDirs" is not working

In my case the none of the answers above worked! since I had different productFlavors just adding repositories{ flatDir{ dirs 'libs' } }

did not work! I ended up with specifying exact location of libs directory:

repositories{
flatDir{
    dirs 'src/main/libs'
}

}

Guess one should introduce flatDirs like this when there's different productFlavors in build.gradle

How can I mock an ES6 module import using Jest?

The claims that you have to mock it at the top of your file are false.

Mock a named ES Import:

// import the named module
import { useWalkthroughAnimations } from '../hooks/useWalkthroughAnimations';

// mock the file and its named export
jest.mock('../hooks/useWalkthroughAnimations', () => ({
  useWalkthroughAnimations: jest.fn()
}));

// do whatever you need to do with your mocked function
useWalkthroughAnimations.mockReturnValue({ pageStyles, goToNextPage, page });

Use table name in MySQL SELECT "AS"

To declare a string literal as an output column, leave the Table off and just use Test. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta(), the table name will be an empty string because it isn't associated with a table.

SELECT
  `field1`, 
  `field2`, 
  'Test' AS `field3` 
FROM `Test`;

Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.

If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:

SELECT
  field1,
  field2,
  field3
FROM 
  /* subquery wraps all fields to put the literal inside a table */
  (SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test

Now field3 will come in the output as Test.field3.