Programs & Examples On #Rtos

An RTOS is a Real-Time Operating System, a type of operating system that is designed to satisfy, possibly hard or firm, timing constraints. An RTOS is most likely to be used in in verifiable or safety critical systems. Such systems arise most frequently in the medical, automotive and defense industries

React-Router: No Not Found Route?

DefaultRoute and NotFoundRoute were removed in react-router 1.0.0.

I'd like to emphasize that the default route with the asterisk has to be last in the current hierarchy level to work. Otherwise it will override all other routes that appear after it in the tree because it's first and matches every path.

For react-router 1, 2 and 3

If you want to display a 404 and keep the path (Same functionality as NotFoundRoute)

<Route path='*' exact={true} component={My404Component} />

If you want to display a 404 page but change the url (Same functionality as DefaultRoute)

<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />

Example with multiple levels:

<Route path='/' component={Layout} />
    <IndexRoute component={MyComponent} />
    <Route path='/users' component={MyComponent}>
        <Route path='user/:id' component={MyComponent} />
        <Route path='*' component={UsersNotFound} />
    </Route>
    <Route path='/settings' component={MyComponent} />
    <Route path='*' exact={true} component={GenericNotFound} />
</Route>

For react-router 4 and 5

Keep the path

<Switch>
    <Route exact path="/users" component={MyComponent} />
    <Route component={GenericNotFound} />
</Switch>

Redirect to another route (change url)

<Switch>
    <Route path="/users" component={MyComponent} />
    <Route path="/404" component={GenericNotFound} />
    <Redirect to="/404" />
</Switch>

The order matters!

Convert a secure string to plain text

In PS 7, you can use ConvertFrom-SecureString and -AsPlainText:

 $UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/ConvertFrom-SecureString?view=powershell-7#parameters

ConvertFrom-SecureString
           [-SecureString] <SecureString>
           [-AsPlainText]
           [<CommonParameters>]

How can I make my website's background transparent without making the content (images & text) transparent too?

Just include following in your code

<body background="C:\Users\Desktop\images.jpg"> 

if you want to specify the size and opacity you can use following

<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p> 

Can you 'exit' a loop in PHP?

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

How to set opacity in parent div and not affect in child div?

I had the same problem and I fixed by setting transparent png image as background for the parent tag.

This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !

How do you create a Spring MVC project in Eclipse?

Download Spring STS (SpringSource Tool Suite) and choose Spring Template Project from the Dashboard. This is the easiest way to get a preconfigured spring mvc project, ready to go.

How do I check if a PowerShell module is installed?

The ListAvailable option doesn't work for me. Instead this does:

if (-not (Get-Module -Name "<moduleNameHere>")) {
    # module is not loaded
}

Or, to be more succinct:

if (!(Get-Module "<moduleNameHere>")) {
    # module is not loaded
}

Remove #N/A in vlookup result

if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

Tried to Load Angular More Than Once

In my case I have index.html which embeds 2 views i.e view1.html and view2.html. I developed these 2 views independent of index.html and then tried to embed using route. So I had all the script files defined in the 2 view html files which was causing this warning. The warning disappeared after removing the inclusion of angularJS script files from views.

In short, the script files angularJS, jQuery and angular-route.js should be included only in index.html and not in view html files.

Is "&#160;" a replacement of "&nbsp;"?

Those do both mean non-breaking space, yes. &#xA0; is another synonym, in hex.

Parsing JSON object in PHP using json_decode

Try this example

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

http://php.net/manual/en/function.json-decode.php

NB - two negatives makes a positive . :)

Insert php variable in a href

You could try:

<a href="<?php echo $directory ?>">The link to the file</a>

Or for PHP 5.4+ (<?= is the PHP short echo tag):

<a href="<?= $directory ?>">The link to the file</a>

But your path is relative to the server, don't forget that.

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

What are the differences between LDAP and Active Directory?

LDAP sits on top of the TCP/IP stack and controls internet directory access. It is environment agnostic.

AD & ADSI is a COM wrapper around the LDAP layer, and is Windows specific.

You can see Microsoft's explanation here.

How to show progress bar while loading, using ajax

Here is an example that's working for me with MVC and Javascript in the Razor. The first function calls an action via ajax on my controller and passes two parameters.

        function redirectToAction(var1, var2)
        {
            try{

                var url = '../actionnameinsamecontroller/' + routeId;

                $.ajax({
                    type: "GET",
                    url: url,
                    data: { param1: var1, param2: var2 },
                    dataType: 'html',
                    success: function(){
                    },
                    error: function(xhr, ajaxOptions, thrownError){
                        alert(error);
                    }
                });

            }
            catch(err)
            {
                alert(err.message);
            }
        }

Use the ajaxStart to start your progress bar code.

           $(document).ajaxStart(function(){
            try
            {
                // showing a modal
                $("#progressDialog").modal();

                var i = 0;
                var timeout = 750;

                (function progressbar()
                {
                    i++;
                    if(i < 1000)
                    {
                        // some code to make the progress bar move in a loop with a timeout to 
                        // control the speed of the bar
                        iterateProgressBar();
                        setTimeout(progressbar, timeout);
                    }
                }
                )();
            }
            catch(err)
            {
                alert(err.message);
            }
        });

When the process completes close the progress bar

        $(document).ajaxStop(function(){
            // hide the progress bar
            $("#progressDialog").modal('hide');
        });

How to remove an element from a list by index

Use del and specify the index of the element you want to delete:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Also supports slices:

>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]

Here is the section from the tutorial.

How to remove underline from a name on hover

Remove the text decoration for the anchor tag

<a name="Section 1" style="text-decoration : none">Section</a>

YYYY-MM-DD format date in shell script

$(date +%F_%H-%M-%S)

can be used to remove colons (:) in between

output

2018-06-20_09-55-58

Git: Cannot see new remote branch

Let's say we are searching for release/1.0.5

When git fetch -all is not working and that you cannot see the remote branch and git branch -r not show this specific branch.

1. Print all refs from remote (branches, tags, ...):

git ls-remote origin Should show you remote branch you are searching for.

e51c80fc0e03abeb2379327d85ceca3ca7bc3ee5        refs/heads/fix/PROJECT-352
179b545ac9dab49f85cecb5aca0d85cec8fb152d        refs/heads/fix/PROJECT-5
e850a29846ee1ecc9561f7717205c5f2d78a992b        refs/heads/master
ab4539faa42777bf98fb8785cec654f46f858d2a        refs/heads/release/1.0.5
dee135fb65685cec287c99b9d195d92441a60c2d        refs/heads/release/1.0.4
36e385cec9b639560d1d8b093034ed16a402c855        refs/heads/release/1.0
d80c1a52012985cec2f191a660341d8b7dd91deb        refs/tags/v1.0

The new branch 'release/1.0.5' appears in the output.

2. Force fetching a remote branch:

git fetch origin <name_branch>:<name_branch>

$ git fetch origin release/1.0.5:release/1.0.5

remote: Enumerating objects: 385, done.
remote: Counting objects: 100% (313/313), done.
remote: Compressing objects: 100% (160/160), done.

Receiving objects: 100% (231/231), 21.02 KiB | 1.05 MiB/s, done.
Resolving deltas: 100% (98/98), completed with 42 local objects.
From http://git.repo:8080/projects/projectX
 * [new branch]        release/1.0.5 -> release/1.0.5

Now you have also the refs locally, you checkout (or whatever) this branch.

Job done!

LINQ to SQL - Left Outer Join with multiple join conditions

Can be written using composite join key. Also if there is need to select properties from both left and right sides the LINQ can be written as

var result = context.Periods
    .Where(p => p.companyid == 100)
    .GroupJoin(
        context.Facts,
        p => new {p.id, otherid = 17},
        f => new {id = f.periodid, f.otherid},
        (p, f) => new {p, f})
    .SelectMany(
        pf => pf.f.DefaultIfEmpty(),
        (pf, f) => new MyJoinEntity
        {
            Id = pf.p.id,
            Value = f.value,
            // and so on...
        });

Overcoming "Display forbidden by X-Frame-Options"

I came across this issue when running a wordpress web site. I tried all sorts of things to fix it and wasn't sure how, ultimately the issue was because I was using DNS forwarding with masking, and the links to external sites were not being addressed properly. i.e. my site was hosted at http://123.456.789/index.html but was masked to run at http://somewebSite.com/index.html. When i entered http://123.456.789/index.html in the browser clicking on those same links resulted in no X-frame-origins issues in the JS console, but running http://somewebSite.com/index.html did. In order to properly mask you must add your host's DNS name servers to your domain service, i.e. godaddy.com should have name servers of example, ns1.digitalocean.com, ns2.digitalocean.com, ns3.digitalocean.com, if you were using digitalocean.com as your hosting service.

How to check if a string "StartsWith" another string?

You can also return all members of an array that start with a string by creating your own prototype / extension to the the array prototype, aka

Array.prototype.mySearch = function (target) {
    if (typeof String.prototype.startsWith != 'function') {
        String.prototype.startsWith = function (str){
        return this.slice(0, str.length) == str;
      };
    }
    var retValues = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i].startsWith(target)) { retValues.push(this[i]); }
    }
    return retValues;
};

And to use it:

var myArray = ['Hello', 'Helium', 'Hideout', 'Hamster'];
var myResult = myArray.mySearch('Hel');
// result -> Hello, Helium

Array Size (Length) in C#

for 1 dimensional array

int[] listItems = new int[] {2,4,8};
int length = listItems.Length;

for multidimensional array

int length = listItems.Rank;

To get the size of 1 dimension

int length =  listItems.GetLength(0);

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

How to float a div over Google Maps?

absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!

How to determine one year from now in Javascript

2020

It's perfect date/time library called Moment.js with this library you can simply write:

moment().subtract(1,'year')

and call any format you wish:

moment().subtract(1,'year').toDate()
moment().subtract(1,'year').toISOString()

See full documentation here: https://momentjs.com/

Java String declaration

String str = new String("SOME")

always create a new object on the heap

String str="SOME" 

uses the String pool

Try this small example:

        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

To avoid creating unnecesary objects on the heap use the second form.

Create a new database with MySQL Workbench

Those who are new to MySQL & Mac users; Note that, Connection is different than Database.

Steps to create a database.

Step 1: Create connection and click to go inside

Step 1

Step 2: Click on database icon

Step 2

Step 3: Name your database schema

Step 3

Step 4: Apply query

Step 4

Step 5: Your DB created, enjoy...

Step 5

If else in stored procedure sql server

You can try below Procedure Sql:

