Programs & Examples On #Model

Part of the MVC pattern, the Model manages the behaviour and data of the application.

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

Ignore mapping one property with Automapper

Could use IgnoreAttribute on the property which needs to be ignored

Eloquent ORM laravel 5 Get Array of ids

You could use lists() :

test::where('id' ,'>' ,0)->lists('id')->toArray();

NOTE : Better if you define your models in Studly Case format, e.g Test.


You could also use get() :

test::where('id' ,'>' ,0)->get('id');

UPDATE: (For versions >= 5.2)

The lists() method was deprecated in the new versions >= 5.2, now you could use pluck() method instead :

test::where('id' ,'>' ,0)->pluck('id')->toArray();

NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:

test::where('id' ,'>' ,0)->pluck('id');

Accessing MVC's model property from Javascript

If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:

$(document).ready(function () {

    @{  var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         var json = serializer.Serialize(Model);
    }

    var model = @Html.Raw(json);
    if(model != null && @Html.Raw(json) != "undefined")
    {
        var id= model.Id;
        var mainFloorPlanId = model.MainFloorPlanId ;
        var imageDirectory = model.ImageDirectory ;
        var iconsDirectory = model.IconsDirectory ;
    }
});

Hope this helps...

How to set a hidden value in Razor

While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.

@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)

How to load json into my angular.js ng-model?

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

It returns some JSON data which looks like this:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

Using helpers in model: how do I include helper dependencies?

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

Credit goes to lornc's answer

Check if an object exists

You can also use get_object_or_404(), it will raise a Http404 if the object wasn't found:

user_pass = log_in(request.POST) #form class
if user_pass.is_valid():
    cleaned_info = user_pass.cleaned_data
    user_object = get_object_or_404(User, email=cleaned_info['username'])
    # User object found, you are good to go!
    ...

AngularJS - Binding radio buttons to models with boolean values

The correct approach in Angularjs is to use ng-value for non-string values of models.

Modify your code like this:

<label data-ng-repeat="choice in question.choices">
  <input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" />
  {{choice.text}}
</label>

Ref: Straight from the horse's mouth

Tensorflow: how to save/restore a model?

For tensorflow 2.0, it is as simple as

# Save the model
model.save('path_to_my_model.h5')

To restore:

new_model = tensorflow.keras.models.load_model('path_to_my_model.h5')

Determine what attributes were changed in Rails after_save callback?

The "selected" answer didn't work for me. I'm using rails 3.1 with CouchRest::Model (based on Active Model). The _changed? methods don't return true for changed attributes in the after_update hook, only in the before_update hook. I was able to get it to work using the (new?) around_update hook:

class SomeModel < ActiveRecord::Base
  around_update :send_notification_after_change

  def send_notification_after_change
    should_send_it = self.published_changed? && self.published == true

    yield

    Notification.send(...) if should_send_it
  end

end

MVC 4 - how do I pass model data to a partial view?

You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
    </div>
</div>

Rails find_or_create_by more than one attribute?

For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:

# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
  Model.where(attributes).first || Model.create(attributes)
end

Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.

How should a model be structured in MVC?

In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.

Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:

File Database.php

class Database {
    private static $connection;
    private static $current_query;
    ...

    public static function query($sql) {
        if (!self::$connection){
            self::open_connection();
        }
        self::$current_query = $sql;
        $result = mysql_query($sql,self::$connection);

        if (!$result){
            self::close_connection();
            // throw custom error
            // The query failed for some reason. here is query :: self::$current_query
            $error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
            $error->handleError();
        }
        return $result;
    }
 ....

    public static function find_by_sql($sql){
        if (!is_string($sql))
            return false;

        $result_set = self::query($sql);
        $obj_arr = array();
        while ($row = self::fetch_array($result_set))
        {
            $obj_arr[] = self::instantiate($row);
        }
        return $obj_arr;
    }
}

Table object classL

class DomainPeer extends Database {

    public static function getDomainInfoList() {
        $sql = 'SELECT ';
        $sql .='d.`id`,';
        $sql .='d.`name`,';
        $sql .='d.`shortName`,';
        $sql .='d.`created_at`,';
        $sql .='d.`updated_at`,';
        $sql .='count(q.id) as queries ';
        $sql .='FROM `domains` d ';
        $sql .='LEFT JOIN queries q on q.domainId = d.id ';
        $sql .='GROUP BY d.id';
        return self::find_by_sql($sql);
    }

    ....
}

I hope this example helps you create a good structure.

Is there a way to get a collection of all the Models in your Rails app?

Module.constants.select { |c| (eval c).is_a?(Class) && (eval c) < ActiveRecord::Base }

Cannot overwrite model once compiled Mongoose

This problem might occur if you define 2 different schema's with same Collection name

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Here is what a model should look like: Make sure yours is like this.

    <?php
    class Logon_model extends CI_Model {

    function __construct()
    {
         parent::__construct();
    }

    function myFunc()
    {
      // do something
    }
}

note the upper-case class name.

To load it use:

$this->load->model('logon_model');

note all lower case.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

I think I would go with @beberlei's suggestion of using proxy methods. What you can do to make this process simpler is to define two interfaces:

interface AlbumInterface {
    public function getAlbumTitle();
    public function getTracklist();
}

interface TrackInterface {
    public function getTrackTitle();
    public function getTrackDuration();
}

Then, both your Album and your Track can implement them, while the AlbumTrackReference can still implement both, as following:

class Album implements AlbumInterface {
    // implementation
}

class Track implements TrackInterface {
    // implementation
}

/** @Entity whatever */
class AlbumTrackReference implements AlbumInterface, TrackInterface
{
    public function getTrackTitle()
    {
        return $this->track->getTrackTitle();
    }

    public function getTrackDuration()
    {
        return $this->track->getTrackDuration();
    }

    public function getAlbumTitle()
    {
        return $this->album->getAlbumTitle();
    }

    public function getTrackList()
    {
        return $this->album->getTrackList();
    }
}

This way, by removing your logic that is directly referencing a Track or an Album, and just replacing it so that it uses a TrackInterface or AlbumInterface, you get to use your AlbumTrackReference in any possible case. What you will need is to differentiate the methods between the interfaces a bit.

This won't differentiate the DQL nor the Repository logic, but your services will just ignore the fact that you're passing an Album or an AlbumTrackReference, or a Track or an AlbumTrackReference because you've hidden everything behind an interface :)

Hope this helps!

How to read fetch(PDO::FETCH_ASSOC);

PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.

You can access the name field like this: $user['name'].

I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

if you use spring boot check in application.propertiese this property is commented or remove it if exist.

server.tomcat.additional-tld-skip-patterns=*.jar

How can I avoid ResultSet is closed exception in Java?

Proper jdbc call should look something like:

try { 
    Connection conn;
    Statement stmt;
    ResultSet rs; 

    try {
        conn = DriverManager.getConnection(myUrl,"",""); 
        stmt = conn.createStatement(); 
        rs = stmt.executeQuery(myQuery); 

        while ( rs.next() ) { 
            // process results
        } 

    } catch (SqlException e) { 
        System.err.println("Got an exception! "); 
        System.err.println(e.getMessage()); 
    } finally {
        // you should release your resources here
        if (rs != null) { 
            rs.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if (conn != null) {
            conn.close();
        }
    }
} catch (SqlException e) {
    System.err.println("Got an exception! "); 
    System.err.println(e.getMessage()); 
}

you can close connection (or statement) only after you get result from result set. Safest way is to do it in finally block. However close() could also throe SqlException, hence the other try-catch block.

How to $watch multiple variable change in angular


UPDATE

Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.


This should work independent of the types and values:

$scope.$watch('[age,name]', function () { ... }, true);

You have to set the third parameter to true in this case.

The string concatenation 'age + name' will fail in a case like this:

<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>

Before the user clicks the button the watched value would be 42foo (42 + foo) and after the click 42foo (4 + 2foo). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" />
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script>
        <script>

angular.module('demo', []).controller('MainCtrl', function ($scope) {

    $scope.firstWatchFunctionCounter = 0;
    $scope.secondWatchFunctionCounter = 0;

    $scope.$watch('[age, name]', function () { $scope.firstWatchFunctionCounter++; }, true);
    $scope.$watch('age + name', function () { $scope.secondWatchFunctionCounter++; });
});

describe('Demo module', function () {
    beforeEach(module('demo'));
    describe('MainCtrl', function () {
        it('watch function should increment a counter', inject(function ($controller, $rootScope) {
            var scope = $rootScope.$new();
            scope.age = 42;
            scope.name = 'foo';
            var ctrl = $controller('MainCtrl', { '$scope': scope });
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(1);
            expect(scope.secondWatchFunctionCounter).toBe(1);

            scope.age = 4;
            scope.name = '2foo';
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(2);
            expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail!
        }));
    });
});


(function () {
    var jasmineEnv = jasmine.getEnv();
    var htmlReporter = new jasmine.HtmlReporter();
    jasmineEnv.addReporter(htmlReporter);
    jasmineEnv.specFilter = function (spec) {
        return htmlReporter.specFilter(spec);
    };
    var currentWindowOnload = window.onload;
    window.onload = function() {
        if (currentWindowOnload) {
            currentWindowOnload();
        }
        execJasmine();
    };
    function execJasmine() {
        jasmineEnv.execute();
    }
})();

        </script>
    </head>
    <body></body>
</html>

http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview

PS:

As stated by @reblace in a comment, it is of course possible to access the values:

$scope.$watch('[age,name]', function (newValue, oldValue) {
    var newAge  = newValue[0];
    var newName = newValue[1];
    var oldAge  = oldValue[0];
    var oldName = oldValue[1];
}, true);

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

How to change the CHARACTER SET (and COLLATION) throughout a database?

change database collation:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change table collation:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change column collation:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

What do the parts of utf8mb4_0900_ai_ci mean?

3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 --   _unicode_
v5.20 --  _unicode_520_
v9.0 --   _0900_ (new)
_bin      -- just compare the bits; don't consider case folding, accents, etc
_ci       -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci    -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin         -- simple, fast
_general_ci  -- fails to compare multiple letters; eg ss=ß, somewhat fast
...          -- slower
_0900_       -- (8.0) much faster because of a rewrite

More info:

Javascript search inside a JSON object

I adapted regex to work with JSON.

First, stringify the JSON object. Then, you need to store the starts and lengths of the matched substrings. For example:

"matched".search("ch") // yields 3

For a JSON string, this works exactly the same (unless you are searching explicitly for commas and curly brackets in which case I'd recommend some prior transform of your JSON object before performing regex (i.e. think :, {, }).

Next, you need to reconstruct the JSON object. The algorithm I authored does this by detecting JSON syntax by recursively going backwards from the match index. For instance, the pseudo code might look as follows:

find the next key preceding the match index, call this theKey
then find the number of all occurrences of this key preceding theKey, call this theNumber
using the number of occurrences of all keys with same name as theKey up to position of theKey, traverse the object until keys named theKey has been discovered theNumber times
return this object called parentChain

With this information, it is possible to use regex to filter a JSON object to return the key, the value, and the parent object chain.

You can see the library and code I authored at http://json.spiritway.co/

Environment variable substitution in sed

Actually, the simplest thing (in GNU sed, at least) is to use a different separator for the sed substitution (s) command. So, instead of s/pattern/'$mypath'/ being expanded to s/pattern//my/path/, which will of course confuse the s command, use s!pattern!'$mypath'!, which will be expanded to s!pattern!/my/path!. I’ve used the bang (!) character (or use anything you like) which avoids the usual, but-by-no-means-your-only-choice forward slash as the separator.

How to fill 100% of remaining height?

This can be done with tables:

<table cellpadding="0" cellspacing="0" width="100%" height="100%">
    <tr height="0%"><td>
        <div id="full">
            <!--contents of 1 -->
        </div>
    </td></tr>
    <tr><td>
        <div id="someid">
            <!--contents of 2 -->
        </div>
    </td></tr>
</table>

Then apply css to make someid fill the remaining space:

#someid {
    height: 100%;
}

Now, I can just hear the angry shouts from the crowd, "Oh noes, he's using tables! Feed him to the lions!" Please hear me out.

Unlike the accepted answer which accomplishes nothing aside from making the container div the full height of the page, this solution makes div #2 fill the remaining space as requested in the question. If you need that second div to fill the full height allotted to it, this is currently the only way to do it.

But feel free to prove me wrong, of course! CSS is always better.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

Make sure you clean your project in android studio (or eclipse),

It should solve your issues

What is content-type and datatype in an AJAX request?

From the jQuery documentation - http://api.jquery.com/jQuery.ajax/

contentType When sending data to the server, use this content type.

dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response

"text": A plain text string.

So you want contentType to be application/json and dataType to be text:

$.ajax({
    type : "POST",
    url : /v1/user,
    dataType : "text",
    contentType: "application/json",
    data : dataAttribute,
    success : function() {

    },
    error : function(error) {

    }
});

Site does not exist error for a2ensite

I have just upgraded the Ubuntu Server version from 12.04 LTS to 14.04 LTS.

Indeed, as said above, the .conf extension to Apache 2.4.x is needed to the websites vhost files that resides on sites-available directory.

Before read this question I did not have a clue what was going on with the server.

Pretty nice solution.

Just summarizing I did the following steps on Terminal:

1) Access sites-enabled folder