Create Procedure sp_ADD_USER_EXTRANET_CLIENT_INDEX_PHY
(
@ParLngId int output
)
as
Begin
    -- Min will return only 1 value, if 'Extranet Client' is found
    -- IsNull will take care of 'Extranet Client' not found, returning 0 instead of Null
    -- But T_Param must be a Master Table with ParStrNom having a Unique Index, if so Min is not reqd at all
    -- But 'PHY', 'Extranet Client' suggests that Unique Key has 2 columns, not just ParStrNom

    SET @ParLngId = IsNull((Select Min (ParLngId) from T_Param where ParStrNom = 'Extranet Client'), 0);

    -- Nothing changed below

    if  (@ParLngId = 0)
        Begin
            Insert Into T_Param values ('PHY', 'Extranet Client', Null, Null, 'T', 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL)
            SET @ParLngId = @@IDENTITY
    End

    Return  @ParLngId
    End

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:

http://www.algolist.net/Algorithms/Merge/Sorted_arrays

Sorting is generally O(N logN) and the merge is O(m+n).

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

Borders of different colors. I used 3 items.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorAccent" />
        </shape>
    </item>
    <item android:top="3dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/light_grey" />
        </shape>
    </item>
    <item
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
</layer-list>

Adding a dictionary to another

foreach(var newAnimal in NewAnimals)
    Animals.Add(newAnimal.Key,newAnimal.Value)

Note: this throws an exception on a duplicate key.


Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange extension method that works on any ICollection<T>, and not just on Dictionary<TKey,TValue>.

public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
    if(target==null)
      throw new ArgumentNullException(nameof(target));
    if(source==null)
      throw new ArgumentNullException(nameof(source));
    foreach(var element in source)
        target.Add(element);
}

(throws on duplicate keys for dictionaries)

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

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

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

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

And need the include below code in JavaScript

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

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

This is an issue if you are using 2008 management studio tools to connect to a SQL 2012 instance.

I experience this a lot if I am working on one server with SQL 2008, and trying to quickly query another server that is running SQL 2012.

I normally keep my personal workstation on the latest version of management studio (2012 in this case), and am able to administer all servers from there.

in python how do I convert a single digit number into a double digits string?

>>> a=["%02d" % x for x in range(24)]
>>> a
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
>>> 

It is that simple

How to delete duplicates on a MySQL table?

this removes duplicates in place, without making a new table

ALTER IGNORE TABLE `table_name` ADD UNIQUE (title, SID)

note: only works well if index fits in memory

How to pass object from one component to another in Angular 2?

From component

_x000D_
_x000D_
import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
    import { HttpClient } from '@angular/common/http';_x000D_
    import { dataService } from "src/app/service/data.service";_x000D_
    @Component( {_x000D_
        selector: 'app-sideWidget',_x000D_
        templateUrl: './sideWidget.html',_x000D_
        styleUrls: ['./linked-widget.component.css']_x000D_
    } )_x000D_
    export class sideWidget{_x000D_
    TableColumnNames: object[];_x000D_
    SelectedtableName: string = "patient";_x000D_
    constructor( private LWTableColumnNames: dataService ) { _x000D_
       _x000D_
    }_x000D_
    _x000D_
    ngOnInit() {_x000D_
        this.http.post( 'getColumns', this.SelectedtableName )_x000D_
            .subscribe(_x000D_
            ( data: object[] ) => {_x000D_
                this.TableColumnNames = data;_x000D_
     this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
            } );_x000D_
    _x000D_
    }    _x000D_
    }
_x000D_
_x000D_
_x000D_

DataService

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
_x000D_
@Injectable()_x000D_
export class dataService {_x000D_
    refLWTableColumnNames: object;//creating an object for the data_x000D_
}
_x000D_
_x000D_
_x000D_

To Component

_x000D_
_x000D_
import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
_x000D_
@Component( {_x000D_
    selector: 'app-linked-widget',_x000D_
    templateUrl: './linked-widget.component.html',_x000D_
    styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
_x000D_
    constructor(private LWTableColumnNames: dataService) { }_x000D_
_x000D_
    ngOnInit() {_x000D_
    console.log(this.LWTableColumnNames.refLWTableColumnNames);_x000D_
    }_x000D_
    createTable(){_x000D_
        console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_
    }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

How to make an executable JAR file?

It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.

First of all make sure to download and add maven to path. [ mvn --version ] will give you version specifications of it if you have added to the path correctly.

Now , add following code to the maven project [ pom.xml ] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].

      <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                    <mainClass>
            your_package_to_class_that_contains_main_file .MainFileName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

Now go to the command line [CMD] in your project and type mvn package and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar under target directory.

Now navigate to the target directory by cd target.

Finally type java -jar jar-file-name.jar and yes this should work successfully if you don't have any errors in your program.

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include statement so the preprocessor finds it where it already is.

Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find it while following that search pattern.

Alternatively you can change the #include statement so that the preprocessor can find it. You tell us the xyz.cxx file is is in the 'code' folder but you don't tell us where you've put the xyz.h file. Let's say your file structure looks like this...

<some folder>\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\xyz.h"

On the other hand let's say your file structure looks like this...

<some folder>\include\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\include\xyz.h"

Update: On the other other hand as @In silico points out in the comments, if you are using #include <xyz.h> you should probably change it to #include "xyz.h"

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had this exact issue running the simple .py code below:

import sys
print 'version is:', sys.version

DSM's code above provided the following:

1 'print \xe2\x80\x98version is\xe2\x80\x99, sys.version'

So the issue was that my text editor used SMART QUOTES, as John Y suggested. After changing the text editor settings and re-opening/saving the file, it works just fine.

How to change the value of ${user} variable used in Eclipse templates

EGit Solution

One would expect creating or changing template variables on a project-, workspace-, or environment-basis is a standard Eclipse feature. Sadly, it is not. More so, given that Eclipse plugins can define new variables and templates, there should be plugins out there providing a solution. If they are, they must be hard to find. mmm-TemplateVariable, which is available in the Eclipse Marketplace, is a step in the right direction for Maven users, giving the ability to include version, artifactId, etc. in templates.

Fortunately, EGit, which is an Eclipse tool for Git, provides very flexible means for including many different variables in code templates. The only requirement is that your project uses Git. If you don’t use Git, but are serious about software development, now is the time to learn (Pro Git book). If you are forced to use a legacy version control system, try changing some minds.

Thanks to the efforts of harmsk, EGit 4.0 and above includes the ability to use Git configuration key values in templates. This allows setting template values based on repository settings (project), user settings (account), and/or global settings (workstation).

The following example shows how to set up Eclipse and Git for a multi-user development workstation and use a custom Git configuration key in lieu of ${user} to provide more flexibility. Although the example is based on a Windows 10 installation of Eclipse Mars and Git for Windows, the example is applicable to Linux and OSX running Eclipse and Git using their respective command line tools.

To avoid possible confusion between Git’s user.name configuration key and Java’s user.name system property, a custom Git configuration key – user.author – will be used to provide an author’s name and/or credentials.

Configuring Templates

The format of a Git template variable is as follows

${<name>:git_config(<key>)}

where <name> is any arbitrary variable name and <key> is the Git configuration key whose value should be used. Given that, changing the Comments?Types template to

/**
 * @author ${author:git_config(user.author)}
 *
 * ${tags}
 */

will now attempt to resolve the author’s name from Git’s user.author configuration key. Without any further configuration, any newly created comments will not include a name after @author, since none has been defined yet.

Configuring Git

From the command line

Git System Configuration - This configuration step makes changes to Git’s system-wide configuration applicable to all accounts on the workstation unless overridden by user or repository settings. Because system-wide configurations are part the underlying Git application (e.g. Git for Windows), changes will require Administrator privileges. Run Git Bash, cmd, or PowerShell as Administrator. The following command will set the system-wide author.

git config --system user.author “SET ME IN GLOBAL(USER) or REPOSITORY(LOCAL) SETTINGS”

The purpose of this “author” is to serve as a reminder that it should be set elsewhere. This is particularly useful when new user accounts are being used on the workstation.

To verify this setting, create an empty Java project that uses Git or open an existing Git-based project. Create a class and use Source?Generate Element Comment from the context menu, ALT-SHIFT-J, or start a JavaDoc comment. The resulting @author tag should be followed by the warning.

The remaining configuration changes can be performed without Administrator privileges.

Git Global(User) Configuration - Global, or user, configurations are those associated with a specific user and will override system-wide configurations. These settings apply to all Git-based projects unless overridden by repository settings. If the author name is different due to various project types such as for work, open source contributions, or personal, set the most frequently used here.

git config --global user.author “Mr. John Smith”

Having configured the global value, return to the test project used early and apply a class comment. The@author tag should now show the global setting.

Git Repository(Local) Configuration - Lastly, a repository or local configuration can be used to configure an author for a specific project. Unlike the previous configurations, a repository configuration must be done from within the repository. Using Git Bash, PowerShell, etc. navigate into the test project’s repository.

git config --local user.author “smithy”

Given this, new comments in the test project will use the locally defined author name. Other Git-based projects, will still use the global author name.

From Within Eclipse

The configuration changes above can also be set from within Eclipse through its Preferences: Team?Git-Configuration. Eclipse must be run as Administrator to change system-wide Git configurations.

In Sum

Although this example dealt specifically with the most common issue, that of changing ${user}, this approach can be used for more. However, caution should be exercised not to use Git-defined configuration keys, unless it is specifically intended.

how to configure hibernate config file for sql server

Keep the jar files under web-inf lib incase you included jar and it is not able to identify .

It worked in my case where everything was ok but it was not able to load the driver class.

Automatic login script for a website on windows machine?

You can use Autohotkey, download it from: http://ahkscript.org/download/

After the installation, if you want to open Gmail website when you press Alt+g, you can do something like this:

!g::
Run www.gmail.com 
return

Further reference: Hotkeys (Mouse, Joystick and Keyboard Shortcuts)

How do you add CSS with Javascript?

if you know at least one <style> tag exist in page , use this function :

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

usage :

CSS("div{background:#00F}");

Time complexity of nested for-loop

Yes, nested loops are one way to quickly get a big O notation.

Typically (but not always) one loop nested in another will cause O(n²).

Think about it, the inner loop is executed i times, for each value of i. The outer loop is executed n times.

thus you see a pattern of execution like this: 1 + 2 + 3 + 4 + ... + n times

Therefore, we can bound the number of code executions by saying it obviously executes more than n times (lower bound), but in terms of n how many times are we executing the code?

Well, mathematically we can say that it will execute no more than n² times, giving us a worst case scenario and therefore our Big-Oh bound of O(n²). (For more information on how we can mathematically say this look at the Power Series)

Big-Oh doesn't always measure exactly how much work is being done, but usually gives a reliable approximation of worst case scenario.


4 yrs later Edit: Because this post seems to get a fair amount of traffic. I want to more fully explain how we bound the execution to O(n²) using the power series

From the website: 1+2+3+4...+n = (n² + n)/2 = n²/2 + n/2. How, then are we turning this into O(n²)? What we're (basically) saying is that n² >= n²/2 + n/2. Is this true? Let's do some simple algebra.

  • Multiply both sides by 2 to get: 2n² >= n² + n?
  • Expand 2n² to get:n² + n² >= n² + n?
  • Subtract n² from both sides to get: n² >= n?

It should be clear that n² >= n (not strictly greater than, because of the case where n=0 or 1), assuming that n is always an integer.

Actual Big O complexity is slightly different than what I just said, but this is the gist of it. In actuality, Big O complexity asks if there is a constant we can apply to one function such that it's larger than the other, for sufficiently large input (See the wikipedia page)

Sorting an array in C?

The best sorting technique of all generally depends upon the size of an array. Merge sort can be the best of all as it manages better space and time complexity according to the Big-O algorithm (This suits better for a large array).

how to get text from textview

Try Like this.

tv1.setText("  " + Integer.toString(X[i]) + "\n" + "+" + " " + Integer.toString(Y[i]));

Java - How to create new Entry (key, value)

If you look at the documentation of Map.Entry you will find that it is a static interface (an interface which is defined inside the Map interface an can be accessed through Map.Entry) and it has two implementations

All Known Implementing Classes:
AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry

The class AbstractMap.SimpleEntry provides 2 constructors:

Constructors and Description
AbstractMap.SimpleEntry(K key, V value)
Creates an entry representing a mapping from the specified key to the
specified value.
AbstractMap.SimpleEntry(Map.Entry<? extends K,? extends V> entry)
Creates an entry representing the same mapping as the specified entry.

An example use case:

import java.util.Map;
import java.util.AbstractMap.SimpleEntry;

public class MyClass {
    public static void main(String args[]) {
      Map.Entry e = new SimpleEntry<String, String>("Hello","World");

      System.out.println(e.getKey()+" "+e.getValue());
    }
}

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

There is an important difference that no answer has mentioned yet.

From this:

new Array(2).length           // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true

You might think the new Array(2) is equivalent to [undefined, undefined], but it's NOT!

Let's try with map():

[undefined, undefined].map(e => 1)  // [1, 1]
new Array(2).map(e => 1)            // "(2) [undefined × 2]" in Chrome

See? The semantics are totally different! So why is that?

According to ES6 Spec 22.1.1.2, the job of Array(len) is just creating a new array whose property length is set to the argument len and that's it, meaning there isn't any real element inside this newly created array.

Function map(), according to spec 22.1.3.15 would firstly check HasProperty then call the callback, but it turns out that:

new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true

And that's why you can not expect any iterating functions working as usual on arrays created from new Array(len).

BTW, Safari and Firefox have a much better "printing" to this situation:

// Safari
new Array(2)             // [](2)
new Array(2).map(e => 1) // [](2) 
[undefined, undefined]   // [undefined, undefined] (2) 

// Firefox
new Array(2)             // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined]   // Array [ undefined, undefined ]

I have already submitted an issue to Chromium and ask them to fix this confusing printing: https://bugs.chromium.org/p/chromium/issues/detail?id=732021

UPDATE: It's already fixed. Chrome now printed as:

new Array(2)             // (2) [empty × 2]

How to set Python's default version to 3.x on OS X?

Mac users just need to run the following code on terminal

brew switch python 3.x.x

3.x.x should be the new python version.

This will update all the system links.

Reading a huge .csv file

here's another solution for Python3:

import csv
with open(filename, "r") as csvfile:
    datareader = csv.reader(csvfile)
    count = 0
    for row in datareader:
        if row[3] in ("column header", criterion):
            doSomething(row)
            count += 1
        elif count > 2:
            break

here datareader is a generator function.

How to convert HTML to PDF using iTextSharp

As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml

Usage is straightforward:

HtmlConverter.ConvertToPdf(
    new FileInfo(@"Path\to\Html\File.html"),
    new FileInfo(@"Path\to\Pdf\File.pdf")
);

Method has many more overloads.

Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

jQuery Get Selected Option From Dropdown

Try

aioConceptName.selectedOptions[0].value

_x000D_
_x000D_
let val = aioConceptName.selectedOptions[0].value

console.log('selected value:',val);
_x000D_
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>
_x000D_
_x000D_
_x000D_

How to get all Errors from ASP.Net MVC modelState?

During debugging I find it useful to put a table at the bottom of each of my pages to show all ModelState errors.

<table class="model-state">
    @foreach (var item in ViewContext.ViewData.ModelState) 
    {
        if (item.Value.Errors.Any())
        { 
        <tr>
            <td><b>@item.Key</b></td>
            <td>@((item.Value == null || item.Value.Value == null) ? "<null>" : item.Value.Value.RawValue)</td>
            <td>@(string.Join("; ", item.Value.Errors.Select(x => x.ErrorMessage)))</td>
        </tr>
        }
    }
</table>

<style>
    table.model-state
    {
        border-color: #600;
        border-width: 0 0 1px 1px;
        border-style: solid;
        border-collapse: collapse;
        font-size: .8em;
        font-family: arial;
    }

    table.model-state td
    {
        border-color: #600;
        border-width: 1px 1px 0 0;
        border-style: solid;
        margin: 0;
        padding: .25em .75em;
        background-color: #FFC;
    }
 </style>

How do I include a file over 2 directories back?

../../../index.php

         

Simple dictionary in C++

Until I was really concerned about performance, I would use a function, that takes a base and returns its match:

char base_pair(char base)
{
    switch(base) {
        case 'T': return 'A';
        ... etc
        default: // handle error
    }
}

If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.

Parameterize an SQL IN clause

Here is another answer to this problem.

(new version posted on 6/4/13).

    private static DataSet GetDataSet(SqlConnectionStringBuilder scsb, string strSql, params object[] pars)
    {
        var ds = new DataSet();
        using (var sqlConn = new SqlConnection(scsb.ConnectionString))
        {
            var sqlParameters = new List<SqlParameter>();
            var replacementStrings = new Dictionary<string, string>();
            if (pars != null)
            {
                for (int i = 0; i < pars.Length; i++)
                {
                    if (pars[i] is IEnumerable<object>)
                    {
                        List<object> enumerable = (pars[i] as IEnumerable<object>).ToList();
                        replacementStrings.Add("@" + i, String.Join(",", enumerable.Select((value, pos) => String.Format("@_{0}_{1}", i, pos))));
                        sqlParameters.AddRange(enumerable.Select((value, pos) => new SqlParameter(String.Format("@_{0}_{1}", i, pos), value ?? DBNull.Value)).ToArray());
                    }
                    else
                    {
                        sqlParameters.Add(new SqlParameter(String.Format("@{0}", i), pars[i] ?? DBNull.Value));
                    }
                }
            }
            strSql = replacementStrings.Aggregate(strSql, (current, replacementString) => current.Replace(replacementString.Key, replacementString.Value));
            using (var sqlCommand = new SqlCommand(strSql, sqlConn))
            {
                if (pars != null)
                {
                    sqlCommand.Parameters.AddRange(sqlParameters.ToArray());
                }
                else
                {
                    //Fail-safe, just in case a user intends to pass a single null parameter
                    sqlCommand.Parameters.Add(new SqlParameter("@0", DBNull.Value));
                }
                using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                {
                    sqlDataAdapter.Fill(ds);
                }
            }
        }
        return ds;
    }

Cheers.

Why can't DateTime.Parse parse UTC date

Just use that:

var myDateUtc = DateTime.SpecifyKind(DateTime.Parse("Tue, 1 Jan 2008 00:00:00"), DateTimeKind.Utc);

if (myDateUtc.Kind == DateTimeKind.Utc)
{
     Console.WriteLine("Yes. I am UTC!");
}

You can test this code using the online c# compiler:

http://rextester.com/

I hope it helps.

How to leave/exit/deactivate a Python virtualenv

I use zsh-autoenv which is based off autoenv.

zsh-autoenv automatically sources (known/whitelisted) .autoenv.zsh files, typically used in project root directories. It handles "enter" and leave" events, nesting, and stashing of variables (overwriting and restoring).

Here is an example:

; cd dtree 
Switching to virtual environment: Development tree utiles
;dtree(feature/task24|?); cat .autoenv.zsh       
# Autoenv.
echo -n "Switching to virtual environment: "
printf "\e[38;5;93m%s\e[0m\n" "Development tree utiles"
workon dtree
# eof
dtree(feature/task24|?); cat .autoenv_leave.zsh 
deactivate

So when I leave the dtree directory, the virtual environment is automatically exited.

"Development tree utiles" is just a name… No hidden mean linking to the Illuminati in here.

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
    begin
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar
        end
    end

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

Is there a way to programmatically scroll a scroll view to a specific edit text?

My EditText was nested several layers inside my ScrollView, which itself isn't the layout's root view. Because getTop() and getBottom() were seeming to report the coordinates within it's containing view, I had it compute the distance from the top of the ScrollView to the top of the EditText by iterating through the parents of the EditText.

// Scroll the view so that the touched editText is near the top of the scroll view
new Thread(new Runnable()
{
    @Override
    public
    void run ()
    {
        // Make it feel like a two step process
        Utils.sleep(333);

        // Determine where to set the scroll-to to by measuring the distance from the top of the scroll view
        // to the control to focus on by summing the "top" position of each view in the hierarchy.
        int yDistanceToControlsView = 0;
        View parentView = (View) m_editTextControl.getParent();
        while (true)
        {
            if (parentView.equals(scrollView))
            {
                break;
            }
            yDistanceToControlsView += parentView.getTop();
            parentView = (View) parentView.getParent();
        }

        // Compute the final position value for the top and bottom of the control in the scroll view.
        final int topInScrollView = yDistanceToControlsView + m_editTextControl.getTop();
        final int bottomInScrollView = yDistanceToControlsView + m_editTextControl.getBottom();

        // Post the scroll action to happen on the scrollView with the UI thread.
        scrollView.post(new Runnable()
        {
            @Override
            public void run()
            {
                int height =m_editTextControl.getHeight();
                scrollView.smoothScrollTo(0, ((topInScrollView + bottomInScrollView) / 2) - height);
                m_editTextControl.requestFocus();
            }
        });
    }
}).start();

How to change the playing speed of videos in HTML5?

According to this site, this is supported in the playbackRate and defaultPlaybackRate attributes, accessible via the DOM. Example:

/* play video twice as fast */
document.querySelector('video').defaultPlaybackRate = 2.0;
document.querySelector('video').play();

/* now play three times as fast just for the heck of it */
document.querySelector('video').playbackRate = 3.0;

The above works on Chrome 43+, Firefox 20+, IE 9+, Edge 12+.

How to play YouTube video in my Android application?

This answer could be really late, but its useful.

You can play youtube videos in the app itself using android-youtube-player.

Some code snippets:

To play a youtube video that has a video id in the url, you simply call the OpenYouTubePlayerActivity intent

Intent intent = new Intent(null, Uri.parse("ytv://"+v), this, 
            OpenYouTubePlayerActivity.class);
startActivity(intent);

where v is the video id.

Add the following permissions in the manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

and also declare this activity in the manifest file:

<activity 
        android:name="com.keyes.youtube.OpenYouTubePlayerActivity"></activity>

Further information can be obtained from the first portions of this code file.

Hope that helps anyone!

Uncaught TypeError: Cannot set property 'onclick' of null

Make sure your javascript is being executed after your element(s) have loaded, perhaps try putting the js file call just before the tag or use the defer attribute in your script, like so: <script src="app.js" defer></script> this makes sure that your script will be executed after the dom has loaded.

Javascript: How to pass a function with string parameters as a parameter to another function

Me, I'd do it something like this:

HTML:

onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"

JS:

function myfunction(params)
{
  var path = params.path;

  /* do stuff */

  // on ok condition 
  params.ok(params.okArgs);

  // on cancel condition
  params.cancel(params.cancelArgs);  
}

But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.

SVN Error - Not a working copy

You must have deleted a SVN - base file from your project (which are read-only files). Due to this you get this error.

Check out a fresh project again, merge the changes (if any) of your older SVN project with new one using "Winmerge" and commit the changes in your latest check out.

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

How to use stringstream to separate comma separated strings

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}