$ cd /etc/apache2/sites-enabled

2) Because the command a2dissite will not work with deprecated files (without .conf) remove the old website files that was published

$ sudo rm <my-old-website-without-.conf>

3) Rename the website vhost files changing its extension adding .conf to the end

$ sudo mv /etc/apache2/sites-available/mywebsite /etc/apache2/sites-available/mywebsite.conf

4) Republish the new and correct vhost file

$ sudo a2ensite mywebsite.conf

5) Check the website on browser and have fun! :)

Set "Homepage" in Asp.Net MVC

If you don't want to change the router, just go to the HomeController and change MyNewViewHere in the index like this:

    public ActionResult Index()
    {
        return View("MyNewViewHere");
    }

How to upgrade Angular CLI to the latest version

To update Angular CLI to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g @angular/cli
npm cache clean
# if npm version is > 5 then use `npm cache verify` to avoid errors (or to avoid using --force)
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install

Source: Github

Display Image On Text Link Hover CSS Only

add

.hover_img a:hover span {
    display: block;
    width: 350px;
}

to show hover image full size in table change 350 to your size.

Build an iOS app without owning a mac?

Update Intel XDK is no longer available.

You can use Intel XDK with that you can develop and publish an app for iOS without the mac.

Click here for detail.

How to set the env variable for PHP?

You need to put the directory that has php.exe in you WAMP installation into your PATH. It is usually something like C:\wamp\xampp\php

How to build a query string for a URL in C#?

This is another (maybe redundant :-]) way for do that.

The conceptuals are the same of the Vedran answer in this page (take a look here).

But this class is more efficient, because it iterate through all Keys only one time: when ToString is invoked.

The formatting code is also semplified and improved.

Hope that could be helpful.

public sealed class QueryStringBuilder
{
    public QueryStringBuilder()
    {
        this.inner = HttpUtility.ParseQueryString(string.Empty);
    }

    public QueryStringBuilder(string queryString)
    {
        this.inner = HttpUtility.ParseQueryString(queryString);
    }

    public QueryStringBuilder(string queryString, Encoding encoding)
    {
        this.inner = HttpUtility.ParseQueryString(queryString, encoding);
    }

    private readonly NameValueCollection inner;

    public QueryStringBuilder AddKey(string key, string value)
    {
        this.inner.Add(key, value);
        return this;
    }

    public QueryStringBuilder RemoveKey(string key)
    {
        this.inner.Remove(key);
        return this;
    }

    public QueryStringBuilder Clear()
    {
        this.inner.Clear();
        return this;
    }

    public override String ToString()
    {
        if (this.inner.Count == 0)
            return string.Empty;

        var builder = new StringBuilder();

        for (int i = 0; i < this.inner.Count; i++)
        {
            if (builder.Length > 0)
                builder.Append('&');

            var key = this.inner.GetKey(i);
            var values = this.inner.GetValues(i);

            if (key == null || values == null || values.Length == 0)
                continue;

            for (int j = 0; j < values.Length; j++)
            {
                if (j > 0)
                    builder.Append('&');

                builder.Append(HttpUtility.UrlEncode(key));
                builder.Append('=');
                builder.Append(HttpUtility.UrlEncode(values[j]));
            }
        }

        return builder.ToString();
    }
}

Any way to exit bash script, but not quitting the terminal

To write a script that is secure to be run as either a shell script or sourced as an rc file, the script can check and compare $0 and $BASH_SOURCE and determine if exit can be safely used.

Here is a short code snippet for that

[ "X$(basename $0)" = "X$(basename $BASH_SOURCE)" ] && \
    echo "***** executing $name_src as a shell script *****" || \
    echo "..... sourcing $name_src ....."

How to quickly check if folder is empty (.NET)?

Based in Brad Parks code:

    public static bool DirectoryIsEmpty(string path)
    {
        if (System.IO.Directory.GetFiles(path).Length > 0) return false;

        foreach (string dir in System.IO.Directory.GetDirectories(path))
            if (!DirectoryIsEmpty(dir)) return false;

        return true;
    }

ES6 class variable alternatives

Just to add to Benjamin's answer — class variables are possible, but you wouldn't use prototype to set them.

For a true class variable you'd want to do something like the following:

class MyClass {}
MyClass.foo = 'bar';

From within a class method that variable can be accessed as this.constructor.foo (or MyClass.foo).

These class properties would not usually be accessible from to the class instance. i.e. MyClass.foo gives 'bar' but new MyClass().foo is undefined

If you want to also have access to your class variable from an instance, you'll have to additionally define a getter:

class MyClass {
    get foo() {
        return this.constructor.foo;
    }
}

MyClass.foo = 'bar';

I've only tested this with Traceur, but I believe it will work the same in a standard implementation.

JavaScript doesn't really have classes. Even with ES6 we're looking at an object- or prototype-based language rather than a class-based language. In any function X () {}, X.prototype.constructor points back to X. When the new operator is used on X, a new object is created inheriting X.prototype. Any undefined properties in that new object (including constructor) are looked up from there. We can think of this as generating object and class properties.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Sharing a variable between multiple different threads

Both T1 and T2 can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.

See this article for more info.

Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.

And note the pros/cons of using volatile vs more complex means of sharing state.

SELECT with a Replace()

This will work:

SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'

Dynamically add properties to a existing object

Take a look at the ExpandoObject.

For example:

dynamic person = new ExpandoObject();
person.Name = "Mr bar";
person.Sex = "No Thanks";
person.Age = 123;

Additional reading here.

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

Dynamically add item to jQuery Select2 control that uses AJAX

This is a lot easier to do starting in select2 v4. You can create a new Option, and append it to the select element directly. See my codepen or the example below:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    $("#state").select2({_x000D_
      tags: true_x000D_
    });_x000D_
      _x000D_
    $("#btn-add-state").on("click", function(){_x000D_
      var newStateVal = $("#new-state").val();_x000D_
      // Set the value, creating a new option if necessary_x000D_
      if ($("#state").find("option[value=" + newStateVal + "]").length) {_x000D_
        $("#state").val(newStateVal).trigger("change");_x000D_
      } else { _x000D_
        // Create the DOM option that is pre-selected by default_x000D_
        var newState = new Option(newStateVal, newStateVal, true, true);_x000D_
        // Append it to the select_x000D_
        $("#state").append(newState).trigger('change');_x000D_
      } _x000D_
    });  _x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select id="state" class="js-example-basic-single" type="text" style="width:90%">_x000D_
  <option value="AL">Alabama</option>_x000D_
  <option value="WY">Wyoming</option>_x000D_
</select>_x000D_
<br>_x000D_
<br>_x000D_
<input id="new-state" type="text" />_x000D_
<button type="button" id="btn-add-state">Set state value</button>
_x000D_
_x000D_
_x000D_

Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.

How to enable DataGridView sorting when user clicks on the column header?

put this line in your windows form (on load or better in a public method like "binddata" ):

//
// bind the data and make the grid sortable 
//
this.datagridview1.MakeSortable( myenumerablecollection ); 

Put this code in a file called DataGridViewExtensions.cs (or similar)

// MakeSortable extension. 
// this will make any enumerable collection sortable on a datagrid view.  

//
// BEGIN MAKESORTABLE - Mark A. Lloyd
//
// Enables sort on all cols of a DatagridView 

//



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    public static class DataGridViewExtensions
    {
    public static void MakeSortable<T>(
        this DataGridView dataGridView, 
        IEnumerable<T> dataSource,
        SortOrder defaultSort = SortOrder.Ascending, 
        SortOrder initialSort = SortOrder.None)
    {
        var sortProviderDictionary = new Dictionary<int, Func<SortOrder, IEnumerable<T>>>();
        var previousSortOrderDictionary = new Dictionary<int, SortOrder>();
        var itemType = typeof(T);
        dataGridView.DataSource = dataSource;
        foreach (DataGridViewColumn c in dataGridView.Columns)
        {
            object Provider(T info) => itemType.GetProperty(c.Name)?.GetValue(info);
            sortProviderDictionary[c.Index] = so => so != defaultSort ? 
                dataSource.OrderByDescending<T, object>(Provider) : 
                dataSource.OrderBy<T,object>(Provider);
            previousSortOrderDictionary[c.Index] = initialSort;
        }

        async Task DoSort(int index)
        {

            switch (previousSortOrderDictionary[index])
            {
                case SortOrder.Ascending:
                    previousSortOrderDictionary[index] = SortOrder.Descending;
                    break;
                case SortOrder.None:
                case SortOrder.Descending:
                    previousSortOrderDictionary[index] = SortOrder.Ascending;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            IEnumerable<T> sorted = null;
            dataGridView.Cursor = Cursors.WaitCursor;
            dataGridView.Enabled = false;
            await Task.Run(() => sorted = sortProviderDictionary[index](previousSortOrderDictionary[index]).ToList());
            dataGridView.DataSource = sorted;
            dataGridView.Enabled = true;
            dataGridView.Cursor = Cursors.Default;

        }

        dataGridView.ColumnHeaderMouseClick+= (object sender, DataGridViewCellMouseEventArgs e) => DoSort(index: e.ColumnIndex);
    }
}

"error: assignment to expression with array type error" when I assign a struct field (C)

You are facing issue in

 s1.name="Paolo";

because, in the LHS, you're using an array type, which is not assignable.

To elaborate, from C11, chapter §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

and, regarding the modifiable lvalue, from chapter §6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, [...]

You need to use strcpy() to copy into the array.

That said, data s1 = {"Paolo", "Rossi", 19}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]

Use grep --exclude/--include syntax to not grep through certain files

grep 2.5.3 introduced the --exclude-dir parameter which will work the way you want.

grep -rI --exclude-dir=\.svn PATTERN .

You can also set an environment variable: GREP_OPTIONS="--exclude-dir=\.svn"

I'll second Andy's vote for ack though, it's the best.

Check if a variable is of function type

I found that when testing native browser functions in IE8, using toString, instanceof, and typeof did not work. Here is a method that works fine in IE8 (as far as I know):

function isFn(f){
    return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);

Alternatively, you can check for native functions using:

"getElementById" in document

Though, I have read somewhere that this will not always work in IE7 and below.