How to check object is nil or not in swift?

Normally, I just want to know if the object is nil or not.

So i use this function that just returns true when the object entered is valid and false when its not.

func isNotNil(someObject: Any?) -> Bool {
        if someObject is String {
            if (someObject as? String) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Array<Any> {
            if (someObject as? Array<Any>) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Dictionary<AnyHashable, Any> {
            if (someObject as? Dictionary<String, Any>) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Data {
            if (someObject as? Data) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is NSNumber {
            if (someObject as? NSNumber) != nil{
                return true
            }else {
                return false
            }
        }else if someObject is UIImage {
            if (someObject as? UIImage) != nil {
                return true
            }else {
                return false
            }
        }
        return false
 }

How to get back Lost phpMyAdmin Password, XAMPP

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command in the Shell:

mysqladmin.exe -u root password WhateverPassword

where 'WhateverPassword' is your new password.

Search an array for matching attribute

you can also use the Array.find feature of es6. the doc is here

return restaurants.find(item => {
   return item.restaurant.food == 'chicken'
})

Is it possible to decompile a compiled .pyc file into a .py file?

Yes.

I use uncompyle6 decompile (even support latest Python 3.8.0):

uncompyle6 utils.cpython-38.pyc > utils.py

and the origin python and decompiled python comparing look like this:

pyc uncompile utils

so you can see, ALMOST same, decompile effect is VERY GOOD.

List all devices, partitions and volumes in Powershell

You can also do it on the CLI with

net use

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

Troubleshooting BadImageFormatException

It can typically occur when you changed the target framework of .csproj and reverted it back to what you started with.

Make sure 1 if supportedRuntime version="a different runtime from cs project target" under startup tag in app.config.

Make sure 2 That also means checking other autogenerated or other files in may be properties folder to see if there is no more runtime mismatch between these files and one that is defined in .csproj file.

These might just save you lot of time before you start trying different things with project properties to overcome the error.

How to ORDER BY a SUM() in MySQL?

Without a GROUP BY clause, any summation will roll all rows up into a single row, so your query will indeed not work. If you grouped by, say, name, and ordered by sum(c_counts+f_counts), then you might get some useful results. But you would have to group by something.

Basic example of using .ajax() with JSONP?

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";

Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.


NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.

RAW JavaScript demonstration (simple Twitter feed using JSONP):

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


Basic jQuery example (simple Twitter feed using JSONP):

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

Base64 decode snippet in C++

I think this one works better:

#include <string>

static const char* B64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static const int B64index[256] =
{
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  62, 63, 62, 62, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0,  0,  0,  0,  0,  0,
    0,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0,  0,  0,  0,  63,
    0,  26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};

const std::string b64encode(const void* data, const size_t &len)
{
    std::string result((len + 2) / 3 * 4, '=');
    char *p = (char*) data, *str = &result[0];
    size_t j = 0, pad = len % 3;
    const size_t last = len - pad;

    for (size_t i = 0; i < last; i += 3)
    {
        int n = int(p[i]) << 16 | int(p[i + 1]) << 8 | p[i + 2];
        str[j++] = B64chars[n >> 18];
        str[j++] = B64chars[n >> 12 & 0x3F];
        str[j++] = B64chars[n >> 6 & 0x3F];
        str[j++] = B64chars[n & 0x3F];
    }
    if (pad)  /// Set padding
    {
        int n = --pad ? int(p[last]) << 8 | p[last + 1] : p[last];
        str[j++] = B64chars[pad ? n >> 10 & 0x3F : n >> 2];
        str[j++] = B64chars[pad ? n >> 4 & 0x03F : n << 4 & 0x3F];
        str[j++] = pad ? B64chars[n << 2 & 0x3F] : '=';
    }
    return result;
}

const std::string b64decode(const void* data, const size_t &len)
{
    if (len == 0) return "";

    unsigned char *p = (unsigned char*) data;
    size_t j = 0,
        pad1 = len % 4 || p[len - 1] == '=',
        pad2 = pad1 && (len % 4 > 2 || p[len - 2] != '=');
    const size_t last = (len - pad1) / 4 << 2;
    std::string result(last / 4 * 3 + pad1 + pad2, '\0');
    unsigned char *str = (unsigned char*) &result[0];

    for (size_t i = 0; i < last; i += 4)
    {
        int n = B64index[p[i]] << 18 | B64index[p[i + 1]] << 12 | B64index[p[i + 2]] << 6 | B64index[p[i + 3]];
        str[j++] = n >> 16;
        str[j++] = n >> 8 & 0xFF;
        str[j++] = n & 0xFF;
    }
    if (pad1)
    {
        int n = B64index[p[last]] << 18 | B64index[p[last + 1]] << 12;
        str[j++] = n >> 16;
        if (pad2)
        {
            n |= B64index[p[last + 2]] << 6;
            str[j++] = n >> 8 & 0xFF;
        }
    }
    return result;
}

std::string b64encode(const std::string& str)
{
    return b64encode(str.c_str(), str.size());
}

std::string b64decode(const std::string& str64)
{
    return b64decode(str64.c_str(), str64.size());
}

Thanks to Jens Alfke for pointing out a performance issue, I have made some modifications to this old post. This one works way faster than before. Its other advantage is smooth handling of corrupt data as well.

Last edition: Although in these kinds of problems, it seems that speed is an overkill, but just for the fun of it I have made some other modifications to make this one the fastest algorithm out there AFAIK. Special thanks goes to GaspardP for his valuable suggestions and nice benchmark.

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Your problem is in this line: Message messageObject = new Message ();
This error says that the Message class is not known at compile time.

So you need to import the Message class.

Something like this:

import package1.package2.Message;

Check this out.

http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html

Checking to see if a DateTime variable has had a value assigned

I generally prefer, where possible, to use the default value of value types to determine whether they've been set. This obviously isn't possible all the time, especially with ints - but for DateTimes, I think reserving the MinValue to signify that it hasn't been changed is fair enough. The benefit of this over nullables is that there's one less place where you'll get a null reference exception (and probably lots of places where you don't have to check for null before accessing it!)

Enabling/Disabling Microsoft Virtual WiFi Miniport

From accepted answer:

You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it

Maybe your device is hidden - first you should unhide it from the device manger, then re-enable the adapter from the device manger tools.

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

How to extract a string between two delimiters

Try as

String s = "ABC[ This is to extract ]";
        Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
        Matcher m = p.matcher(s);
        m.find();
        String text = m.group(1);
        System.out.println(text);

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.

How to delete all files from a specific folder?

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);

Or in a single line:

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);

How do I convert NSInteger to NSString datatype?

When compiling with support for arm64, this won't generate a warning:

[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];

Error: Java: invalid target release: 11 - IntelliJ IDEA

I added these two lines to build.gradle file

compileJava.options.fork = true
                                              
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk-11.0.8'

and it works

I am using windows and my project based on gradle

my jdk path -> 'C:\Program Files\Java\jdk-11.0.8'

please provide your jdk path

How to run an android app in background?

Starting an Activity is not the right approach for this behavior. Instead have your BroadcastReceiver use an intent to start a Service which can continue to run as long as possible. (See http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle)

See also Persistent service

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
    DTO dTO = new DTO();
    dTO.setrarchyID((Long) (rowMap.get("ID")));
}

IntelliJ and Tomcat.. Howto..?

Please verify that the required plug-ins are enabled in Settings | Plugins, most likely you've disabled several of them, that's why you don't see all the facet options.

For the step by step tutorial, see: Creating a simple Web application and deploying it to Tomcat.

How to Batch Rename Files in a macOS Terminal?

Using mmv

mmv '*_*_*' '#1_#3' *.png

Using both Python 2.x and Python 3.x in IPython Notebook

If you’re running Jupyter on Python 3, you can set up a Python 2 kernel like this:

python2 -m pip install ipykernel

python2 -m ipykernel install --user

http://ipython.readthedocs.io/en/stable/install/kernel_install.html

How do I get the max and min values from a set of numbers entered?

I tried to optimize solution by handling user input exceptions.

public class Solution {
    private static Integer TERMINATION_VALUE = 0;
    public static void main(String[] args) {
        Integer value = null;
        Integer minimum = Integer.MAX_VALUE;
        Integer maximum = Integer.MIN_VALUE;
        Scanner scanner = new Scanner(System.in);
        while (value != TERMINATION_VALUE) {
            Boolean inputValid = Boolean.TRUE;
            try {
                System.out.print("Enter a value: ");
                value = scanner.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Value must be greater or equal to " + Integer.MIN_VALUE + " and less or equals to " + Integer.MAX_VALUE );
                inputValid = Boolean.FALSE;
                scanner.next();
            }
            if(Boolean.TRUE.equals(inputValid)){
                minimum = Math.min(minimum, value);
                maximum = Math.max(maximum, value);
            }
        }
        if(TERMINATION_VALUE.equals(minimum) || TERMINATION_VALUE.equals(maximum)){
            System.out.println("There is not any valid input.");
        } else{
            System.out.println("Minimum: " + minimum);
            System.out.println("Maximum: " + maximum);
        }
        scanner.close();
    }
}

Line Break in XML formatting?

If you are refering to res strings, use CDATA with \n.

<string name="about">
    <![CDATA[
 Author: Sergio Abreu\n
 http://sites.sitesbr.net
  ]]>        
</string>

Show Youtube video source into HTML5 video tag?

Step 1: add &html5=True to your favorite youtube url

Step 2: Find <video/> tag in source

Step 3: Add controls="controls" to video tag: <video controls="controls"..../>

Example:

_x000D_
_x000D_
<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&amp;itag=43&amp;ipbits=0&amp;signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&amp;sver=3&amp;ratebypass=yes&amp;expire=1300417200&amp;key=yt1&amp;ip=0.0.0.0&amp;id=37da319914f6616c"></video>
_x000D_
_x000D_
_x000D_

Note there seems to some expire stuff. I don't know how long the src string will work.

Still testing myself.

Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.

How to add new elements to an array?

As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.

String[] where = new String[10];

This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a dynamically growing collection, use the ArrayList.

angular 2 sort and filter

This is my sort. It will do number sort , string sort and date sort .

import { Pipe , PipeTransform  } from "@angular/core";

@Pipe({
  name: 'sortPipe'
 })

export class SortPipe implements PipeTransform {

    transform(array: Array<string>, key: string): Array<string> {

        console.log("Entered in pipe*******  "+ key);


        if(key === undefined || key == '' ){
            return array;
        }

        var arr = key.split("-");
        var keyString = arr[0];   // string or column name to sort(name or age or date)
        var sortOrder = arr[1];   // asc or desc order
        var byVal = 1;


        array.sort((a: any, b: any) => {

            if(keyString === 'date' ){

                let left    = Number(new Date(a[keyString]));
                let right   = Number(new Date(b[keyString]));

                return (sortOrder === "asc") ? right - left : left - right;
            }
            else if(keyString === 'name'){

                if(a[keyString] < b[keyString]) {
                    return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
                } else if (a[keyString] > b[keyString]) {
                    return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
                } else {
                    return 0;
                }  
            }
            else if(keyString === 'age'){
                return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
            }

        });

        return array;

  }

}

Find duplicate values in R

A terser way, either with rev :

x[!(!duplicated(x) & rev(!duplicated(rev(x))))]

... rather than fromLast:

x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]

... and as a helper function to provide either logical vector or elements from original vector :

duplicates <- function(x, as.bool = FALSE) {
    is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
    if (as.bool) { is.dup } else { x[is.dup] }
}

Treating vectors as data frames to pass to table is handy but can get difficult to read, and the data.table solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.

how to pass list as parameter in function

You should always avoid using List<T> as a parameter. Not only because this pattern reduces the opportunities of the caller to store the data in a different kind of collection, but also the caller has to convert the data into a List first.

Converting an IEnumerable into a List costs O(n) complexity which is absolutely unneccessary. And it also creates a new object.

TL;DR you should always use a proper interface like IEnumerable or IQueryable based on what do you want to do with your collection. ;)

In your case:

public void foo(IEnumerable<DateTime> dateTimes)
{
}

Parse string to DateTime in C#

Try the following code

Month = Date = DateTime.Now.Month.ToString();   
Year = DateTime.Now.Year.ToString(); 
ViewBag.Today = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(Int32.Parse(Month)) + Year;

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

You can use noWeekends function to disable the weekend selection

  $(function() {
     $( "#datepicker" ).datepicker({
     beforeShowDay: $.datepicker.noWeekends
     });
     });

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

How to change indentation in Visual Studio Code?

Problem: The accepted answer does not actually fix the indentation in the current document.

Solution: Run Format Document to re-process the document according to current (new) settings.

Problem: The HTML docs in my projects are of type "Django HTML" not "HTML" and there is no formatter available.

Solution: Switch them to syntax "HTML", format them, then switch back to "Django HTML."

Problem: The HTML formatter doesn't know how to handle Django template tags and undoes much of my carefully applied nesting.

Solution: Install the Indent 4-2 extension, which performs indentation strictly, without regard to the current language syntax (which is what I want in this case).

JavaScript: location.href to open in new window/tab?

window.open(
  'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
  '_blank' // <- This is what makes it open in a new window.
);

Find the nth occurrence of substring in a string

Def:

def get_first_N_words(mytext, mylen = 3):
    mylist = list(mytext.split())
    if len(mylist)>=mylen: return ' '.join(mylist[:mylen])

To use:

get_first_N_words('  One Two Three Four ' , 3)

Output:

'One Two Three'

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Java way to check if a string is palindrome

I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:

import java.util.ArrayList;
import java.util.List;

public class PalindromeRecursiveBoolean {

    public static boolean isPalindrome(String str) {

        str = str.toUpperCase();
        char[] strChars = str.toCharArray();

        List<Character> word = new ArrayList<>();
        for (char c : strChars) {
            word.add(c);
        }

        while (true) {
            if ((word.size() == 1) || (word.size() == 0)) {
                return true;
            }
            if (word.get(0) == word.get(word.size() - 1)) {
                word.remove(0);
                word.remove(word.size() - 1);
            } else {
                return false;

            }

        }
    }
}
  1. If the string is made of no letters or just one letter, it is a palindrome.
  2. Otherwise, compare the first and last letters of the string.
    • If the first and last letters differ, then the string is not a palindrome
    • Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.

The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'

Total number of items defined in an enum

You can use the static method Enum.GetNames which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum

var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

Difference between final and effectively final

'Effectively final' is a variable which would not give compiler error if it were to be appended by 'final'

From a article by 'Brian Goetz',

Informally, a local variable is effectively final if its initial value is never changed -- in other words, declaring it final would not cause a compilation failure.

lambda-state-final- Brian Goetz

Node.js project naming conventions for files & folders

There are no conventions. There are some logical structure.

The only one thing that I can say: Never use camelCase file and directory names. Why? It works but on Mac and Windows there are no different between someAction and some action. I met this problem, and not once. I require'd a file like this:

var isHidden = require('./lib/isHidden');

But sadly I created a file with full of lowercase: lib/ishidden.js. It worked for me on mac. It worked fine on mac of my co-worker. Tests run without errors. After deploy we got a huge error:

Error: Cannot find module './lib/isHidden'

Oh yeah. It's a linux box. So camelCase directory structure could be dangerous. It's enough for a colleague who is developing on Windows or Mac.

So use underscore (_) or dash (-) separator if you need.

Detect IE version (prior to v9) in JavaScript

Simple solution stop thinking browser and use the year.

var year = eval(today.getYear());
if(year < 1900 )
 {alert('Good to go: All browsers and IE 9 & >');}
else
 {alert('Get with it and upgrade your IE to 9 or >');}

What is an optional value in Swift?

Here is an equivalent optional declaration in Swift:

var middleName: String?

This declaration creates a variable named middleName of type String. The question mark (?) after the String variable type indicates that the middleName variable can contain a value that can either be a String or nil. Anyone looking at this code immediately knows that middleName can be nil. It's self-documenting!

If you don't specify an initial value for an optional constant or variable (as shown above) the value is automatically set to nil for you. If you prefer, you can explicitly set the initial value to nil:

var middleName: String? = nil

for more detail for optional read below link

http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values

need to test if sql query was successful

if you're not using the -> format, you can do this:

$a = "SQL command...";
if ($b = mysqli_query($con,$a)) {
  // results was successful
} else {
  // result was not successful
}

Change image size with JavaScript

Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:

var i,L=document.images.length;
for(i=0;i<L;++i){
 document.images[i].style.height = 'auto'; //setting CSS value
 document.images[i].style.width = 'auto'; //setting CSS value
// document.images[i].height = ''; (don't need this, would be setting img.attribute)
// document.images[i].width = ''; (don't need this, would be setting img.attribute)
}

Class JavaLaunchHelper is implemented in two places

Same error, I upgrade my Junit and resolve it

org.junit.jupiter:junit-jupiter-api:5.0.0-M6

to

org.junit.jupiter:junit-jupiter-api:5.0.0

Difference between "module.exports" and "exports" in the CommonJs Module System

Rene's answer about the relationship between exports and module.exports is quite clear, it's all about javascript references. Just want to add that:

We see this in many node modules:

var app = exports = module.exports = {};

This will make sure that even if we changed module.exports, we can still use exports by making those two variables point to the same object.

python multithreading wait till all threads finished

In Python3, since Python 3.2 there is a new approach to reach the same result, that I personally prefer to the traditional thread creation/start/join, package concurrent.futures: https://docs.python.org/3/library/concurrent.futures.html

Using a ThreadPoolExecutor the code would be:

from concurrent.futures.thread import ThreadPoolExecutor
import time

def call_script(ordinal, arg):
    print('Thread', ordinal, 'argument:', arg)
    time.sleep(2)
    print('Thread', ordinal, 'Finished')

args = ['argumentsA', 'argumentsB', 'argumentsC']

with ThreadPoolExecutor(max_workers=2) as executor:
    ordinal = 1
    for arg in args:
        executor.submit(call_script, ordinal, arg)
        ordinal += 1
print('All tasks has been finished')

The output of the previous code is something like:

Thread 1 argument: argumentsA
Thread 2 argument: argumentsB
Thread 1 Finished
Thread 2 Finished
Thread 3 argument: argumentsC
Thread 3 Finished
All tasks has been finished

One of the advantages is that you can control the throughput setting the max concurrent workers.

Cannot connect to Database server (mysql workbench)

Forr me reason was that I tried to use newest MySQL Workbench 8.x to connect to MySQL Server 5.1 (both running on Windows Server 2012).

When I uninstalled MySQL Workbench 8.x and installed MySQL Workbench 6.3.10 it successfully connected to localhost database

Why do Sublime Text 3 Themes not affect the sidebar?

To Sidebar ceased to be white:

  1. Download default theme because it is not in the folder sublime link here by default.sublime-Theme
  2. In sublime 3 preferences -- > > Browse package
  3. create a folder called "default theme" and put the downloaded file

if you installed the theme setUI, setUI file.sublime-the theme is looking for the line with comment:

"// sidebar || BG of selected files"

and under it a string

"layer0. opacity: { "target": 0.0, "speed": 50.0, "interpolation": "smoothstep" }
replaceable target": 0.0 --> target": 1.0

jQuery selector regular expressions

If you just want to select elements that contain given string then you can use following selector:

$(':contains("search string")')

Getting the .Text value from a TextBox

Did you try using t.Text?

MySQL SELECT only not null values

You should use IS NOT NULL. (The comparison operators = and <> both give UNKNOWN with NULL on either side of the expression.)

SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;

Just for completeness I'll mention that in MySQL you can also negate the null safe equality operator but this is not standard SQL.

SELECT *
FROM table 
WHERE NOT (YourColumn <=> NULL);

Edited to reflect comments. It sounds like your table may not be in first normal form in which case changing the structure may make your task easier. A couple of other ways of doing it though...

SELECT val1 AS val
FROM  your_table
WHERE val1 IS NOT NULL
UNION ALL
SELECT val2 
FROM  your_table
WHERE val2 IS NOT NULL
/*And so on for all your columns*/

The disadvantage of the above is that it scans the table multiple times once for each column. That may possibly be avoided by the below but I haven't tested this in MySQL.

SELECT CASE idx
         WHEN 1 THEN val1
         WHEN 2 THEN val2
       END AS val
FROM   your_table
        /*CROSS JOIN*/
       JOIN (SELECT 1 AS idx
                   UNION ALL
                   SELECT 2) t
HAVING val IS NOT NULL  /*Can reference alias in Having in MySQL*/

Change value of input and submit form in JavaScript

This might help you.

Your HTML

<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>

Your Script

    <script>
        function save(){
            $('#myinput').val('1');
            $('#form').submit();
        }
    </script>

How do I determine if a checkbox is checked?

The line where you define lfckv is run whenever the browser finds it. When you put it into the head of your document, the browser tries to find lifecheck id before the lifecheck element is created. You must add your script below the lifecheck input in order for your code to work.