How to get min, seconds and milliseconds from datetime.now() in python?

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

How to align footer (div) to the bottom of the page?

A simple solution that i use, works from IE8+

Give min-height:100% on html so that if content is less then still page takes full view-port height and footer sticks at bottom of page. When content increases the footer shifts down with content and keep sticking to bottom.

JS fiddle working Demo: http://jsfiddle.net/3L3h64qo/2/

Css

html{
  position:relative; 
  min-height: 100%;
}
/*Normalize html and body elements,this style is just good to have*/
html,body{
  margin:0;
  padding:0;
}
.pageContentWrapper{
  margin-bottom:100px;/* Height of footer*/
} 
.footer{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height:100px;
    background:#ccc;
}

Html

   <html>
    <body>
        <div class="pageContentWrapper">
            <!-- All the page content goes here-->
        </div>
        <div class="footer">
        </div>
    </body>
    </html>

How do I obtain a Query Execution Plan in SQL Server?

Explaining execution plan can be very detailed and takes up quite a reading time, but in summary if you use 'explain' before the query it should give you a lot of info including which parts were executed first and so. if you wanna read a bit more details about this, I compiled a small blog about this which points you as well to the right refs. https://medium.com/swlh/jetbrains-datagrip-explain-plan-ac406772c470

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

How do I get the day of week given a date?

Here is my python3 implementation.

months = {'jan' : 1, 'feb' : 4, 'mar' : 4, 'apr':0, 'may':2, 'jun':5, 'jul':6, 'aug':3, 'sep':6, 'oct':1, 'nov':4, 'dec':6}
dates = {'Sunday':1, 'Monday':2, 'Tuesday':3, 'Wednesday':4, 'Thursday':5, 'Friday':6, 'Saterday':0}
ranges = {'1800-1899':2, '1900-1999':0, '2000-2099':6, '2100-2199':4, '2200-2299':2}

def getValue(val, dic):
    if(len(val)==4):
        for k,v in dic.items():
            x,y=int(k.split('-')[0]),int(k.split('-')[1])
            val = int(val)
            if(val>=x and val<=y):
                return v
    else:
        return dic[val]

def getDate(val):
    return (list(dates.keys())[list(dates.values()).index(val)]) 



def main(myDate):
    dateArray = myDate.split('-')
    # print(dateArray)
    date,month,year = dateArray[2],dateArray[1],dateArray[0]
    # print(date,month,year)

    date = int(date)
    month_v = getValue(month, months)
    year_2 = int(year[2:])
    div = year_2//4
    year_v = getValue(year, ranges)
    sumAll = date+month_v+year_2+div+year_v
    val = (sumAll)%7
    str_date = getDate(val)

    print('{} is a {}.'.format(myDate, str_date))

if __name__ == "__main__":
    testDate = '2018-mar-4'
    main(testDate)

Batch file to copy files from one folder to another folder

If you want to copy file not using absolute path, relative path in other words:

Don't forget to write backslash in the path AND NOT slash

Example:

copy children-folder\file.something .\other-children-folder

PS: absolute path can be retrieved using these wildcards called "batch parameters"

@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"

Check documentation here about copy: https://technet.microsoft.com/en-us/library/bb490886.aspx

And also here for batch parameters documentation: https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

How to emulate GPS location in the Android Emulator?

If you are using eclipse then using Emulator controller you can manually set latitude and longitude and run your map based app in emulator

How to sort a data frame by date

The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ] 

List all tables in postgresql information_schema

The "\z" COMMAND is also a good way to list tables when inside the interactive psql session.

eg.

# psql -d mcdb -U admin -p 5555
mcdb=# /z
                           Access privileges for database "mcdb"
 Schema |              Name              |   Type   |           Access privileges
--------+--------------------------------+----------+---------------------------------------
 public | activities                     | table    |
 public | activities_id_seq              | sequence |
 public | activities_users_mapping       | table    |
[..]
 public | v_schedules_2                  | view     | {admin=arwdxt/admin,viewuser=r/admin}
 public | v_systems                      | view     |
 public | vapp_backups                   | table    |
 public | vm_client                      | table    |
 public | vm_datastore                   | table    |
 public | vmentity_hle_map               | table    |
(148 rows)

How to push changes to github after jenkins build completes?

I followed the below Steps. It worked for me.

In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.

enter image description here

Download Git Publisher Plugin and Configure as shown below snapshot.

enter image description here

Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Send and receive messages through NSNotificationCenter in Objective-C?

This one helped me:

// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(showMainMenu:) 
                                                 name:@"loginComplete" object:nil];


// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginComplete" object:nil];


// the function specified in the same class where we defined the addObserver
- (void)showMainMenu:(NSNotification *)note {
    NSLog(@"Received Notification - Someone seems to have logged in"); 
}

Source: http://www.smipple.net/snippet/Sounden/Simple%20NSNotificationCenter%20example

How to get the azure account tenant Id?

This answer was provided on Microsoft's website, last updated on 3/21/2018:

https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

In short, here are the screenshots from the walkthrough:

  1. Select Azure Active Directory.

Azure Active Directory

  1. To get the tenant ID, select Properties for your Azure AD tenant.

Select Properties

  1. Copy the Directory ID. This value is your tenant ID.

Copy the Directory ID, this is the tenant ID.

Hope this helps.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

All PLEASE note what Tyler said

Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won't get back

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

I had this error today with Amazon Cloudfront. It was because the cname I used (e.g cdn.example.com) was not added to the distribution settings under "alternate cnames", I only had cdn.example.com forwarded to the cloudfront domain in my site/hosting control panel, but you need to add it to Amazon CloudFront panel too.

Create component to specific module with Angular-CLI

ng g component nameComponent --module=app.module.ts

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

I liked solution of @picciano & @Maksim Kniazev. We can also create annular border with following:

func addExternalAnnularBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.white) {
    let externalBorder = CALayer()
    externalBorder.frame = CGRect(x: -borderWidth*2, y: -borderWidth*2, width: frame.size.width + 4 * borderWidth, height: frame.size.height + 4 * borderWidth)
    externalBorder.borderColor = borderColor.cgColor
    externalBorder.borderWidth = borderWidth
    externalBorder.cornerRadius = (frame.size.width + 4 * borderWidth) / 2
    externalBorder.name = Constants.ExternalBorderName
    layer.insertSublayer(externalBorder, at: 0)
    layer.masksToBounds = false
}

Undefined symbols for architecture x86_64 on Xcode 6.1

It turned out I forgot to write my @implementation part.

Convert to date format dd/mm/yyyy

Try this:

$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

write newline into a file

the other answers should work. however I wanna mention

from java doc:

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

reading your method codes, you are about to write String to the file, what you were doing is convert String to raw bytes, then write so I think using FileWriter is not a bad idea.

And for the newline problem, Writer has method .write(String), which is convenient to use.

ModuleNotFoundError: No module named 'sklearn'


Brief Introduction


When using Anaconda, one needs to be aware of the environment that one is working.

Then, in Anaconda Prompt (base) one needs to use the following code:

conda $command -n $ENVIRONMENT_NAME $IDE/package/module

$command - Command that I intend to use (consult documentation for general commands)

$ENVIRONMENT NAME - The name of your environment (if one is working in the root, conda $command $IDE/package/module is enough)

$IDE/package/module - The name of the IDE or package or module


Solution


If one wants to install it in the root and one follows the requirements - (Python (>= 2.7 or >= 3.4), NumPy (>= 1.8.2), SciPy (>= 0.13.3).) - the following will solve the problem:

conda install scikit-learn

Let's say that one is working in the environment with the name ML.

Then the following will solve one's problem:

conda install -n ML scikit-learn

Note: If one needs to install/update packages, the logic is the same as mentioned in the introduction. If you need more information on Anaconda Packages, check the documentation.


If the above doesn't work, on Anaconda Prompt one can also use pip (here's how to pip install scikit-learn) so the following may help

pip install scikit-learn

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

It is called the extended call syntax. From the documentation:

If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

and:

If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.

Fatal error: Maximum execution time of 300 seconds exceeded

If you are on xampp and using phpMyadmin to import large sql files and you have increased max_execution time, max file upload limit and everything needed And If none of the above answers work for you come here

Go to your xampp folder, in my case here is the relative path to the file that I need to modify: C:\xampp\phpMyAdmin\libraries\config.default.php

/** * maximum execution time in seconds (0 for no limit) * * @global integer $cfg['ExecTimeLimit'] * by defautlt 300 is the value * change it to 0 for unlimited * time is seconds * Line 709 for me */ $cfg['ExecTimeLimit'] = 0;

Remove whitespaces inside a string in javascript

Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim() work.

update

This answer only applies to older browsers. Newer browsers apparently support trim() natively.

Connection Strings for Entity Framework

Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.

CREATE TABLE [dbo].[SystemConfig]  
    (  
      [Id] [int] IDENTITY(1, 1)  
                 NOT NULL ,  
      [AppName] [varchar](128) NULL ,  
      [ScopeName] [varchar](128) NOT NULL ,  
      [Key] [varchar](256) NOT NULL ,  
      [Value] [varchar](MAX) NOT NULL ,  
      CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )  
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
               ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]  
    )  
ON  [PRIMARY]  

GO  

SET ANSI_PADDING OFF  
GO  

ALTER TABLE [dbo].[SystemConfig] ADD  CONSTRAINT [DF_SystemConfig_ScopeName]  DEFAULT ('SystemConfig') FOR [ScopeName]  
GO 

With such configuration table you can create rows like such: enter image description here

Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.

What is the difference between a stored procedure and a view?

Main difference is that when you are querying a view then it's definition is pasted into your query. Procedure could also give results of query, but it is compiled and for so faster. Another option are indexed views..

oracle diff: how to compare two tables?

I used Oracle SQL developer to export the table/s into CSV format and then did the comparison using WinMerge.

Getting the folder name from a path

This is ugly but avoids allocations:

private static string GetFolderName(string path)
{
    var end = -1;
    for (var i = path.Length; --i >= 0;)
    {
        var ch = path[i];
        if (ch == System.IO.Path.DirectorySeparatorChar ||
            ch == System.IO.Path.AltDirectorySeparatorChar ||
            ch == System.IO.Path.VolumeSeparatorChar)
        {
            if (end > 0)
            {
                return path.Substring(i + 1, end - i - 1);
            }

            end = i;
        }
    }

    if (end > 0)
    {
        return path.Substring(0, end);
    }

    return path;
}

Garbage collector in Android

My app manage a lot of images and it died with a OutOfMemoryError. This helped me. In the Manifest.xml Add

<application
....
   android:largeHeap="true"> 

Git: force user and password prompt

This is most likely because you have multiple accounts, like one private, one for work with GitHub.

SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub

SOLUTION OnMac, issue following on terminal:

git remote set-url origin https://[email protected]/username/repo-name.git

by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.

indexOf Case Sensitive?

Here is my solution which does not allocate any heap memory, therefore it should be significantly faster than most of the other implementations mentioned here.

public static int indexOfIgnoreCase(final String haystack,
                                    final String needle) {
    if (needle.isEmpty() || haystack.isEmpty()) {
        // Fallback to legacy behavior.
        return haystack.indexOf(needle);
    }

    for (int i = 0; i < haystack.length(); ++i) {
        // Early out, if possible.
        if (i + needle.length() > haystack.length()) {
            return -1;
        }

        // Attempt to match substring starting at position i of haystack.
        int j = 0;
        int ii = i;
        while (ii < haystack.length() && j < needle.length()) {
            char c = Character.toLowerCase(haystack.charAt(ii));
            char c2 = Character.toLowerCase(needle.charAt(j));
            if (c != c2) {
                break;
            }
            j++;
            ii++;
        }
        // Walked all the way to the end of the needle, return the start
        // position that this was found.
        if (j == needle.length()) {
            return i;
        }
    }

    return -1;
}