Place API key in Headers or URL

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.

find a minimum value in an array of floats

Python has a min() built-in function:

>>> darr = [1, 3.14159, 1e100, -2.71828]
>>> min(darr)
-2.71828

What is the difference between an interface and abstract class?

The main point is that:

  • Abstract is object oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization).
  • Interface is functionality oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces.

Display number with leading zeros

Use:

'00'[len(str(i)):] + str(i)

Or with the math module:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)

Can I change the headers of the HTTP request sent by the browser?

I was looking to do exactly the same thing (RESTful web service), and I stumbled upon this firefox addon, which lets you modify the accept headers (actually, any request headers) for requests. It works perfectly.

https://addons.mozilla.org/en-US/firefox/addon/967/

How to run jenkins as a different user

ISSUE 1:

Started by user anonymous

That does not mean that Jenkins started as an anonymous user.

It just means that the person who started the build was not logged in. If you enable Jenkins security, you can create usernames for people and when they log in, the

"Started by anonymous" 

will change to

"Started by < username >". 

Note: You do not have to enable security in order to run jenkins or to clone correctly.

If you want to enable security and create users, you should see the options at Manage Jenkins > Configure System.


ISSUE 2:

The "can't clone" error is a different issue altogether. It has nothing to do with you logging in to jenkins or enabling security. It just means that Jenkins does not have the credentials to clone from your git SCM.

Check out the Jenkins Git Plugin to see how to set up Jenkins to work with your git repository.

Hope that helps.

How do I find out what is hammering my SQL Server?

Run either of these a few second apart. You'll detect the high CPU connection. Or: stored CPU in a local variable, WAITFOR DELAY, compare stored and current CPU values

select * from master..sysprocesses
where status = 'runnable' --comment this out
order by CPU
desc

select * from master..sysprocesses
order by CPU
desc

May not be the most elegant but it'd effective and quick.

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

android on Text Change Listener

A bit late of a answer, but here is a reusable solution:

/**
 * An extension of TextWatcher which stops further callbacks being called as 
 * a result of a change happening within the callbacks themselves.
 */
public abstract class EditableTextWatcher implements TextWatcher {

    private boolean editing;

    @Override
    public final void beforeTextChanged(CharSequence s, int start, 
                                                    int count, int after) {
        if (editing)
            return;

        editing = true;
        try {
            beforeTextChange(s, start, count, after);
        } finally {
            editing = false;
        }
    }

    protected abstract void beforeTextChange(CharSequence s, int start, 
                                                     int count, int after);

    @Override
    public final void onTextChanged(CharSequence s, int start, 
                                                int before, int count) {
        if (editing)
            return;

        editing = true;
        try {
            onTextChange(s, start, before, count);
        } finally {
            editing = false;
        }
    }

    protected abstract void onTextChange(CharSequence s, int start, 
                                            int before, int count);

    @Override
    public final void afterTextChanged(Editable s) {
        if (editing)
            return;

        editing = true;
        try {
            afterTextChange(s);
        } finally {
            editing = false;
        }
    }

    public boolean isEditing() {
        return editing;
    }

    protected abstract void afterTextChange(Editable s);
}

So when the above is used, any setText() calls happening within the TextWatcher will not result in the TextWatcher being called again:

/**
 * A setText() call in any of the callbacks below will not result in TextWatcher being 
 * called again.
 */
public class MyTextWatcher extends EditableTextWatcher {

    @Override
    protected void beforeTextChange(CharSequence s, int start, int count, int after) {
    }

    @Override
    protected void onTextChange(CharSequence s, int start, int before, int count) {
    }

    @Override
    protected void afterTextChange(Editable s) {
    }
}

How do you add a Dictionary of items into another Dictionary

You can add a Dictionary extension like this:

extension Dictionary {
    func mergedWith(otherDictionary: [Key: Value]) -> [Key: Value] {
        var mergedDict: [Key: Value] = [:]
        [self, otherDictionary].forEach { dict in
            for (key, value) in dict {
                mergedDict[key] = value
            }
        }
        return mergedDict
    }
}

Then usage is as simple as the following:

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var combinedDict = dict1.mergedWith(dict2)
// => ["a": "foo", "b": "bar"]

If you prefer a framework that also includes some more handy features then checkout HandySwift. Just import it to your project and you can use the above code without adding any extensions to the project yourself.

How to make MySQL table primary key auto increment with some prefix

Here is PostgreSQL example without trigger if someone need it on PostgreSQL:

CREATE SEQUENCE messages_seq;

 CREATE TABLE IF NOT EXISTS messages (
    id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
    name CHAR(30) NOT NULL,
);

ALTER SEQUENCE messages_seq OWNED BY messages.id;

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

My problem was that I had @WebServlet("/route") and the same servlet declared in web.xml

Initializing a member array in constructor initializer

How about

...
  C() : arr{ {1,2,3} }
{}
...

?

Compiles fine on g++ 4.8

Java, Shifting Elements in an Array

In the first iteration of your loop, you overwrite the value in array[1]. You should go through the indicies in the reverse order.

How to capture Curl output to a file?

use --trace-asci output.txt can output the curl details to the output.txt

Android scale animation on view

Resize using helper methods and start-repeat-end handlers like this:

resize(
    view1,
    1.0f,
    0.0f,
    1.0f,
    0.0f,
    0.0f,
    0.0f,
    150,
    null,
    null,
    null);

  return null;
}

Helper methods:

/**
 * Resize a view.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration) {

  resize(
    view,
    fromX,
    toX,
    fromY,
    toY,
    pivotX,
    pivotY,
    duration,
    null,
    null,
    null);
}

/**
 * Resize a view with handlers.
 *
 * @param view     A view to resize.
 * @param fromX    X scale at start.
 * @param toX      X scale at end.
 * @param fromY    Y scale at start.
 * @param toY      Y scale at end.
 * @param pivotX   Rotate angle at start.
 * @param pivotY   Rotate angle at end.
 * @param duration Animation duration.
 * @param start    Actions on animation start. Otherwise NULL.
 * @param repeat   Actions on animation repeat. Otherwise NULL.
 * @param end      Actions on animation end. Otherwise NULL.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration,
  Callable start,
  Callable repeat,
  Callable end) {

  Animation animation;

  animation =
    new ScaleAnimation(
      fromX,
      toX,
      fromY,
      toY,
      Animation.RELATIVE_TO_SELF,
      pivotX,
      Animation.RELATIVE_TO_SELF,
      pivotY);

  animation.setDuration(
    duration);

  animation.setInterpolator(
    new AccelerateDecelerateInterpolator());

  animation.setFillAfter(true);

  view.startAnimation(
    animation);

  animation.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) {

      if (start != null) {
        try {

          start.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    }

    @Override
    public void onAnimationEnd(Animation animation) {

      if (end != null) {
        try {

          end.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    @Override
    public void onAnimationRepeat(
      Animation animation) {

      if (repeat != null) {
        try {

          repeat.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }  
    }
  });
}

Jquery select this + class

Use $(this).find(), or pass this in context, using jQuery context with selector.

Using $(this).find()

$(".class").click(function(){
     $(this).find(".subclass").css("visibility","visible");
});

Using this in context, $( selector, context ), it will internally call find function, so better to use find on first place.

$(".class").click(function(){
     $(".subclass", this).css("visibility","visible");
});

Download & Install Xcode version without Premium Developer Account

I am able to download it using apple's download website today. https://developer.apple.com/download/

I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

In your Dockerfile, run this first:

apt-get update && apt-get install -y gnupg2

How to use HTML to print header and footer on every printed page of a document?

Muhammad Musavi's comment is the best answer, so here it is surfaced as an actual Answer:

thead/tfoot are automatically repeated on the top and bottom of each page. However, tfoot isn't sticky to the bottom of the last page.

position: fixed in print will repeat on each page, and the footer will stick to the bottom of all pages including the last one - but, it won't create space for its contents.

Combine them:

HTML:

<header>(repeated header)</header>

<table class=paging><thead><tr><td>&nbsp;</td></tr></thead><tbody><tr><td>

(content goes here)

</td></tr></tbody><tfoot><tr><td>&nbsp;</td></tr></tfoot></table>

<footer>(repeated footer)</footer>

CSS:

@page {
    size: letter;
    margin: .5in;
}

@media print {
    table.paging thead td, table.paging tfoot td {
        height: .5in;
    }
}

header, footer {
    width: 100%; height: .5in;
}

header {
    position: absolute;
    top: 0;
}

@media print {
    header, footer {
        position: fixed;
    }
    
    footer {
        bottom: 0;
    }
}

There are a lot of niceties you can add in here, but I've intentionally slashed this to the bare minimum to get a cleanly rendering header and footer, appearing once on-screen and at the top and bottom of every printed page.

https://medium.com/@Idan_Co/the-ultimate-print-html-template-with-header-footer-568f415f6d2a

jQuery - find table row containing table cell containing specific text

I know this is an old post but I thought I could share an alternative [not as robust, but simpler] approach to searching for a string in a table.

$("tr:contains(needle)"); //where needle is the text you are searching for.

For example, if you are searching for the text 'box', that would be:

$("tr:contains('box')");

This would return all the elements with this text. Additional criteria could be used to narrow it down if it returns multiple elements

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

I would like to mention some of the possible ways here together with a pure javascript trick which works across all browsers:

// with jQuery 
$(document).ready(function(){ /* ... */ });

// shorter jQuery version 
$(function(){ /* ... */ });

// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){ 
    // your code goes here
}, false);

// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
    alert('DOM Ready!');
});

The trick here, as explained by the original author, is that we are checking the document.readyState property. If it contains the string in (as in uninitialized and loading, the first two DOM ready states out of 5) we set a timeout and check again. Otherwise, we execute the passed function.

And here's the jsFiddle for the trick which works across all browsers.

Thanks to Tutorialzine for including this in their book.

How to display Base64 images in HTML?

If you have PHP on the back-end, you can use this code:

$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="'.$src.'">';

Omitting one Setter/Getter in Lombok

User the below code for omit/excludes from creating setter and getter. value key should use inside @Getter and @Setter.

@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
private int mySecret;

Spring boot 2.3 version, this is working well.

How can I enable or disable the GPS programmatically on Android?

This code works on ROOTED phones:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] cmds = {"cd /system/bin" ,"settings put secure location_providers_allowed +gps"};
        try {
            Process p = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            for (String tmpCmd : cmds) {
                os.writeBytes(tmpCmd + "\n");
            }
            os.writeBytes("exit\n");
            os.flush();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

For turning off GPS you can use this command instead

settings put secure location_providers_allowed -gps

You can also toggle network accuracy using the following commands: for turning on use:

settings put secure location_providers_allowed +network

and for turning off you can use:

settings put secure location_providers_allowed -network

C# : changing listbox row color?

First use this Namespace:

using System.Drawing;

Add this anywhere on your form:

listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += listBox_DrawItem;

Here is the Event Handler:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
     e.DrawBackground();

     Graphics g = e.Graphics;
     g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
     ListBox lb = (ListBox)sender;
     g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));

     e.DrawFocusRectangle();
}

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

There are chances that you might end up with Scientific Number when you convert Integer to Str... safer way is

SET @ActualWeightDIMS = STR(@Actual_Dims_Width); OR Select STR(@Actual_Dims_Width) + str(@Actual_Dims_Width)

What exactly does big ? notation represent?

First let's understand what big O, big Theta and big Omega are. They are all sets of functions.

Big O is giving upper asymptotic bound, while big Omega is giving a lower bound. Big Theta gives both.

Everything that is ?(f(n)) is also O(f(n)), but not the other way around.
T(n) is said to be in ?(f(n)) if it is both in O(f(n)) and in Omega(f(n)).
In sets terminology, ?(f(n)) is the intersection of O(f(n)) and Omega(f(n))

For example, merge sort worst case is both O(n*log(n)) and Omega(n*log(n)) - and thus is also ?(n*log(n)), but it is also O(n^2), since n^2 is asymptotically "bigger" than it. However, it is not ?(n^2), Since the algorithm is not Omega(n^2).

A bit deeper mathematic explanation

O(n) is asymptotic upper bound. If T(n) is O(f(n)), it means that from a certain n0, there is a constant C such that T(n) <= C * f(n). On the other hand, big-Omega says there is a constant C2 such that T(n) >= C2 * f(n))).

Do not confuse!

Not to be confused with worst, best and average cases analysis: all three (Omega, O, Theta) notation are not related to the best, worst and average cases analysis of algorithms. Each one of these can be applied to each analysis.

We usually use it to analyze complexity of algorithms (like the merge sort example above). When we say "Algorithm A is O(f(n))", what we really mean is "The algorithms complexity under the worst1 case analysis is O(f(n))" - meaning - it scales "similar" (or formally, not worse than) the function f(n).

Why we care for the asymptotic bound of an algorithm?

Well, there are many reasons for it, but I believe the most important of them are:

  1. It is much harder to determine the exact complexity function, thus we "compromise" on the big-O/big-Theta notations, which are informative enough theoretically.
  2. The exact number of ops is also platform dependent. For example, if we have a vector (list) of 16 numbers. How much ops will it take? The answer is: it depends. Some CPUs allow vector additions, while other don't, so the answer varies between different implementations and different machines, which is an undesired property. The big-O notation however is much more constant between machines and implementations.

To demonstrate this issue, have a look at the following graphs: enter image description here

It is clear that f(n) = 2*n is "worse" than f(n) = n. But the difference is not quite as drastic as it is from the other function. We can see that f(n)=logn quickly getting much lower than the other functions, and f(n) = n^2 is quickly getting much higher than the others.
So - because of the reasons above, we "ignore" the constant factors (2* in the graphs example), and take only the big-O notation.

In the above example, f(n)=n, f(n)=2*n will both be in O(n) and in Omega(n) - and thus will also be in Theta(n).
On the other hand - f(n)=logn will be in O(n) (it is "better" than f(n)=n), but will NOT be in Omega(n) - and thus will also NOT be in Theta(n).
Symetrically, f(n)=n^2 will be in Omega(n), but NOT in O(n), and thus - is also NOT Theta(n).


1Usually, though not always. when the analysis class (worst, average and best) is missing, we really mean the worst case.

What are best practices for multi-language database design?

Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?

Would that require an IFNULL() and another SELECT statement for each field ?

The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.

Why does the JFrame setSize() method not set the size correctly?

JFrame SetSize() contains the the Area + Border.

I think you have to set the size of ContentPane of that

jFrame.getContentPane().setSize(800,400);

So I would advise you to use JPanel embedded in a JFrame and you draw on that JPanel. This would minimize your problem.

JFrame jf = new JFrame();
JPanel jp = new JPanel();
jp.setPreferredSize(new Dimension(400,800));// changed it to preferredSize, Thanks!
jf.getContentPane().add( jp );// adding to content pane will work here. Please read the comment bellow.
jf.pack();

I am reading this from Javadoc

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write:

frame.add(child);

However using JFrame you need to add the child to the JFrame's content pane instead:

frame.getContentPane().add(child);

How to pass the id of an element that triggers an `onclick` event to the event handling function

Here's a non-standard but cross-browser method that may be useful if you don't want to pass any arguments:-

Html:

<div onclick=myHandler() id="my element's id">&rarr; Click Here! &larr;</div>

Script:

function myHandler(){
    alert(myHandler.caller.arguments[0].target.id)
}

Demo: http://codepen.io/mrmoje/pen/ouJtk

Property 'value' does not exist on type 'EventTarget'

Angular 10+

Open tsconfig.json and disable strictDomEventTypes.

  "angularCompilerOptions": {
    ....
    ........
    "strictDomEventTypes": false
  }

Collision Detection between two images in Java

I think your problem is that you are not using good OO design for your player and enemies. Create two classes:

public class Player
{
    int X;
    int Y;
    int Width;
    int Height;

    // Getters and Setters
}

public class Enemy
{
    int X;
    int Y;
    int Width;
    int Height;

    // Getters and Setters
}

Your Player should have X,Y,Width,and Height variables.

Your enemies should as well.

In your game loop, do something like this (C#):

foreach (Enemy e in EnemyCollection)
{
    Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);
    Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);

    // Assuming there is an intersect method, otherwise just handcompare the values
    if (r.Intersects(p))
    {
       // A Collision!
       // we know which enemy (e), so we can call e.DoCollision();
       e.DoCollision();
    }
}

To speed things up, don't bother checking if the enemies coords are offscreen.

Calling an executable program using awk

I was able to have this done via below method

cat ../logs/em2.log.1 |grep -i 192.168.21.15 |awk '{system(`date`); print $1}'

awk has a function called system it enables you to execute any linux bash command within the output of awk.

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

You are using setTimeout wrong way. The (one of) function signature is setTimeout(callback, delay). So you can easily specify what code should be run after what delay.

var codeAddress = (function() {
    var index = 0;
    var delay = 100;

    function GeocodeCallback(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
            console.log(results);
        }
        else alert("Geocode was not successful for the following reason: " + status);
    };

    return function(vPostCode) {
        if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
        index++;
    };
})();

This way, every codeAddress() call will result in geocoder.geocode() being called 100ms later after previous call.

I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay variable.

Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Difference between Spring MVC and Spring Boot

To add my once cent, Java Spring is a framework while Java Spring Boot is addon to accelerate it by providing pre-configurations and or easy to use components. It is always recommended to have fundamental concepts of Java Spring before jumping to Java Spring Boot.

get all the elements of a particular form

document.getElementById("someFormId").elements;

This collection will also contain <select>, <textarea> and <button> elements (among others), but you probably want that.

How to set seekbar min and max value

The easiest way to set a min and max value to a seekbar for me: if you want values min=60 to max=180, this is equal to min=0 max=120. So in your seekbar xml set property:

android:max="120"

min will be always 0.

Now you only need to do what your are doing, add the amount to get your translated value in any change, in this case +60.

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int translatedProgress = progress + 60;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

Be careful with the seekbar property android:progress, if you change the range you must recalculate your initial progress. If you want 50%, max/2, in my example 120/2 = 60;

How to hide output of subprocess in Python 2.7

As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.

Your code would be updated as such:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)

How to fix "Incorrect string value" errors?

The solution for me when running into this Incorrect string value: '\xF8' for column error using scriptcase was to be sure that my database is set up for utf8 general ci and so are my field collations. Then when I do my data import of a csv file I load the csv into UE Studio then save it formatted as utf8 and Voila! It works like a charm, 29000 records in there no errors. Previously I was trying to import an excel created csv.

Is there any JSON Web Token (JWT) example in C#?

It would be better to use standard and famous libraries instead of writing the code from scratch.

  1. JWT for encoding and decoding JWT tokens
  2. Bouncy Castle supports encryption and decryption, especially RS256 get it here

Using these libraries you can generate a JWT token and sign it using RS256 as below.

    public string GenerateJWTToken(string rsaPrivateKey)
    {
        var rsaParams = GetRsaParameters(rsaPrivateKey);
        var encoder = GetRS256JWTEncoder(rsaParams);

        // create the payload according to the Google's doc
        var payload = new Dictionary<string, object>
        {
            { "iss", ""},
            { "sub", "" },
            // and other key-values according to the doc
        };

        // add headers. 'alg' and 'typ' key-values are added automatically.
        var header = new Dictionary<string, object>
        {
            { "kid", "{your_private_key_id}" },
        };

        var token = encoder.Encode(header,payload, new byte[0]);

        return token;
    }

    private static IJwtEncoder GetRS256JWTEncoder(RSAParameters rsaParams)
    {
        var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(rsaParams);

        var algorithm = new RS256Algorithm(csp, csp);
        var serializer = new JsonNetSerializer();
        var urlEncoder = new JwtBase64UrlEncoder();
        var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        return encoder;
    }

    private static RSAParameters GetRsaParameters(string rsaPrivateKey)
    {
        var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
        using (var ms = new MemoryStream(byteArray))
        {
            using (var sr = new StreamReader(ms))
            {
                // use Bouncy Castle to convert the private key to RSA parameters
                var pemReader = new PemReader(sr);
                var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
                return DotNetUtilities.ToRSAParameters(keyPair.Private as RsaPrivateCrtKeyParameters);
            }
        }
    }

ps: the RSA private key should have the following format:

-----BEGIN RSA PRIVATE KEY----- {base64 formatted value} -----END RSA PRIVATE KEY-----

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

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.

Saving image from PHP URL

If you have allow_url_fopen set to true:

$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));

Else use cURL:

$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

How to sort strings in JavaScript

In your operation in your initial question, you are performing the following operation:

item1.attr - item2.attr

So, assuming those are numbers (i.e. item1.attr = "1", item2.attr = "2") You still may use the "===" operator (or other strict evaluators) provided that you ensure type. The following should work:

return parseInt(item1.attr) - parseInt(item2.attr);

If they are alphaNumeric, then do use localCompare().

Using a remote repository with non-standard port

SSH based git access method can be specified in <repo_path>/.git/config using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:

URL style:

url = ssh://[user@]host.xz[:port]/path/to/repo.git/

SCP style:

url = [user@]host.xz:path/to/repo.git/

Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config host definition in your ~/.ssh/config such as:

Host my_git_host
HostName git.some.host.org
Port 24589
User not_a_root_user

Then you can test in a shell with:

ssh my_git_host

and alter your SCP-style URI in <repo_path>/.git/config as:

url = my_git_host:path/to/repo.git/

MySQL Results as comma separated list

Instead of using group concat() you can use just concat()

Select concat(Col1, ',', Col2) as Foo_Bar from Table1;

edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.

Auto-indent spaces with C in vim?

These two commands should do it:

:set autoindent
:set cindent

For bonus points put them in a file named .vimrc located in your home directory on linux