And here are the unit tests that verify correct behavior.

@Test
public void testIndexOfIgnoreCase() {
    assertThat(StringUtils.indexOfIgnoreCase("A", "A"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("a", "A"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("A", "a"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("a", "a"), is(0));

    assertThat(StringUtils.indexOfIgnoreCase("a", "ba"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase("ba", "a"), is(1));

    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", " Royal Blue"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase(" Royal Blue", "Royal Blue"), is(1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "royal"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "oyal"), is(1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "al"), is(3));
    assertThat(StringUtils.indexOfIgnoreCase("", "royal"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", ""), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "BLUE"), is(6));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "BIGLONGSTRING"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "Royal Blue LONGSTRING"), is(-1));  
}

OSX - How to auto Close Terminal window after the "exit" command executed.

Use the osascript command in your code as icktoofay mentioned: osascript -e 'tell application "Terminal" to quit'

Then, open Terminal preferences, go to Settings > Shell, and set "Prompt before closing:" to "Never." Terminal should now quit completely (not remain open in your dock) and ignore the prompt before quitting. If you have only one Terminal window open and the osascript command is your last line of code, it should wait for whatever command you ran before to finish.

This would not be ideal if you are running scripts in the same window or other windows in the background (for instance, you may run a command in the background and continue using the current window for other commands if the first command is followed by an ampersand); be careful!

If you wrap the osascript code in a shell script file, you can probably call it with whatever pithy file-name you give it---as long as it is in Terminal's search path (run echo $PATH to see where Terminal looks for scripts).

Easier way to debug a Windows service

This YouTube video by Fabio Scopel explains how to debug a Windows service quite nicely... the actual method of doing it starts at 4:45 in the video...

Here is the code explained in the video... in your Program.cs file, add the stuff for the Debug section...

namespace YourNamespace
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
#if DEBUG
            Service1 myService = new Service1();
            myService.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
#endif

        }
    }
}

In your Service1.cs file, add the OnDebug() method...

    public Service1()
    {
        InitializeComponent();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    protected override void OnStart(string[] args)
    {
        // your code to do something
    }

    protected override void OnStop()
    {
    }

How it works

Basically you have to create a public void OnDebug() that calls the OnStart(string[] args) as it's protected and not accessible outside. The void Main() program is added with #if preprocessor with #DEBUG.

Visual Studio defines DEBUG if project is compiled in Debug mode.This will allow the debug section(below) to execute when the condition is true

Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

And it will run just like a console application, once things go OK you can change the mode Release and the regular else section will trigger the logic

How To: Execute command line in C#, get STD OUT results

 System.Diagnostics.ProcessStartInfo psi =
   new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
 psi.RedirectStandardOutput = true;
 psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 psi.UseShellExecute = false;
 System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
 System.IO.StreamReader myOutput = proc.StandardOutput;
 proc.WaitForExit(2000);
 if (proc.HasExited)
  {
      string output = myOutput.ReadToEnd();
 }

How do I get the number of days between two dates in JavaScript?

I found this question when I want do some calculate on two date, but the date have hours and minutes value, I modified @michael-liu 's answer to fit my requirement, and it passed my test.

diff days 2012-12-31 23:00 and 2013-01-01 01:00 should equal 1. (2 hour) diff days 2012-12-31 01:00 and 2013-01-01 23:00 should equal 1. (46 hour)

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

var millisecondsPerDay = 24 * 60 * 60 * 1000;
function diffDays(startDate, endDate) {
    return Math.floor(treatAsUTC(endDate) / millisecondsPerDay) - Math.floor(treatAsUTC(startDate) / millisecondsPerDay);
}

Print a file's last modified date in Bash

Best is

date -r filename +"%Y-%m-%d %H:%M:%S"

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

Converting two lists into a matrix

You can use np.c_

np.c_[[1,2,3], [4,5,6]]

It will give you:

np.array([[1,4], [2,5], [3,6]])

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How to manually set REFERER header in Javascript?

If you want to change the referer (url) header that will be sent to the server when a user clicks an anchor or iframe is opened, you can do it without any hacks. Simply do history.replaceState, you will change the url as it will appear in the browser bar and also the referer that will be send to the server.

Determine Whether Integer Is Between Two Other Integers?

Your code snippet,

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

actually checks if number is larger than both 10000 and 30000.

Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:

if 10000 <= number <= 30000:
    print ("you have to pay 5% taxes")

This Python feature is further described in the Python documentation.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

Auto-fit TextView for Android

Ok I have used the last week to massively rewrite my code to precisely fit your test. You can now copy this 1:1 and it will immediately work - including setSingleLine(). Please remember to adjust MIN_TEXT_SIZE and MAX_TEXT_SIZE if you're going for extreme values.

Converging algorithm looks like this:

for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

    // Go to the mean value...
    testSize = (upperTextSize + lowerTextSize) / 2;

    // ... inflate the dummy TextView by setting a scaled textSize and the text...
    mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
    mTestView.setText(text);

    // ... call measure to find the current values that the text WANTS to occupy
    mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int tempHeight = mTestView.getMeasuredHeight();

    // ... decide whether those values are appropriate.
    if (tempHeight >= targetFieldHeight) {
        upperTextSize = testSize; // Font is too big, decrease upperSize
    }
    else {
        lowerTextSize = testSize; // Font is too small, increase lowerSize
    }
}

And the whole class can be found here.

The result is very flexible now. This works the same declared in xml like so:

<com.example.myProject.AutoFitText
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="4"
    android:text="@string/LoremIpsum" />

... as well as built programmatically like in your test.

I really hope you can use this now. You can call setText(CharSequence text) now to use it by the way. The class takes care of stupendously rare exceptions and should be rock-solid. The only thing that the algorithm does not support yet is:

  • Calls to setMaxLines(x) where x >= 2

But I have added extensive comments to help you build this if you wish to!


Please note:

If you just use this normally without limiting it to a single line then there might be word-breaking as you mentioned before. This is an Android feature, not the fault of the AutoFitText. Android will always break words that are too long for a TextView and it's actually quite a convenience. If you want to intervene here than please see my comments and code starting at line 203. I have already written an adequate split and the recognition for you, all you'd need to do henceforth is to devide the words and then modify as you wish.

In conclusion: You should highly consider rewriting your test to also support space chars, like so:

final Random _random = new Random();
final String ALLOWED_CHARACTERS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
final int textLength = _random.nextInt(80) + 20;
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < textLength; ++i) {
    if (i % 7 == 0 && i != 0) {
        builder.append(" ");
    }
    builder.append(ALLOWED_CHARACTERS.charAt(_random.nextInt(ALLOWED_CHARACTERS.length())));
}
((AutoFitText) findViewById(R.id.textViewMessage)).setText(builder.toString());

This will produce very beutiful (and more realistic) results.
You will find commenting to get you started in this matter as well.

Good luck and best regards

Python how to plot graph sine wave

import numpy as np
import matplotlib.pyplot as plt

F = 5.e2          # No. of cycles per second, F = 500 Hz
T = 2.e-3         # Time period, T = 2 ms
Fs = 50.e3        # No. of samples per second, Fs = 50 kHz
Ts = 1./Fs        # Sampling interval, Ts = 20 us
N = int(T/Ts)     # No. of samples for 2 ms, N = 100

t = np.linspace(0, T, N)
signal = np.sin(2*np.pi*F*t)

plt.plot(t, signal)
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

Javascript change color of text and background to input value

Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.

First considerations are about mixing HTML, Javascript and CSS:

Why is using onClick() in HTML a bad practice?

Unobtrusive Javascript

Inline Styles vs Classes

I will be removing inline content and splitting these into their appropriate files.

Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.

Your function changeBackground sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.

CSS

#TheForm {
    margin-left: 396px;
}
#submitColor {
    margin-left: 48px;
    margin-top: 5px;
}

HTML

<form id="TheForm">
    <input id="color" type="text" />
    <br/>
    <input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>

Javascript

function changeBackground() {
    var color = document.getElementById("color").value; // cached

    // The working function for changing background color.
    document.bgColor = color;

    // The code I'd like to use for changing the text simultaneously - however it does not work.
    document.getElementById("coltext").style.color = color;
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Source: w3schools

Color Values

CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).

Hex values are written as 3 double digit numbers, starting with a # sign.

Update: as pointed out by @Ian

Hex can be either 3 or 6 characters long

Source: W3C

Numerical color values

The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.

For regex testing, I will use this pattern

/^#(?:[0-9a-f]{3}){1,2}$/i

but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern

function changeBackground() {
    var color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;

    if (rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Hex Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Here is a further modification that will allow colours by name along with by hex.

function changeBackground() {
    var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
        color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
        formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();

    if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

It seems that now you can just mark the method parameter with @RequestParam and it will do the job for you.

@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam Map<String, String> body ) {
  //work with Map
}

Regarding 'main(int argc, char *argv[])'

The comp.lang.c FAQ deals with the question

"What's the correct declaration of main()?"
in Question 11.12a.

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

After struggling for a whole evening I finally got this to work. After some debugging I found the problem I was walking into was that my client was sending a so called preflight Options request to check if the application was allowed to send a post request with the origin, methods and headers provided. I didn't want to use Owin or an APIController, so I started digging and came up with the following solution with just an ActionFilterAttribute. Especially the "Access-Control-Allow-Headers" part is very important, as the headers mentioned there do have to match the headers your request will send.

using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyNamespace
{
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequest request = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            // check for preflight request
            if (request.Headers.AllKeys.Contains("Origin") && request.HttpMethod == "OPTIONS")
            {
                response.AppendHeader("Access-Control-Allow-Origin", "*");
                response.AppendHeader("Access-Control-Allow-Credentials", "true");
                response.AppendHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
                response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-RequestDigest, Cache-Control, Content-Type, Accept, Access-Control-Allow-Origin, Session, odata-version");
                response.End();
            }
            else
            {
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.Cache.SetNoStore();

                response.AppendHeader("Access-Control-Allow-Origin", "*");
                response.AppendHeader("Access-Control-Allow-Credentials", "true");
                if (request.HttpMethod == "POST")
                {
                    response.AppendHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
                    response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-RequestDigest, Cache-Control, Content-Type, Accept, Access-Control-Allow-Origin, Session, odata-version");
                }

                base.OnActionExecuting(filterContext);
            }
        }
    }
}

Finally, my MVC action method looks like this. Important here is to also mention the Options HttpVerbs, because otherwise the preflight request will fail.

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Options)]
[AllowCrossSiteJson]
public async Task<ActionResult> Create(MyModel model)
{
    return Json(await DoSomething(model));
}

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

How to add headers to OkHttp request interceptor?

you can do it this way

private String GET(String url, Map<String, String> header) throws IOException {
        Headers headerbuild = Headers.of(header);
        Request request = new Request.Builder().url(url).headers(headerbuild).
                        build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

Calling a function on bootstrap modal open

You can use belw code for show and hide bootstrap model.

$('#my-model').on('shown.bs.modal', function (e) {
  // do something here...
})

and if you want to hide model then you can use below code.

$('#my-model').on('hidden.bs.modal', function() {
    // do something here...
});

I hope this answer is useful for your project.

How to style the option of an html "select" element?

As already mentioned, the only way is to use a plugin that replaces <select> functionality.

A list of jQuery plugins: http://plugins.jquery.com/tag/select/

Take a look at the example using Select2 plugin: http://jsfiddle.net/swsLokfj/23/

Python Create unix timestamp five minutes in the future

Another way is to use calendar.timegm:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return calendar.timegm(future.timetuple())

It's also more portable than %s flag to strftime (which doesn't work on Windows).

How to encode the plus (+) symbol in a URL

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

POST data with request module on Node.JS