Any difference between await Promise.all() and multiple await?

In case of await Promise.all([task1(), task2()]); "task1()" and "task2()" will run parallel and will wait until both promises are completed (either resolved or rejected). Whereas in case of

const result1 = await t1;
const result2 = await t2;

t2 will only run after t1 has finished execution (has been resolved or rejected). Both t1 and t2 will not run parallel.

Structs data type in php?

I cobbled together a 'dynamic' struct class today, had a look tonight and someone has written something similar with better handling of constructor parameters, it might be worth a look:

http://code.activestate.com/recipes/577160-php-struct-port/

One of the comments on this page mentions an interesting thing in PHP - apparently you're able to cast an array as an object, which lets you refer to array elements using the arrow notation, as you would with a Struct pointer in C. The comment's example was as follows:

$z = array('foo' => 1, 'bar' => true, 'baz' => array(1,2,3));
//accessing values as properties
$y = (object)$z;
echo $y->foo;

I haven't tried this myself yet, but it may be that you could get the desired notation by just casting - if that's all you're after. These are of course 'dynamic' data structures, just syntactic sugar for accessing key/value pairs in a hash.

If you're actually looking for something more statically typed, then ASpencer's answer is the droid you're looking for (as Obi-Wan might say.)

Restricting JTextField input to Integers

Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.

The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.

For example: using-documentfilter-filterbypass

Also for tutorial help, please look at: Implementing a DocumentFilter.

Edit

For instance:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class DocFilter {
   public static void main(String[] args) {
      JTextField textField = new JTextField(10);

      JPanel panel = new JPanel();
      panel.add(textField);

      PlainDocument doc = (PlainDocument) textField.getDocument();
      doc.setDocumentFilter(new MyIntFilter());


      JOptionPane.showMessageDialog(null, panel);
   }
}

class MyIntFilter extends DocumentFilter {
   @Override
   public void insertString(FilterBypass fb, int offset, String string,
         AttributeSet attr) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.insert(offset, string);

      if (test(sb.toString())) {
         super.insertString(fb, offset, string, attr);
      } else {
         // warn the user and don't allow the insert
      }
   }

   private boolean test(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException e) {
         return false;
      }
   }

   @Override
   public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }

   }
}

Why is this important?

  • What if the user uses copy and paste to insert data into the text component? A KeyListener can miss this?
  • You appear to be desiring to check that the data can represent an int. What if they enter numeric data that doesn't fit?
  • What if you want to allow the user to later enter double data? In scientific notation?

How do I calculate someone's age based on a DateTime type birthday?

It can be this simple:

int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;

Returning IEnumerable<T> vs. IQueryable<T>

I would like to clarify a few things due to seemingly conflicting responses (mostly surrounding IEnumerable).

(1) IQueryable extends the IEnumerable interface. (You can send an IQueryable to something which expects IEnumerable without error.)

(2) Both IQueryable and IEnumerable LINQ attempt lazy loading when iterating over the result set. (Note that implementation can be seen in interface extension methods for each type.)

In other words, IEnumerables are not exclusively "in-memory". IQueryables are not always executed on the database. IEnumerable must load things into memory (once retrieved, possibly lazily) because it has no abstract data provider. IQueryables rely on an abstract provider (like LINQ-to-SQL), although this could also be the .NET in-memory provider.

Sample use case

(a) Retrieve list of records as IQueryable from EF context. (No records are in-memory.)

(b) Pass the IQueryable to a view whose model is IEnumerable. (Valid. IQueryable extends IEnumerable.)

(c) Iterate over and access the data set's records, child entities and properties from the view. (May cause exceptions!)

Possible Issues

(1) The IEnumerable attempts lazy loading and your data context is expired. Exception thrown because provider is no longer available.

(2) Entity Framework entity proxies are enabled (the default), and you attempt to access a related (virtual) object with an expired data context. Same as (1).

(3) Multiple Active Result Sets (MARS). If you are iterating over the IEnumerable in a foreach( var record in resultSet ) block and simultaneously attempt to access record.childEntity.childProperty, you may end up with MARS due to lazy loading of both the data set and the relational entity. This will cause an exception if it is not enabled in your connection string.

Solution

  • I have found that enabling MARS in the connection string works unreliably. I suggest you avoid MARS unless it is well-understood and explicitly desired.

Execute the query and store results by invoking resultList = resultSet.ToList() This seems to be the most straightforward way of ensuring your entities are in-memory.

In cases where the you are accessing related entities, you may still require a data context. Either that, or you can disable entity proxies and explicitly Include related entities from your DbSet.

Is there a unique Android device ID?

Yes, every Android device have a unique serial numbers you can able to get it from this code. Build.SERIAL. Note that it was only added in API level 9, and it may not be present on all devices. To get a unique ID on earlier platforms, you'll need to read something like the MAC address or IMEI.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

$ sudo npm i -g increase-memory-limit

Run from the root location of your project:

$ increase-memory-limit

This tool will append --max-old-space-size=4096 in all node calls inside your node_modules/.bin/* files.


Node.js version >= 8 - DEPRECATION NOTICE

Since NodeJs V8.0.0, it is possible to use the option --max-old-space-size. NODE_OPTIONS=options...

$ export NODE_OPTIONS=--max_old_space_size=4096

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

git push says "everything up-to-date" even though I have local changes

I know it is super old, but in my case I fixed it quite quick.

I was getting this same error while being one commit ahead of master. Then I found the current Stack Overflow post. However before proceeding with the suggested ideas, I just decided to make a new commit and try again with the push to origin and it worked smoothly.

I don't know why, but maybe it is useful for somebody else.

How to forcefully set IE's Compatibility Mode off from the server-side?

Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Maybe this url can help you: Activating Browser Modes with Doctype

Edit: Today we were able to override the compatibility view with: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

How to check if an user is logged in Symfony2 inside a controller?

If you using roles you could check for ROLE_USER that is the solution i use:

if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
    // user is logged in
} 

Items in JSON object are out of order using "json.dumps"?

hey i know it is so late for this answer but add sort_keys and assign false to it as follows :

json.dumps({'****': ***},sort_keys=False)

this worked for me

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

XPath: difference between dot and text()

There is big difference between dot (".") and text() :-

  • The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.

  • The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.

For an example :-

<a href="something.html">
  <img src="filename.gif">
  link
</a>

Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.

Hope it will help you..:)

Upgrade Node.js to the latest version on Mac OS

Nvm Nvm is a script-based node version manager. You can install it easily with a curl and bash one-liner as described in the documentation. It's also available on Homebrew.

Assuming you have successfully installed nvm. The following will install the latest version of node.

 nvm install node --reinstall-packages-from=node

The last option installs all global npm packages over to your new version. This way packages like mocha and node-inspector keep working.

N N is an npm-based node version manager. You can install it by installing first some version of node and then running npm install -g n.

Assuming you have successfully installed n. The following will install the latest version of node.

sudo n latest

Homebrew Homebrew is one of the two popular package managers for Mac. Assuming you have previously installed node with brew install node. You can get up-to-date with formulae and upgrade to the latest Node.js version with the following.

1 brew update
2 brew upgrade node

MacPorts MacPorts is the another package manager for Mac. The following will update the local ports tree to get access to updated versions. Then it will install the latest version of Node.js. This works even if you have previous version of the package installed.

1 sudo port selfupdate
2 sudo port install nodejs-devel

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

Using Keypress Event

  1. Array Method
var asciiCodeOfNumbers = [48, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57]
$(".numbersOnly").keypress(function (e) {
        if ($.inArray(e.which, asciiCodeOfNumbers) == -1)
            e.preventDefault();
    });
  1. Direct Method
$(".numbersOnly").keypress(function (e) {
        if (e.which < 48 || 57 < e.which)
            e.preventDefault();
    });

DateTime.Compare how to check if a date is less than 30 days old?

Compare is unnecessary, Days / TotalDays are unnecessary.

All you need is

if (expireDate < DateTime.Now) {
    // has expired
} else {
    // not expired
}

note this will work if you decide to use minutes or months or even years as your expiry criteria.

How to calculate the SVG Path for an arc (of a circle)

You want to use the elliptical Arc command. Unfortunately for you, this requires you to specify the Cartesian coordinates (x, y) of the start and end points rather than the polar coordinates (radius, angle) that you have, so you have to do some math. Here's a JavaScript function which should work (though I haven't tested it), and which I hope is fairly self-explanatory:

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = angleInDegrees * Math.PI / 180.0;
  var x = centerX + radius * Math.cos(angleInRadians);
  var y = centerY + radius * Math.sin(angleInRadians);
  return [x,y];
}

Which angles correspond to which clock positions will depend on the coordinate system; just swap and/or negate the sin/cos terms as necessary.

The arc command has these parameters:

rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y

For your first example:

rx=ry=25 and x-axis-rotation=0, since you want a circle and not an ellipse. You can compute both the starting coordinates (which you should Move to) and ending coordinates (x, y) using the function above, yielding (200, 175) and about (182.322, 217.678), respectively. Given these constraints so far, there are actually four arcs that could be drawn, so the two flags select one of them. I'm guessing you probably want to draw a small arc (meaning large-arc-flag=0), in the direction of decreasing angle (meaning sweep-flag=0). All together, the SVG path is:

M 200 175 A 25 25 0 0 0 182.322 217.678

For the second example (assuming you mean going the same direction, and thus a large arc), the SVG path is:

M 200 175 A 25 25 0 1 0 217.678 217.678

Again, I haven't tested these.

(edit 2016-06-01) If, like @clocksmith, you're wondering why they chose this API, have a look at the implementation notes. They describe two possible arc parameterizations, "endpoint parameterization" (the one they chose), and "center parameterization" (which is like what the question uses). In the description of "endpoint parameterization" they say:

One of the advantages of endpoint parameterization is that it permits a consistent path syntax in which all path commands end in the coordinates of the new "current point".

So basically it's a side-effect of arcs being considered as part of a larger path rather than their own separate object. I suppose that if your SVG renderer is incomplete it could just skip over any path components it doesn't know how to render, as long as it knows how many arguments they take. Or maybe it enables parallel rendering of different chunks of a path with many components. Or maybe they did it to make sure rounding errors didn't build up along the length of a complex path.

The implementation notes are also useful for the original question, since they have more mathematical pseudocode for converting between the two parameterizations (which I didn't realize when I first wrote this answer).

Angular2 - Http POST request parameters

In later versions of Angular2 there is no need of manually setting Content-Type header and encoding the body if you pass an object of the right type as body.

You simply can do this

import { URLSearchParams } from "@angular/http"


testRequest() {
  let data = new URLSearchParams();
  data.append('username', username);
  data.append('password', password);

  this.http
    .post('/api', data)
      .subscribe(data => {
            alert('ok');
      }, error => {
          console.log(error.json());
      });
}

This way angular will encode the body for you and will set the correct Content-Type header.

P.S. Do not forget to import URLSearchParams from @angular/http or it will not work.