I have to get the data from a POST method of the PHP code. What worked for me was:

const querystring = require('querystring');
const request = require('request');

const link = 'http://your-website-link.com/sample.php';
let params = { 'A': 'a', 'B': 'b' };

params = querystring.stringify(params); // changing into querystring eg 'A=a&B=b'

request.post({
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // important to interect with PHP
  url: link,
  body: params,
}, function(error, response, body){
  console.log(body);
});

python getoutput() equivalent in subprocess

Use subprocess.Popen:

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)

Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.

Why can't overriding methods throw exceptions broader than the overridden method?

To illustrate this, consider:

public interface FileOperation {
  void perform(File file) throws FileNotFoundException;
}

public class OpenOnly implements FileOperation {
  void perform(File file) throws FileNotFoundException {
    FileReader r = new FileReader(file);
  }
}

Suppose you then write:

public class OpenClose implements FileOperation {
  void perform(File file) throws FileNotFoundException {
    FileReader r = new FileReader(file);
    r.close();
  }
}

This will give you a compilation error, because r.close() throws an IOException, which is broader than FileNotFoundException.

To fix this, if you write:

public class OpenClose implements FileOperation {
  void perform(File file) throws IOException {
    FileReader r = new FileReader(file);
    r.close();
  }
}

You will get a different compilation error, because you are implementing the perform(...) operation, but throwing an exception not included in the interface's definition of the method.

Why is this important? Well a consumer of the interface may have:

FileOperation op = ...;
try {
  op.perform(file);
}
catch (FileNotFoundException x) {
  log(...);
}

If the IOException were allowed to be thrown, the client's code is nolonger correct.

Note that you can avoid this sort of issue if you use unchecked exceptions. (I am not suggesting you do or don't, that is a philosophical issue)

Laravel 5 Class 'form' not found

Begin by installing this package through Composer. Run the following from the terminal:

composer require "laravelcollective/html":"^5.3.0"

Next, add your new provider to the providers array of config/app.php:

'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
  ],

Finally, add two class aliases to the aliases array of config/app.php:

'aliases' => [
    // ...
      'Form' => Collective\Html\FormFacade::class,
      'Html' => Collective\Html\HtmlFacade::class,
    // ...
  ],

SRC:

https://laravelcollective.com/docs/5.3/html

Node.js: Gzip compression?

How about this?

node-compress
A streaming compression / gzip module for node.js
To install, ensure that you have libz installed, and run:
node-waf configure
node-waf build
This will put the compress.node binary module in build/default.
...

Converting NumPy array into Python List structure?

The numpy .tolist method produces nested lists if the numpy array shape is 2D.

if flat lists are desired, the method below works.

import numpy as np
from itertools import chain

a = [1,2,3,4,5,6,7,8,9]
print type(a), len(a), a
npa = np.asarray(a)
print type(npa), npa.shape, "\n", npa
npa = npa.reshape((3, 3))
print type(npa), npa.shape, "\n", npa
a = list(chain.from_iterable(npa))
print type(a), len(a), a`

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

_x000D_
_x000D_
    var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");_x000D_
    alert(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_

How can I call the 'base implementation' of an overridden virtual method?

You can't do it by C#, but you can edit MSIL.

IL code of your Main method:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] class MsilEditing.A a)
    L_0000: nop 
    L_0001: newobj instance void MsilEditing.B::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: callvirt instance void MsilEditing.A::X()
    L_000d: nop 
    L_000e: ret 
}

You should change opcode in L_0008 from callvirt to call

L_0008: call instance void MsilEditing.A::X()

Java Date vs Calendar

A little bit late at party, but Java has a new Date Time API in JDK 8. You may want to upgrade your JDK version and embrace the standard. No more messy date/calendar, no more 3rd party jars.

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

Here's an answer to a 2-year old question in case it helps anyone else with the same problem.

Based upon the information you've provided, a permissions issue on the file (or files) would be one cause of the same 500 Internal Server Error.

To check whether this is the problem (if you can't get more detailed information on the error), navigate to the directory in Terminal and run the following command:

ls -la

If you see limited permissions - e.g. -rw-------@ against your file, then that's your problem.

The solution then is to run chmod 644 on the problem file(s) or chmod 755 on the directories. See this answer - How do I set chmod for a folder and all of its subfolders and files? - for a detailed explanation of how to change permissions.

By way of background, I had precisely the same problem as you did on some files that I had copied over from another Mac via Google Drive, which transfer had stripped most of the permissions from the files.

The screenshot below illustrates. The index.php file with the -rw-------@ permissions generates a 500 Internal Server Error, while the index_finstuff.php (precisely the same content!) with -rw-r--r--@ permissions is fine. Changing the permissions on the index.php immediately resolves the problem.

In other words, your PHP code and the server may both be fine. However, the limited read permissions on the file may be forbidding the server from displaying the content, causing the 500 Internal Server Error message to be displayed instead.

enter image description here

Read line by line in bash script

xargs is the most flexible solution for splitting output into command arguments.

It is also very human readable and easy to use due to its simple parameterisation.

Format is xargs -n $NUMLINES mycommand.

For example, to echo each individual line in a file /tmp/tmp.txt you'd do:

cat /tmp/tmp.txt | xargs -n 1 echo

Or to diff each successive pair of files listed as lines in a file of the above name you'd do:

cat /tmp/tmp.txt | xargs -n 2 diff

The -n 2 instructs xargs to consume and pass as separate arguments two lines of what you've piped into it at a time.

You can tailor xargs to split on delimiters besides carriage return/newline.

Use man xargs and google to find out more about the power of this versatile utility.

height: 100% for <div> inside <div> with display: table-cell

table{
   height:1px;
}

table > td{
   height:100%;
}

table > td > .inner{
   height:100%;
}

Confirmed working on:

  • Chrome 60.0.3112.113, 63.0.3239.84
  • Firefox 55.0.3, 57.0.1
  • Internet Explorer 11

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

How to get < span > value?

var test = document.getElementById( 'test' );

// To get the text only, you can use "textContent"
console.log( test.textContent ); // "1 2 3 4"

textContent is the standard way. innerText is the property to use for legacy IE. If you want something as cross browser as possible, recursively use nodeValue.

How do I loop through or enumerate a JavaScript object?

In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3",
    *[Symbol.iterator]() {
        yield *Object.keys(this);
    }
};

[...p] //["p1", "p2", "p3"]

this will give the same result as using for...in es6 loop.

for(var key in p) {
    console.log(key);
}

But its important to know the capabilities you now have using es6!

Capture key press without placing an input element on the page?

Detect key press, including key combinations:

window.addEventListener('keydown', function (e) {
  if (e.ctrlKey && e.keyCode == 90) {
    // Ctrl + z pressed
  }
});

Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

Multi column forms with fieldsets

I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.

<div class="form-group">
    <div class="col-sm-12">
        <label for="user_login">Username</label>
        <input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
    </div>
</div>

Check out this demo.

Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.

<form action="#" method="post" class="form-horizontal">

Check out this demo.

When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.

error C2039: 'string' : is not a member of 'std', header file problem

Take care not to include

#include <string.h> 

but only

#include <string>

It took me 1 hour to find this in my code.

Hope this can help

In Java, how do I check if a string contains a substring (ignoring case)?

I also favor the RegEx solution. The code will be much cleaner. I would hesitate to use toLowerCase() in situations where I knew the strings were going to be large, since strings are immutable and would have to be copied. Also, the matches() solution might be confusing because it takes a regular expression as an argument (searching for "Need$le" cold be problematic).

Building on some of the above examples:

public boolean containsIgnoreCase( String haystack, String needle ) {
  if(needle.equals(""))
    return true;
  if(haystack == null || needle == null || haystack .equals(""))
    return false; 

  Pattern p = Pattern.compile(needle,Pattern.CASE_INSENSITIVE+Pattern.LITERAL);
  Matcher m = p.matcher(haystack);
  return m.find();
}

example call: 

String needle = "Need$le";
String haystack = "This is a haystack that might have a need$le in it.";
if( containsIgnoreCase( haystack, needle) ) {
  System.out.println( "Found " + needle + " within " + haystack + "." );
}

(Note: you might want to handle NULL and empty strings differently depending on your needs. I think they way I have it is closer to the Java spec for strings.)

Speed critical solutions could include iterating through the haystack character by character looking for the first character of the needle. When the first character is matched (case insenstively), begin iterating through the needle character by character, looking for the corresponding character in the haystack and returning "true" if all characters get matched. If a non-matched character is encountered, resume iteration through the haystack at the next character, returning "false" if a position > haystack.length() - needle.length() is reached.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Python loop for inside lambda

anon and chepner's answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).

However, you can get the print function very easily in python 2.x by importing from the standard library's future module. Check it out:

>>>from __future__ import print_function
>>>
>>>iterable = ["a","b","c"]
>>>map(print, iterable)
a
b
c
[None, None, None]
>>>

I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]'s output (you are interested in the side-effects only, I assume):

>>>_ = map(print, iterable)
a
b
c
>>>

Jquery to change form action

Try this:

$('#button1').click(function(){
   $('#formId').attr('action', 'page1');
});


$('#button2').click(function(){
   $('#formId').attr('action', 'page2');
});

How to replace a set of tokens in a Java String?

You could try using a templating library like Apache Velocity.

http://velocity.apache.org/

Here is an example:

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;

public class TemplateExample {
    public static void main(String args[]) throws Exception {
        Velocity.init();

        VelocityContext context = new VelocityContext();
        context.put("name", "Mark");
        context.put("invoiceNumber", "42123");
        context.put("dueDate", "June 6, 2009");

        String template = "Hello $name. Please find attached invoice" +
                          " $invoiceNumber which is due on $dueDate.";
        StringWriter writer = new StringWriter();
        Velocity.evaluate(context, writer, "TemplateName", template);

        System.out.println(writer);
    }
}

The output would be:

Hello Mark. Please find attached invoice 42123 which is due on June 6, 2009.

What does 'const static' mean in C and C++?

According to C99/GNU99 specification:

  • static

    • is storage-class specifier

    • objects of file level scope by default has external linkage

    • objects of file level scope with static specifier has internal linkage
  • const

    • is type-qualifier (is a part of type)

    • keyword applied to immediate left instance - i.e.

      • MyObj const * myVar; - unqualified pointer to const qualified object type

      • MyObj * const myVar; - const qualified pointer to unqualified object type

    • Leftmost usage - applied to the object type, not variable

      • const MyObj * myVar; - unqualified pointer to const qualified object type

THUS:

static NSString * const myVar; - constant pointer to immutable string with internal linkage.

Absence of the static keyword will make variable name global and might lead to name conflicts within the application.

Android and setting alpha for (image) view alpha

Maybe a helpful alternative for a plain-colored background:

Put a LinearLayout over the ImageView and use the LinearLayout as a opacity filter. In the following a small example with a black background:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000" >

<RelativeLayout
    android:id="@+id/relativeLayout2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_stop_big" />

    <LinearLayout
        android:id="@+id/opacityFilter"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#CC000000"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

Vary the android:background attribute of the LinearLayout between #00000000 (fully transparent) and #FF000000 (fully opaque).

PostgreSQL: Why psql can't connect to server?

The error means that the Postgres server is not running. Try starting it:

sudo systemctl start postgresql

Make sure that the server starts on boot:

sudo systemctl enable postgresql

Python - OpenCV - imread - Displaying Image

In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation

The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.

cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE) where each window is related to image container by the name arg, make sure to use same name

eg:

import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)

Correct MIME Type for favicon.ico?

I think the root for this confusion is well explained in this wikipedia article.

While the IANA-registered MIME type for ICO files is image/vnd.microsoft.icon, it was submitted to IANA in 2003 by a third party and is not recognised by Microsoft software, which uses image/x-icon instead.

If even the inventor of the ICO format does not use the official MIME type, I will use image/x-icon, too.

WebAPI Multiple Put/Post parameters

Nice question and comments - learnt much from the replies here :)

As an additional example, note that you can also mix body and routes e.g.

[RoutePrefix("api/test")]
public class MyProtectedController 
{
    [Authorize]
    [Route("id/{id}")]
    public IEnumerable<object> Post(String id, [FromBody] JObject data)
    {
        /*
          id                                      = "123"
          data.GetValue("username").ToString()    = "user1"
          data.GetValue("password").ToString()    = "pass1"
         */
    }
}

Calling like this:

POST /api/test/id/123 HTTP/1.1
Host: localhost
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer x.y.z
Cache-Control: no-cache

username=user1&password=pass1


enter code here

How can you encode a string to Base64 in JavaScript?

I have re-wrote by hand, these encoding and decoding methods with the exception of the hexadecimal one into a modular format for cross-platform / browser compatibility and also with real private scoping, and uses btoa and atob if they exist due to speed rather than utilize its own encoding:

https://gist.github.com/Nijikokun/5192472

Usage:

base64.encode(/* String */);
base64.decode(/* String */);

utf8.encode(/* String */);
utf8.decode(/* String */);

How do I escape the wildcard/asterisk character in bash?

It may be worth getting into the habit of using printf rather then echo on the command line.

In this example it doesn't give much benefit but it can be more useful with more complex output.

FOO="BAR * BAR"
printf %s "$FOO"

How do I compile jrxml to get jasper?

If you are using iReport you can easily do it.

  1. When you click preview it will automatically compile.
  2. There is an option to make it complie. You can compile by selecting the page then right click you will get the compile option.

What is an IIS application pool?

The application Pools element contains configuration settings for all application pools running on your IIS. An application pool defines a group of one or more worker processes, configured with common settings that serve requests to one or more applications that are assigned to that application pool.

Because application pools allow a set of Web applications to share one or more similarly configured worker processes, they provide a convenient way to isolate a set of Web applications from other Web applications on the server computer.

Process boundaries separate each worker process; therefore, application problems in one application pool do not affect Web sites or applications in other application pools. Application pools significantly increase both the reliability and manageability of your Web infrastructure.

Cannot find JavaScriptSerializer in .Net 4.0

Are you targeting the .NET 4 framework or the .NET 4 Client Profile?

If you're targeting the latter, you won't find that class. You also may be missing a reference, likely to an extensions dll.

How to set date format in HTML date input tag?

Why not use the html5 date control as it is, with other attributes that allows it work ok on browsers that support date type and still works on other browsers like firefox that is yet to support date type

<input type="date" name="input1" placeholder="YYYY-MM-DD" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" title="Enter a date in this formart YYYY-MM-DD"/>

How to remove single character from a String

You can use Java String method called replace, which will replace all characters matching the first parameter with the second parameter:

String a = "Cool";
a = a.replace("o","");

What's a simple way to get a text input popup dialog box on an iPhone

In Xamarin and C#:

var alert = new UIAlertView ("Your title", "Your description", null, "Cancel", new [] {"OK"});
alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
alert.Clicked += (s, b) => {
    var title = alert.ButtonTitle(b.ButtonIndex);
    if (title == "OK") {
        var text = alert.GetTextField(0).Text;
        ...
    }
};

alert.Show();

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

How do I create ColorStateList programmatically?

My builder class for create ColorStateList

private class ColorStateListBuilder {
    List<Integer> colors = new ArrayList<>();
    List<int[]> states = new ArrayList<>();

    public ColorStateListBuilder addState(int[] state, int color) {
        states.add(state);
        colors.add(color);
        return this;
    }

    public ColorStateList build() {
        return new ColorStateList(convertToTwoDimensionalIntArray(states),
                convertToIntArray(colors));
    }

    private int[][] convertToTwoDimensionalIntArray(List<int[]> integers) {
        int[][] result = new int[integers.size()][1];
        Iterator<int[]> iterator = integers.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            result[i] = iterator.next();
        }
        return result;
    }

    private int[] convertToIntArray(List<Integer> integers) {
        int[] result = new int[integers.size()];
        Iterator<Integer> iterator = integers.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            result[i] = iterator.next();
        }
        return result;
    }
}

Example Using

ColorStateListBuilder builder = new ColorStateListBuilder();
builder.addState(new int[] { android.R.attr.state_pressed }, ContextCompat.getColor(this, colorRes))
       .addState(new int[] { android.R.attr.state_selected }, Color.GREEN)
       .addState(..., some color);

if(// some condition){
      builder.addState(..., some color);
}
builder.addState(new int[] {}, colorNormal); // must add default state at last of all state

ColorStateList stateList = builder.build(); // ColorStateList created here

// textView.setTextColor(stateList);

Border Height on CSS

This will add a centered border to the left of the cell that is 80% the height of the cell. You can reference the full border-image documentation here.

table td {
    border-image: linear-gradient(transparent 10%, blue 10% 90%, transparent 90%) 0 0 0 1 / 3px;
}

Swapping two variable value without using third variable

single line solution for swapping two values in c language.

a=(b=(a=a+b,a-b),a-b);

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

How to get HTML 5 input type="date" working in Firefox and/or IE 10

You can try webshims, which is available on cdn + only loads the polyfill, if it is needed.

Here is a demo with CDN: http://jsfiddle.net/trixta/BMEc9/

<!-- cdn for modernizr, if you haven't included it already -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<!-- polyfiller file to detect and load polyfills -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
<script>
  webshims.setOptions('waitReady', false);
  webshims.setOptions('forms-ext', {types: 'date'});
  webshims.polyfill('forms forms-ext');
</script>

<input type="date" />

In case the default configuration does not satisfy, there are many ways to configure it. Here you find the datepicker configurator.

Note: While there might be new bugfix releases for webshim in the future. There won't be any major releases anymore. This includes support for jQuery 3.0 or any new features.

What is lexical scope?

var scope = "I am global";
function whatismyscope(){
   var scope = "I am just a local";
   function func() {return scope;}
   return func;
}

whatismyscope()()

The above code will return "I am just a local". It will not return "I am a global". Because the function func() counts where is was originally defined which is under the scope of function whatismyscope.

It will not bother from whatever it is being called(the global scope/from within another function even), that's why global scope value I am global will not be printed.

This is called lexical scoping where "functions are executed using the scope chain that was in effect when they were defined" - according to JavaScript Definition Guide.

Lexical scope is a very very powerful concept.

Hope this helps..:)

Asking the user for input until they give a valid response

Yeah I'm 6 years late from the but this question deserves more up-to-date answer.

Separation of concerns

I am a big fan of Unix philosophy "Do one thing and do it well". In this type of problem, it is better practice to split the problem to

  • Ask input with get_input until the input is ok.
  • Validate in validator function. You could write different validators for different input queries.

Asking for input

It can be kept as simple as (Python 3+)

def myvalidator(value):
    try:
        value = int(value)
    except ValueError:
        return False
    return value >= 0

def get_input(prompt, validator, on_validationerror):
    while True:
        value = input(prompt)
        if validator(value):
            return value
        print(on_validationerror)

Example

In [2]: get_input('Give a positive number: ', myvalidator, 'Please, try again')
Give a positive number: foobar
Please, try again
Give a positive number: -10
Please, try again
Give a positive number: 42
Out[2]: '42'

Python 3.8+ Note

In Python 3.8+ you could use the walrus operator

def get_input(prompt, validator, on_validationerror):
    while not validator(value := input(prompt)):
        print(on_validationerror)
    return value 

How to change the default GCC compiler in Ubuntu?

As @Tommy suggested, you should use update-alternatives.
It assigns values to every software of a family, so that it defines the order in which the applications will be called.

It is used to maintain different versions of the same software on a system. In your case, you will be able to use several declinations of gcc, and one will be favoured.

To figure out the current priorities of gcc, type in the command pointed out by @tripleee's comment:

update-alternatives --query gcc

Now, note the priority attributed to gcc-4.4 because you'll need to give a higher one to gcc-3.3.
To set your alternatives, you should have something like this (assuming your gcc installation is located at /usr/bin/gcc-3.3, and gcc-4.4's priority is less than 50):

update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-3.3 50

--edit--

Finally, you can also use the interactive interface of update-alternatives to easily switch between versions. Type update-alternatives --config gcc to be asked to choose the gcc version you want to use among those installed.

--edit 2 --

Now, to fix the CXX environment variable systemwide, you need to put the line indicated by @DipSwitch's in your .bashrc file (this will apply the change only for your user, which is safer in my opinion):

echo 'export CXX=/usr/bin/gcc-3.3' >> ~/.bashrc

How to remove word wrap from textarea?

textarea {
  white-space: pre;
  overflow-wrap: normal;
  overflow-x: scroll;
}

white-space: nowrap also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre.

overflow-wrap: normal (was word-wrap in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre is set.

also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap seems to be the default on my browser.

Executing JavaScript without a browser?

I have installed Node.js on an iMac and

node somefile.js

in bash will work.

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

How to make graphics with transparent background in R using ggplot2?

Updated with the theme() function, ggsave() and the code for the legend background:

df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
  stat_boxplot(aes(x = x, y = y, color = group), 
               fill = "transparent" # for the inside of the boxplot
  ) 

Fastest way is using using rect, as all the rectangle elements inherit from rect:

p <- p +
  theme(
        rect = element_rect(fill = "transparent") # all rectangles
      )
    p

More controlled way is to use options of theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

To save (this last step is important):

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")

Show constraints on tables command

I use

SHOW CREATE TABLE mytable;

This shows you the SQL statement necessary to receate mytable in its current form. You can see all the columns and their types (like DESC) but it also shows you constraint information (and table type, charset, etc.).

MySQL and GROUP_CONCAT() maximum length

The correct syntax is mysql> SET @@global.group_concat_max_len = integer;
If you do not have the privileges to do this on the server where your database resides then use a query like:
mySQL="SET @@session.group_concat_max_len = 10000;"or a different value.
Next line:
SET objRS = objConn.Execute(mySQL)  your variables may be different.
then
mySQL="SELECT GROUP_CONCAT(......);" etc
I use the last version since I do not have the privileges to change the default value of 1024 globally (using cPanel).
Hope this helps.

Why does Python code use len() function instead of a length method?

Strings do have a length method: __len__()

The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes for you) on objects which are iterable.

See Emulating container types for more information.

Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment

What's the best way to set a single pixel in an HTML5 canvas?

One method that hasnt been mentioned is using getImageData and then putImageData.
This method is good for when you want to draw a lot in one go, fast.
http://next.plnkr.co/edit/mfNyalsAR2MWkccr

  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var canvasWidth = canvas.width;
  var canvasHeight = canvas.height;
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  var id = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
  var pixels = id.data;

    var x = Math.floor(Math.random() * canvasWidth);
    var y = Math.floor(Math.random() * canvasHeight);
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var off = (y * id.width + x) * 4;
    pixels[off] = r;
    pixels[off + 1] = g;
    pixels[off + 2] = b;
    pixels[off + 3] = 255;

  ctx.putImageData(id, 0, 0);

Naming convention - underscore in C++ and C# variables

It's simply means that it's a member field in the class.

C# Change A Button's Background Color

this.button2.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(190)))), ((int)(((byte)(149)))));

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

it is also possible to implement what you want using a single layer

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:bottom="-5dp"
        android:right="-5dp"
        android:top="-5dp">
        <shape android:shape="rectangle" >
            <solid android:color="@color/color_of_the_background" />

            <stroke
                android:width="5dp"
                android:color="@color/color_of_the_border" />
        </shape>
    </item>

</layer-list>

this way only left border is visible but you can achieve any combination you want by playing with bottom, left, right and top attributes of the item element

Where is Ubuntu storing installed programs?

Simply, type the command:

~$ whereis "program name"

Who sets response content-type in Spring MVC (@ResponseBody)

public final class ConfigurableStringHttpMessageConverter extends AbstractHttpMessageConverter<String> {

    private Charset defaultCharset;

    public Charset getDefaultCharset() {
        return defaultCharset;
    }

    private final List<Charset> availableCharsets;

    private boolean writeAcceptCharset = true;

    public ConfigurableStringHttpMessageConverter() {
        super(new MediaType("text", "plain", StringHttpMessageConverter.DEFAULT_CHARSET), MediaType.ALL);
        defaultCharset = StringHttpMessageConverter.DEFAULT_CHARSET;
        this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
    }

    public ConfigurableStringHttpMessageConverter(String charsetName) {
        super(new MediaType("text", "plain", Charset.forName(charsetName)), MediaType.ALL);
        defaultCharset = Charset.forName(charsetName);
        this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
    }

    /**
     * Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
     * <p>Default is {@code true}.
     */
    public void setWriteAcceptCharset(boolean writeAcceptCharset) {
        this.writeAcceptCharset = writeAcceptCharset;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return String.class.equals(clazz);
    }

    @Override
    protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException {
        Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
        return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
    }

    @Override
    protected Long getContentLength(String s, MediaType contentType) {
        Charset charset = getContentTypeCharset(contentType);
        try {
            return (long) s.getBytes(charset.name()).length;
        }
        catch (UnsupportedEncodingException ex) {
            // should not occur
            throw new InternalError(ex.getMessage());
        }
    }

    @Override
    protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException {
        if (writeAcceptCharset) {
            outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
        }
        Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
        FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset));
    }

    /**
     * Return the list of supported {@link Charset}.
     *
     * <p>By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses.
     *
     * @return the list of accepted charsets
     */
    protected List<Charset> getAcceptedCharsets() {
        return this.availableCharsets;
    }

    private Charset getContentTypeCharset(MediaType contentType) {
        if (contentType != null && contentType.getCharSet() != null) {
            return contentType.getCharSet();
        }
        else {
            return defaultCharset;
        }
    }
}

Sample configuration :

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <util:list>
                <bean class="ru.dz.mvk.util.ConfigurableStringHttpMessageConverter">
                    <constructor-arg index="0" value="UTF-8"/>
                </bean>
            </util:list>
        </property>
    </bean>

How can I search (case-insensitive) in a column using LIKE wildcard?

When I want to develop insensitive case searchs, I always convert every string to lower case before do comparasion

SQL Update with row_number()

With UpdateData  As
(
SELECT RS_NOM,
ROW_NUMBER() OVER (ORDER BY [RS_NOM] DESC) AS RN
FROM DESTINATAIRE_TEMP
)
UPDATE DESTINATAIRE_TEMP SET CODE_DEST = RN
FROM DESTINATAIRE_TEMP
INNER JOIN UpdateData ON DESTINATAIRE_TEMP.RS_NOM = UpdateData.RS_NOM

Why should we typedef a struct so often in C?

As Greg Hewgill said, the typedef means you no longer have to write struct all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.

Stuff like

typedef struct {
  int x, y;
} Point;

Point point_new(int x, int y)
{
  Point a;
  a.x = x;
  a.y = y;
  return a;
}

becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef, is the case I guess.

Also note that while your example (and mine) omitted naming the struct itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:

typedef struct Point Point;

Point * point_new(int x, int y);

and then provide the struct definition in the implementation file:

struct Point
{
  int x, y;
};

Point * point_new(int x, int y)
{
  Point *p;
  if((p = malloc(sizeof *p)) != NULL)
  {
    p->x = x;
    p->y = y;
  }
  return p;
}

In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.

UPDATE Note that there are also highly-regarded C projects where this use of typedef to hide struct is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.

Moment JS start and end of given month

you can use this directly for the end or start date of the month

new moment().startOf('month').format("YYYY-DD-MM");
new moment().endOf("month").format("YYYY-DD-MM");

you can change the format by defining a new format

Creating a range of dates in Python

You can write a generator function that returns date objects starting from today:

import datetime

def date_generator():
  from_date = datetime.datetime.today()
  while True:
    yield from_date
    from_date = from_date - datetime.timedelta(days=1)

This generator returns dates starting from today and going backwards one day at a time. Here is how to take the first 3 dates:

>>> import itertools
>>> dates = itertools.islice(date_generator(), 3)
>>> list(dates)
[datetime.datetime(2009, 6, 14, 19, 12, 21, 703890), datetime.datetime(2009, 6, 13, 19, 12, 21, 703890), datetime.datetime(2009, 6, 12, 19, 12, 21, 703890)]

The advantage of this approach over a loop or list comprehension is that you can go back as many times as you want.

Edit

A more compact version using a generator expression instead of a function:

date_generator = (datetime.datetime.today() - datetime.timedelta(days=i) for i in itertools.count())

Usage:

>>> dates = itertools.islice(date_generator, 3)
>>> list(dates)
[datetime.datetime(2009, 6, 15, 1, 32, 37, 286765), datetime.datetime(2009, 6, 14, 1, 32, 37, 286836), datetime.datetime(2009, 6, 13, 1, 32, 37, 286859)]

How to convert List<Integer> to int[] in Java?

This simple loop is always correct! no bugs

  int[] integers = new int[myList.size()];
  for (int i = 0; i < integers.length; i++) {
      integers[i] = myList.get(i);
  }

How to create a sticky navigation bar that becomes fixed to the top after scrolling

In answer to Shubham Patwa: This way, the page is "jumpy" soon as the class "navbar-fixed-top" applies. That's because the #mainnav is throwen in and out of the document's DOM flow. This can result in an ugly UX if the page has a "critical height", jumping between fixed and un-fixed #mainnav position.

I altered the code this way, which seems to work fine (not pixel-perfect, but fine):

$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  var navheight = $('#mainnav').outerHeight();

$(window).bind('scroll', function() {
  if ($(window).scrollTop() > navpos.top) {
   $('#mainnav').addClass('navbar-fixed-top');
   $('body').css('marginTop',navheight);
   }
   else {
     $('#mainnav').removeClass('navbar-fixed-top');
     $('body').css('marginTop','0');
   }
});

How to recover MySQL database from .myd, .myi, .frm files

For those that have Windows XP and have MySQL server 5.5 installed - the location for the database is C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.5\data, unless you changed the location within the MySql Workbench installation GUI.

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.

The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api

Relevant passages as of January 2021 are below. These are excerpts from the text.

4.6 HTTP-network fetch

To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.

To append a name/value name/value pair to a Headers object (headers), run these steps:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If headers’s guard is "immutable", then throw a TypeError.

Filling Headers object headers with a given object object:

To fill a Headers object headers with a given object object, run these steps:

  1. If object is a sequence, then for each header in object:
    1. If header does not contain exactly two items, then throw a TypeError.

Method steps sometimes throw TypeError:

The delete(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. If this’s guard is "immutable", then throw a TypeError.

The get(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. Return the result of getting name from this’s header list.

The has(name) method steps are:

  1. If name is not a name, then throw a TypeError.

The set(name, value) method steps are:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If this’s guard is "immutable", then throw a TypeError.

To extract a body and a Content-Type value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.

In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin

In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:

The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In the Response class:

The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...

The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In section "The Fetch method"

The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.

In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.

'Operation is not valid due to the current state of the object' error during postback

Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.

Try adding the following setting in your web.config's <appsettings> block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2001" />
 </appSettings>

For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

How to simulate POST request?

Dont forget to add user agent since some server will block request if there's no server agent..(you would get Forbidden resource response) example :

curl -X POST -A 'Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0' -d "field=acaca&name=afadxx" https://example.com

Apply formula to the entire column

I think it's a more recent feature, but it works for me:

Double clicking the square on the bottom right of the highlighted cell copies the formula of the highlighted cell.

Hope it helps.

Unsupported major.minor version 52.0

You must run and compile your application with the same version of Java.

If you're using Eclipse you should do 2 things:

  1. In Eclipse, click on "Window > Preferences", and in the window that appears, on the left side, under "Java", click on "Installed JREs", click on "Add..." and navigate to the folder that contains the JDK.

  2. Right-click on your project and click on "Properties", in the window that appears, on the left side, click on "Java Compiler" and uncheck "Use compliance from execution environment on the Java Build Path", this allows you to choose in the the list "Compiler compilance level" the same version that you set in the previous step.

How do you properly determine the current script directory?

The os.path... approach was the 'done thing' in Python 2.

In Python 3, you can find directory of script as follows:

from pathlib import Path
cwd = Path(__file__).parents[0]

Convert sqlalchemy row object to python dict

if your models table column is not equie mysql column.

such as :

class People:
    id: int = Column(name='id', type_=Integer, primary_key=True)
    createdTime: datetime = Column(name='create_time', type_=TIMESTAMP,
                               nullable=False,
                               server_default=text("CURRENT_TIMESTAMP"),
                               default=func.now())
    modifiedTime: datetime = Column(name='modify_time', type_=TIMESTAMP,
                                server_default=text("CURRENT_TIMESTAMP"),
                                default=func.now())

Need to use:

 from sqlalchemy.orm import class_mapper 
 def asDict(self):
        return {x.key: getattr(self, x.key, None) for x in
            class_mapper(Application).iterate_properties}

if you use this way you can get modify_time and create_time both are None

{'id': 1, 'create_time': None, 'modify_time': None}


    def to_dict(self):
        return {c.name: getattr(self, c.name, None)
         for c in self.__table__.columns}

Because Class Attributes name not equal with column store in mysql

Overcoming "Display forbidden by X-Frame-Options"

Not mentioned but can help in some instances:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState !== 4) return;
    if (xhr.status === 200) {
        var doc = iframe.contentWindow.document;
        doc.open();
        doc.write(xhr.responseText);
        doc.close();
    }
}
xhr.open('GET', url, true);
xhr.send(null);

Show spinner GIF during an $http request in AngularJS?

Just discovered the angular-busy directive that shows a little loader depending on some async call.

For example, if you have to make a GET, reference the promise in your $scope,

$scope.req = $http.get('http://google.fr');

and call it like so :

<div cg-busy="req"></div>

Here is the GitHub.

You can also install it using bower (don't forget to update your project dependencies):

bower install angular-busy --save

Is it possible to create a File object from InputStream

Easy Java 9 solution with try with resources block

public static void copyInputStreamToFile(InputStream input, File file) {  

    try (OutputStream output = new FileOutputStream(file)) {
        input.transferTo(output);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

java.io.InputStream#transferTo is available since Java 9.

font size in html code

you dont need those quotes

<td style="padding-left: 5px;padding-bottom:3px; font-size: 35px;"> <b>Datum:</b><br/>
                        November 2010 </td>

JavaScript DOM remove element

removeChild should be invoked on the parent, i.e.:

parent.removeChild(child);

In your example, you should be doing something like:

if (frameid) {
    frameid.parentNode.removeChild(frameid);
}

Error Code: 1005. Can't create table '...' (errno: 150)

It happened in my case, because the name of the table being referenced in the constraint declaration wasn't correct (I forgot the upper case in the table name):

ALTER TABLE `Window` ADD CONSTRAINT `Windows_ibfk_1` FOREIGN KEY (`WallId`) REFERENCES `Wall` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

jQuery - Detect value change on hidden input field

It is possible to use Object.defineProperty() in order to redefine the 'value' property of the input element and do anything during its changing.

Object.defineProperty() allows us to define a getter and setter for a property, thus controlling it.

replaceWithWrapper($("#hid1")[0], "value", function(obj, property, value) { 
  console.log("new value:", value)
});

function replaceWithWrapper(obj, property, callback) {
  Object.defineProperty(obj, property, new function() {
    var _value = obj[property];
    return {
      set: function(value) {
        _value = value;
        callback(obj, property, value)
      },
      get: function() {
        return _value;
      }
    }
  });
}

$("#hid1").val(4);

https://jsfiddle.net/bvvmhvfk/

Format ints into string of hex

a = [0,1,2,3,127,200,255]
print str.join("", ("%02x" % i for i in a))

prints

000102037fc8ff

(Also note that your code will fail for integers in the range from 10 to 15.)

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

How does inline Javascript (in HTML) work?

It looks suspicious because there is no apparent function that is being returned from!

It is an anonymous function that has been attached to the click event of the object.

why are you doing this, Steve?

Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)

How can I retrieve Id of inserted entity using Entity framework?

You can get ID only after saving, instead you can create a new Guid and assign before saving.

Filter rows which contain a certain string

edit included the newer across() syntax

Here's another tidyverse solution, using filter(across()) or previously filter_at. The advantage is that you can easily extend to more than one column.

Below also a solution with filter_all in order to find the string in any column, using diamonds as example, looking for the string "V"

library(tidyverse)

String in only one column

# for only one column... extendable to more than one creating a column list in `across` or `vars`!
mtcars %>% 
  rownames_to_column("type") %>% 
  filter(across(type, ~ !grepl('Toyota|Mazda', .))) %>%
  head()
#>                type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1        Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#> 2    Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> 3 Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#> 4           Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#> 5        Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
#> 6         Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

The now superseded syntax for the same would be:

mtcars %>% 
  rownames_to_column("type") %>% 
  filter_at(.vars= vars(type), all_vars(!grepl('Toyota|Mazda',.))) 

String in all columns:

# remove all rows where any column contains 'V'
diamonds %>%
  filter(across(everything(), ~ !grepl('V', .))) %>%
  head
#> # A tibble: 6 x 10
#>   carat cut     color clarity depth table price     x     y     z
#>   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
#> 2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
#> 3  0.31 Good    J     SI2      63.3    58   335  4.34  4.35  2.75
#> 4  0.3  Good    J     SI1      64      55   339  4.25  4.28  2.73
#> 5  0.22 Premium F     SI1      60.4    61   342  3.88  3.84  2.33
#> 6  0.31 Ideal   J     SI2      62.2    54   344  4.35  4.37  2.71

The now superseded syntax for the same would be:

diamonds %>% 
  filter_all(all_vars(!grepl('V', .))) %>%
  head

I tried to find an across alternative for the following, but I didn't immediately come up with a good solution:

    #get all rows where any column contains 'V'
    diamonds %>%
    filter_all(any_vars(grepl('V',.))) %>%
      head
    #> # A tibble: 6 x 10
    #>   carat cut       color clarity depth table price     x     y     z
    #>   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
    #> 1 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31
    #> 2 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
    #> 3 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
    #> 4 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
    #> 5 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
    #> 6 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49

Update: Thanks to user Petr Kajzar in this answer, here also an approach for the above:

diamonds %>%
   filter(rowSums(across(everything(), ~grepl("V", .x))) > 0)

Is there an alternative sleep function in C to milliseconds?

#include <stdio.h>
#include <stdlib.h>
int main () {

puts("Program Will Sleep For 2 Seconds");

system("sleep 2");      // works for linux systems


return 0;
}

C# event with custom arguments

I might be late in the game, but how about:

public event Action<MyEvent> EventTriggered = delegate { }; 

private void Trigger(MyEvent e) 
{ 
     EventTriggered(e);
} 

Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.

I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.

Xampp MySQL not starting - "Attempting to start MySQL service..."

Only for windows I have fixed the mysql startup issue by following below steps

Steps:

  1. Open CMD and copy paste the command netstat -ano | findstr 3306 If you get any result for command then the Port 3306 is active

  2. Now we want to kill the active port(3306), so now open powershell and paste the command Stop-Process -Id (Get-NetTCPConnection -LocalPort 3306).OwningProcess -Force

Where 3306 is active port. Now port will be inactive

Start Mysql service from Xampp which will work fine now

Note: This works only if the port 3306 is in active state. If you didn't get any result from step 1 this method is not applicable. There could be some other errors

For other ports change 3306 to "Required port"

Ways to open CMD and Powershell

  1. For CMD-> search for cmd from start menu
  2. For Powershell-> search for powershell from start menu

How to wait until WebBrowser is completely loaded in VB.NET?

Sometimes if you use JavaScript the DocumentComplete event don't return the right answer; I use the event ProgressChanged instead:

Private Sub WebBrowser1_ProgressChanged(sender As Object, e As WebBrowserProgressChangedEventArgs) Handles WebBrowser1.ProgressChanged

        Console.WriteLine("Current Progress: " + e.CurrentProgress.ToString)

        If e.CurrentProgress = e.MaximumProgress Then

            ' The maximum progress is reached
            load_started = True

        End If

        ' The page is confirmed downloaded after the progress returns to 0
        If e.CurrentProgress = 0 Then

            If load_started Then

                ' The page is ready to print or download...
                WebBrowser1.Print()
                load_started = False

            End If

        End If

End Sub

.setAttribute("disabled", false); changes editable attribute to false

just replace 'myselect' with your id

to disable->

document.getElementById("mySelect").disabled = true;  

to enable->

document.getElementById("mySelect").disabled = false; 

Show all tables inside a MySQL database using PHP?

SHOW TABLE_NAME is not valid. Try SHOW TABLES

TD

How to check if character is a letter in Javascript?

// to check if the given string contain alphabets    
function isPangram(sentence){
        let lowerCased = sentence.toLowerCase();
        let letters = "abcdefghijklmnopqrstuvwxyz";
        // traditional for loop can also be used
        for (let char of letters){
            if (!lowerCased.includes(char)) return false;
        }
        return true;
    }

How to move a marker in Google Maps API

<style>
    #frame{
        position: fixed;
        top: 5%;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        width: 98%;
        height: 92%;
        display: none;
        z-index: 1000;
    }
    #map{
        position: fixed;
        display: inline-block;
        width: 99%;
        height: 93%;
        display: none;
        z-index: 1000;
    }

    #loading{
        position: fixed;
        top: 50%;
        left: 50%;
        opacity: 1!important;
        margin-top: -100px;
        margin-left: -150px;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        max-width: 66%;
        display: none;
        color: #000;

    }
    #mytitle{
        color: #FFF;
        background-image: linear-gradient(to bottom,#d67631,#d67631);
        //  border-color: rgba(47, 164, 35, 1);
        width: 100%;
        cursor: move;
    }
    #closex{ 
        display: block;
        float:right;
        position:relative;
        top:-10px;
        right: -10px;
        height: 20px;
        cursor: pointer;
    }
    .pointer{
        cursor: pointer !important;
    }

</style> 
<div id="loading">
    <i class="fa fa-circle-o-notch fa-spin fa-2x"></i>
    Loading...
</div>
<div id="frame">
    <div id="headerx"></div>
    <div id="map" >    
    </div>
</div>


<?php
$url = Yii::app()->baseUrl . '/reports/reports/transponderdetails';
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

<script>
    function clode() {
        $('#frame').hide();
        $('#frame').html();
    }
    function track(id) {
        $('#loading').show();
        $('#loading').parent().css("opacity", '0.7');


        $.ajax({
            type: "POST",
            url: '<?php echo $url; ?>',
            data: {'id': id},
            success: function(data) {
                $('#frame').show();
                $('#headerx').html(data);
                $('#loading').parents().css("opacity", '1');
                $('#loading').hide();
                var thelat = parseFloat($('#lat').text());
                var long = parseFloat($('#long').text());
                $('#map').show();
                var lat = thelat;
                var lng = long;
                var orlat=thelat;
                var orlong=long;
                //Intialize the Path Array
                var path = new google.maps.MVCArray();
                var service = new google.maps.DirectionsService();


                var myLatLng = new google.maps.LatLng(lat, lng), myOptions = {zoom: 4, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP};
                var map = new google.maps.Map(document.getElementById('map'), myOptions);
                var poly = new google.maps.Polyline({map: map, strokeColor: '#4986E7'});
                var marker = new google.maps.Marker({position: myLatLng, map: map});

                function initialize() {
                    marker.setMap(map);
                    movepointer(map, marker);
                    var drawingManager = new google.maps.drawing.DrawingManager();
                    drawingManager.setMap(map);
                }

                function movepointer(map, marker) {
                    marker.setPosition(new google.maps.LatLng(lat, lng));
                    map.panTo(new google.maps.LatLng(lat, lng));

                    var src = myLatLng;//start point
                    var des = myLatLng;// should be the destination
                    path.push(src);
                    poly.setPath(path);
                    service.route({
                        origin: src,
                        destination: des,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    }, function(result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                path.push(result.routes[0].overview_path[i]);
                            }
                        }
                    });

                }
                ;

                // function()
                setInterval(function() {
                    lat = Math.random() + orlat;
                    lng = Math.random() + orlong;
                    console.log(lat + "-" + lng);
                    myLatLng = new google.maps.LatLng(lat, lng);
                    movepointer(map, marker);

                }, 1000);



            },
            error: function() {
                $('#frame').html('Sorry, no details found');
            },
        });
        return false;
    }
    $(function() {
        $("#frame").draggable();
    });

</script>

How to add background-image using ngStyle (angular2)?

Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.

_x000D_
_x000D_
import { Component, OnInit, Input } from '@angular/core';_x000D_
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';_x000D_
_x000D_
@Component({_x000D_
  selector: 'my-component',_x000D_
  templateUrl: './my-component.component.html',_x000D_
  styleUrls: ['./my-component.component.scss']_x000D_
})_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  public backgroundImg: SafeStyle;_x000D_
  @Input() myObject: any;_x000D_
_x000D_
  constructor(private sanitizer: DomSanitizer) {}_x000D_
_x000D_
  ngOnInit() {_x000D_
     this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>
_x000D_
_x000D_
_x000D_

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I have encountered this error on "an empty branch" on my local gitlab server. Some people mentioned that "you can not push for the first time on an empty branch". I tried to create a simple README file on the gitlab via my browser. Then everything fixed amazingly and the problem sorted out!! I mention that I was the master and the branch was not protected.

Descending order by date filter in AngularJs

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.filter("toArray", function () {_x000D_
    return function (obj) {_x000D_
        var result = [];_x000D_
        angular.forEach(obj, function (val, key) {_x000D_
            result.push(val);_x000D_
        });_x000D_
        return result;_x000D_
    };_x000D_
});_x000D_
_x000D_
_x000D_
myApp.controller("mainCtrl", function ($scope) {_x000D_
_x000D_
  $scope.logData = [_x000D_
              { event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },_x000D_
              { event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },_x000D_
              { event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }_x000D_
          ]; _x000D_
        _x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="mainCtrl">_x000D_
_x000D_
  <h4>Descending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
  <br>_x000D_
  _x000D_
  _x000D_
  <h4>Ascending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Why number 9 in kill -9 command in unix?

There were 8 other signals they came up with first.

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

How to export collection to CSV in MongoDB?

I could not get mongoexport to do this for me. I found that,to get an exhaustive list of all the fields, you need to loop through the entire collection once. Use this to generate the headers. Then loop through the collection again to populate these headers for each document.

I've written a script to do just this. Converting MongoDB docs to csv irrespective of schema differences between individual documents.

https://github.com/surya-shodan/mongoexportcsv

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

Alter Table Add Column Syntax

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;

How to format font style and color in echo

echo '< span style = "font-color: #ff0000"> Movie List for {$key} 2013 </span>';

Adding a favicon to a static HTML page

Try to use the <link rel="icon" type="image/ico" href="images/favi.ico"/>

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.