Programs & Examples On #Jasmin

Jasmin is an assembler for the Java Virtual Machine. It takes ASCII descriptions of Java classes, written in a simple assembler-like syntax using the Java Virtual Machine instruction set. It converts them into binary Java class files, suitable for loading by a Java runtime system.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

Can not find module “@angular-devkit/build-angular”

Another issue could be with your dev-dependencies. Please check if they have been installed properly (check if they are availabe in the node_modules folder)

If not then a quick fix would be:

npm i --only=dev

Or check how your npm settings are regarding prod:

npm config get production

In case they are set to true - change them to false:

npm config set -g production false

and setup a new angular project.

Found that hint here: https://github.com/angular/angular-cli/issues/10661 (ken107 and lichunbin814)

Hope that helps.

Could not find module "@angular-devkit/build-angular"

for angular 6 and above

The working solution for me was

npm install

ng update

and finally

npm update

Error: Local workspace file ('angular.json') could not be found

I was trying to set my Ionic 4 app to run as a pwa. When I run the command:

ng add @angular/pwa

...got the error message. After some try and error I discovered that when my project was created the start command was wrong. I was using an Ionic 3 version:

ionic start myApp tabs --type=ionic-angular

And the correct is:

ionic start myApp tabs --type=angular

with no 'ionic-' in type. This solved the error.

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

The timeout you specify here needs to be shorter than the default timeout.

The default timeout is 5000 and the framework by default is jasmine in case of jest. You can specify the timeout inside the test by adding

jest.setTimeout(30000);

But this would be specific to the test. Or you can set up the configuration file for the framework.

Configuring Jest

// jest.config.js
module.exports = {
  // setupTestFrameworkScriptFile has been deprecated in
  // favor of setupFilesAfterEnv in jest 24
  setupFilesAfterEnv: ['./jest.setup.js']
}

// jest.setup.js
jest.setTimeout(30000)

See also these threads:

setTimeout per test #5055

Make jasmine.DEFAULT_TIMEOUT_INTERVAL configurable #652

P.S.: The misspelling setupFilesAfterEnv (i.e. setupFileAfterEnv) will also throw the same error.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

If it happens, then it means you have to upgrade your node.js. Simply uninstall your current node from your pc or mac and download the latest version from https://nodejs.org/en/

'mat-form-field' is not a known element - Angular 5 & Material2

When using the 'mat-form-field' MatInputModule needs to be imported also

import { 
    MatToolbarModule, 
    MatButtonModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule ,
    MatStepperModule,
    MatInputModule
} from '@angular/material';

No provider for HttpClient

In my case I found once I rebuild the app it worked.

I had imported the HttpClientModule as specified in the previous posts but I was still getting the error. I stopped the server, rebuilt the app (ng serve) and it worked.

Angular: Cannot Get /

For me it also was problem with path, but I had percentage sign in the root folder.

After I replaced %20 with space, it started to work :)

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

I had a similar issue and solved after running these instructions!

npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start

VSCode cannot find module '@angular/core' or any other modules

I solved this problem as follow:

  1. Open Visual studio code with your project.
  2. Terminal -> New Terminal.
  3. Write npm install.

Cannot find module '@angular/compiler'

I just run npm install and then ok.

How to upgrade Angular CLI project?

Solution that worked for me:

  • Delete node_modules and dist folder
  • (in cmd)>> ng update --all --force
  • (in cmd)>> npm install typescript@">=3.4.0 and <3.5.0" --save-dev --save-exact
  • (in cmd)>> npm install --save core-js
  • Commenting import 'core-js/es7/reflect'; in polyfill.ts
  • (in cmd)>> ng serve

can not find module "@angular/material"

That's what solved this problem for me.

I used:

npm install --save @angular/material @angular/cdk
npm install --save @angular/animations

but INSIDE THE APPLICATION'S FOLDER.

Source: https://medium.com/@ismapro/first-steps-with-angular-cli-and-angular-material-5a90406e9a4

How to execute only one test spec with angular-cli

Each of your .spec.ts file have all its tests grouped in describe block like this:

describe('SomeComponent', () => {...}

You can easily run just this single block, by prefixing the describe function name with f:

fdescribe('SomeComponent', () => {...}

If you have such function, no other describe blocks will run. Btw. you can do similar thing with it => fit and there is also a "blacklist" version - x. So:

  • fdescribe and fit causes only functions marked this way to run
  • xdescribe and xit causes all but functions marked this way to run

How can I mock an ES6 module import using Jest?

Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
  });
});

And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.

Angular 2 : No NgModule metadata found

I would recommend restarting the application. Most of the cases editor won't be able to detect the changes in the lazy loaded module.

Angular 2 Unit Tests: Cannot find name 'describe'

Only had to do the following to pick up @types in a Lerna Mono-repo where several node_modules exist.

npm install -D @types/jasmine

Then in each tsconfig.file of each module or app

"typeRoots": [
  "node_modules/@types",
  "../../node_modules/@types" <-- I added this line
],

How to write unit testing for Angular / TypeScript for private methods with Jasmine

As most of the developers don't recommend testing private function, Why not test it?.

Eg.

YourClass.ts

export class FooBar {
  private _status: number;

  constructor( private foo : Bar ) {
    this.initFooBar({});
  }

  private initFooBar(data){
    this.foo.bar( data );
    this._status = this.foo.foo();
  }
}

TestYourClass.spec.ts

describe("Testing foo bar for status being set", function() {

...

//Variable with type any
let fooBar;

fooBar = new FooBar();

...
//Method 1
//Now this will be visible
fooBar.initFooBar();

//Method 2
//This doesn't require variable with any type
fooBar['initFooBar'](); 
...
}

Thanks to @Aaron, @Thierry Templier.

toBe(true) vs toBeTruthy() vs toBeTrue()

There are a lot many good answers out there, i just wanted to add a scenario where the usage of these expectations might be helpful. Using element.all(xxx), if i need to check if all elements are displayed at a single run, i can perform -

expect(element.all(xxx).isDisplayed()).toBeTruthy(); //Expectation passes
expect(element.all(xxx).isDisplayed()).toBe(true); //Expectation fails
expect(element.all(xxx).isDisplayed()).toBeTrue(); //Expectation fails

Reason being .all() returns an array of values and so all kinds of expectations(getText, isPresent, etc...) can be performed with toBeTruthy() when .all() comes into picture. Hope this helps.

Code coverage for Jest built on top of Jasmine

This works for me:

 "jest": {
    "collectCoverage": true,
    "coverageReporters": ["json", "html"]
  },
  "scripts": {
    "test": "jest  --coverage"
  },

Run:

yarn/npm test

How do I mock a service that returns promise in AngularJS Jasmine unit test?

describe('testing a method() on a service', function () {    

    var mock, service

    function init(){
         return angular.mock.inject(function ($injector,, _serviceUnderTest_) {
                mock = $injector.get('service_that_is_being_mocked');;                    
                service = __serviceUnderTest_;
            });
    }

    beforeEach(module('yourApp'));
    beforeEach(init());

    it('that has a then', function () {
       //arrange                   
        var spy= spyOn(mock, 'actionBeingCalled').and.callFake(function () {
            return {
                then: function (callback) {
                    return callback({'foo' : "bar"});
                }
            };
        });

        //act                
        var result = service.actionUnderTest(); // does cleverness

        //assert 
        expect(spy).toHaveBeenCalled();  
    });
});

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

If you have an argument (done) in the it function try to remove it as well it's call within the function itself:

it("should broadcast delete message notification", function(/*done -> YOU SHOULD REMOVE IT */) {

    requestNotificationChannel.deleteMessage(1, 4);
    expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4 });
    // done(); -> YOU SHOULD REMOVE IT        
});

Jasmine JavaScript Testing - toBe vs toEqual

Thought someone might like explanation by (annotated) example:

Below, if my deepClone() function does its job right, the test (as described in the 'it()' call) will succeed:

describe('deepClone() array copy', ()=>{
    let source:any = {}
    let clone:any = source
    beforeAll(()=>{
        source.a = [1,'string literal',{x:10, obj:{y:4}}]
        clone = Utils.deepClone(source) // THE CLONING ACT TO BE TESTED - lets see it it does it right.
    })
    it('should create a clone which has unique identity, but equal values as the source object',()=>{
        expect(source !== clone).toBe(true) // If we have different object instances...
        expect(source).not.toBe(clone) // <= synonymous to the above. Will fail if: you remove the '.not', and if: the two being compared are indeed different objects.
        expect(source).toEqual(clone) // ...that hold same values, all tests will succeed.
    })
})

Of course this is not a complete test suite for my deepClone(), as I haven't tested here if the object literal in the array (and the one nested therein) also have distinct identity but same values.

How to spyOn a value property (rather than a method) with Jasmine

Suppose there is a method like this that needs testing The src property of the tiny image needs checking

function reportABCEvent(cat, type, val) {
                var i1 = new Image(1, 1);
                var link = getABC('creosote');
                    link += "&category=" + String(cat);
                    link += "&event_type=" + String(type);
                    link += "&event_value=" + String(val);
                    i1.src = link;
                }

The spyOn() below causes the "new Image" to be fed the fake code from the test the spyOn code returns an object that only has a src property

As the variable "hook" is scoped to be visible in the fake code in the SpyOn and also later after the "reportABCEvent" is called

describe("Alphabetic.ads", function() {
    it("ABC events create an image request", function() {
    var hook={};
    spyOn(window, 'Image').andCallFake( function(x,y) {
          hook={ src: {} }
          return hook;
      }
      );
      reportABCEvent('testa', 'testb', 'testc');
      expect(hook.src).
      toEqual('[zubzub]&arg1=testa&arg2=testb&event_value=testc');
    });

This is for jasmine 1.3 but might work on 2.0 if the "andCallFake" is altered to the 2.0 name

How do I override nested NPM dependency versions?

For those from 2018 and beyond, using npm version 5 or later: edit your package-lock.json: remove the library from "requires" section and add it under "dependencies".

For example, you want deglob package to use glob package version 3.2.11 instead of its current one. You open package-lock.json and see:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "glob": "7.1.2",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  }
},

Remove "glob": "7.1.2", from "requires", add "dependencies" with proper version:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  },
  "dependencies": {
    "glob": {
      "version": "3.2.11"
    }
  }
},

Now remove your node_modules folder, run npm install and it will add missing parts to the "dependencies" section.

Jasmine.js comparing arrays

You can compare an array like the below mentioned if the array has some values

it('should check if the array are equal', function() {
        var mockArr = [1, 2, 3];
        expect(mockArr ).toEqual([1, 2, 3]);
 });

But if the array that is returned from some function has more than 1 elements and all are zero then verify by using

expect(mockArray[0]).toBe(0);

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

Using Jasmine to spy on a function without an object

There is 2 alternative which I use (for jasmine 2)

This one is not quite explicit because it seems that the function is actually a fake.

test = createSpy().and.callFake(test); 

The second more verbose, more explicit, and "cleaner":

test = createSpy('testSpy', test).and.callThrough();

-> jasmine source code to see the second argument

How to write a test which expects an Error to be thrown in Jasmine?

As mentioned previously, a function needs to be passed to toThrow as it is the function you're describing in your test: "I expect this function to throw x"

expect(() => parser.parse(raw))
  .toThrow(new Error('Parsing is not possible'));

If using Jasmine-Matchers you can also use one of the following when they suit the situation;

// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
  .toThrowAnyError();

or

// I just want to know that an error of 
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
  .toThrowErrorOfType(TypeError);

CSS3 selector to find the 2nd div of the same class

.parent_class div:first-child + div

I just used the above to find the second div by chaining first-child with the + selector.

How to calculate the sum of the datatable column in asp.net?

You can do like..

DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);

C++ templates that accept only certain types

Well, you could create your template reading something like this:

template<typename T>
class ObservableList {
  std::list<T> contained_data;
};

This will however make the restriction implicit, plus you can't just supply anything that looks like a list. There are other ways to restrict the container types used, for example by making use of specific iterator types that do not exist in all containers but again this is more an implicit than an explicit restriction.

To the best of my knowledge a construct that would mirror the statement Java statement to its full extent does not exist in current standard.

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

In C++11, the introduction of concepts should make this easier but I don't think it'll do exactly what you'd want either.

Writing to a file in a for loop

That is because you are opening , writing and closing the file 10 times inside your for loop

myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

You should open and close your file outside for loop.

myfile = open('xyz.txt', 'w')
for line in lines:
    var1, var2 = line.split(",");
    myfile.write("%s\n" % var1)

myfile.close()
text_file.close()

You should also notice to use write and not writelines.

writelines writes a list of lines to your file.

Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python

Can I automatically increment the file build version when using Visual Studio?

Maybe, for this task, you can use code like this:

    private bool IncreaseFileVersionBuild()
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            try
            {
                var fi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.GetDirectories("Properties")[0].GetFiles("AssemblyInfo.cs")[0];
                var ve = System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string ol = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + ve.FileBuildPart.ToString() + "." + ve.FilePrivatePart.ToString();
                string ne = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + (ve.FileBuildPart + 1).ToString() + "." + ve.FilePrivatePart.ToString();
                System.IO.File.WriteAllText(fi.FullName, System.IO.File.ReadAllText(fi.FullName).Replace("[assembly: AssemblyFileVersion(\"" + ol + "\")]", "[assembly: AssemblyFileVersion(\"" + ne + "\")]"));
                return true;
            }
            catch
            {
                return false;
            }
        }
        return false;
    }

and call it from form loading.
With this code you can update any part of file info in AssemblyInfo.cs (but you must use "standard" directory structure).

How should I use try-with-resources with JDBC?

Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:

try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
    PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
    try {
        PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
        s.setInt(1, userid);
        return s;
    } catch (SQLException e) { throw new RuntimeException(e); }
    }).get();
    ResultSet resultSet = stmt.executeQuery()) {
}

keytool error Keystore was tampered with, or password was incorrect

I have solve this issue by using default password "changeit".

Making text background transparent but not text itself

For a fully transparent background use:

background: transparent;

Otherwise for a semi-transparent color fill use:

background: rgba(255,255,255,0.5); // or hsla(0, 0%, 100%, 0.5)

where the values are:

background: rgba(red,green,blue,opacity); // or hsla(hue, saturation, lightness, opacity)

You can also use rgba values for gradient backgrounds.

To get transparency on an image background simply reduce the opacity of the image in an image editor of you choice beforehand.

How to clear all input fields in a specific div with jQuery?

If you wanted to stay with a class level selector then you could do something like this (using the same jfiddle from Mahn)

$("div.fetch_results input:text").each(function() {
  this.value = "testing";
})?

This will select only the text input boxes within the div with a fetch_results class.

As with any jQuery this is just one way to do it. Ask 10 jQuery people this question and you will get 12 answers.

Read entire file in Scala?

Just like in Java, using CommonsIO library:

FileUtils.readFileToString(file, StandardCharsets.UTF_8)

Also, many answers here forget Charset. It's better to always provide it explicitly, or it will hit one day.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.

What parameters should I use in a Google Maps URL to go to a lat-lon?

This works to zoom into an area more then drop a pin: https://www.google.com/maps/@30.2,17.9820525,9z

And the params are:

@lat,lng,zoom

How to open a new HTML page using jQuery?

If you want to use jQuery, the .load() function is the correct function you are after;

But you are missing the # from the div1 id selector in the example 2)

This should work:

$("#div1").load("file2.html");

WSDL vs REST Pros and Cons

Regarding WSDL (meaning "SOAP") as being "heavy-weight". Heavy matters how? If the toolset is doing all the "heavy lifting" for you, then why does it matter?

I have never yet needed to consume a complicated REST API. When I do, I expect I'll wish for a WSDL, which my tools will gladly convert into a set of proxy classes, so I can just call what appear to be methods. Instead, I suspect that in order to consume a non-trivial REST-based API, it will be necessary to write by hand a substantial amount of "light-weight" code.

Even when that's all done, you still will have translated human-readable documentation into code, with all the attendant risk that the humans read it wrong. Since WSDL is a machine-readable description of the service, it's much harder to "read it wrong".


Just a note: since this post, I have had the opportunity to work with a moderately complicated REST service. I did, indeed, wish for a WSDL or the equivalent, and I did, indeed, have to write a lot of code by hand. In fact, a substantial part of the development time was spent removing the code duplication of all the code that called different service operations "by hand".

For homebrew mysql installs, where's my.cnf?

  1. $ps aux | grep mysqld /usr/local/opt/mysql/bin/mysqld --basedir=/usr/local/opt/mysql --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/opt/mysql/lib/plugin

  2. Drop your my.cf file to /usr/local/opt/mysql

  3. brew services restart mysql

Using classes with the Arduino

I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:

class AMLed
{
    private:
          uint8_t _ledPin;
          long _turnOffTime;

    public:
          AMLed(uint8_t pin);
          void setOn();
          void setOff();
          // Turn the led on for a given amount of time (relies
          // on a call to check() in the main loop()).
          void setOnForTime(int millis);
          void check();
};

And here is the main source

AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
    pinMode(_ledPin, OUTPUT);
}

void AMLed::setOn()
{
    digitalWrite(_ledPin, HIGH);
}

void AMLed::setOff()
{
    digitalWrite(_ledPin, LOW);
}

void AMLed::setOnForTime(int p_millis)
{
    _turnOffTime = millis() + p_millis;
    setOn();
}

void AMLed::check()
{
    if (_turnOffTime != 0 && (millis() > _turnOffTime))
    {
        _turnOffTime = 0;
        setOff();
    }
}

It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html

To use, I simply do something like this in the .pde file:

#include "AM_Led.h"

#define TIME_LED    12   // The port for the LED

AMLed test(TIME_LED);

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

After modifying the References in the Web.config file as mentioned above, we resolved the references.

I was facing similar issue.

For us we have reference Microsoft.Data.Edm.dll and OData.dll and other assemblies from Program Files:

C:\Program Files (x86)\Microsoft WCF Data Services\5.0
                          \bin\.NETFramework\Microsoft.Data.Edm.dll

and

C:\Program Files (x86)\Microsoft WCF Data Services\5.0
                        \bin\.NETFramework\Microsoft.Data.OData.dll

and version was 5.6.4.

Once I change the reference of both assemblies to C:\....Project\packages\Microsoft.Data.Edm.5.6.0 , the issue was resolved

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

c# how to add byte to byte array

As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:

var mahByteArray = new ArrayList<byte>();

If you have a byte array from elsewhere, you can use the AddRange function.

mahByteArray.AddRange(mahOldByteArray);

Then you can use Add() and Insert() to add elements.

mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.

Need it back in an array? .ToArray() has you covered!

mahOldByteArray = mahByteArray.ToArray();

Differences between fork and exec

fork() splits the current process into two processes. Or in other words, your nice linear easy to think of program suddenly becomes two separate programs running one piece of code:

 int pid = fork();

 if (pid == 0)
 {
     printf("I'm the child");
 }
 else
 {
     printf("I'm the parent, my child is %i", pid);
     // here we can kill the child, but that's not very parently of us
 }

This can kind of blow your mind. Now you have one piece of code with pretty much identical state being executed by two processes. The child process inherits all the code and memory of the process that just created it, including starting from where the fork() call just left off. The only difference is the fork() return code to tell you if you are the parent or the child. If you are the parent, the return value is the id of the child.

exec is a bit easier to grasp, you just tell exec to execute a process using the target executable and you don't have two processes running the same code or inheriting the same state. Like @Steve Hawkins says, exec can be used after you forkto execute in the current process the target executable.

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

You may also get this error if you have a name clash of a view and a module. I've got the error when i distribute my view files under views folder, /views/view1.py, /views/view2.py and imported some model named table.py in view2.py which happened to be a name of a view in view1.py. So naming the view functions as v_table(request,id) helped.

When is a C++ destructor called?

Remember that Constructor of an object is called immediately after the memory is allocated for that object and whereas the destructor is called just before deallocating the memory of that object.

Execute PHP script in cron job

I had the same problem... I had to run it as a user.

00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php

Convert UTC datetime string to local datetime

Consolidating the answer from franksands into a convenient method.

import calendar
import datetime

def to_local_datetime(utc_dt):
    """
    convert from utc datetime to a locally aware datetime according to the host timezone

    :param utc_dt: utc datetime
    :return: local timezone datetime
    """
    return datetime.datetime.fromtimestamp(calendar.timegm(utc_dt.timetuple()))

Docker how to change repository name or rename image?

docker run -it --name NEW_NAME Existing_name

To change the existing image name.

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

How to link 2 cell of excel sheet?

Just follow these Steps :

If you want the contents of, say, C1 to mirror the contents of cell A1, you just need to set the formula in C1 to =A1. From this point forward, anything you type in A1 will show up in C1 as well.

To Link Multiple Cells in Excel From Another Worksheet :

Step 1

Click the worksheet tab at the bottom of the screen that contains a range of precedent cells to which you want to link. A range is a block or group of adjacent cells. For example, assume you want to link a range of blank cells in “Sheet1” to a range of precedent cells in “Sheet2.” Click the “Sheet2” tab.

Step 2

Determine the precedent range’s width in columns and height in rows. In this example, assume cells A1 through A4 on “Sheet2” contain a list of numbers 1, 2, 3 and 4, respectively, which will be your precedent cells. This precedent range is one column wide by four rows high.

Step 3

Click the worksheet tab at the bottom of the screen that contains the blank cells in which you will insert a link. In this example, click the “Sheet1” tab.

Step 4

Select the range of blank cells you want to link to the precedent cells. This range must be the same size as the precedent range, but can be in a different location on the worksheet. Click and hold the mouse button on the top left cell of the range, drag the mouse cursor to the bottom right cell in the range and release the mouse button to select the range. In this example, assume you want to link cells C1 through C4 to the precedent range. Click and hold on cell C1, drag the mouse to cell C4 and release the mouse to highlight the range.

Step 5

Type “=,” the worksheet name containing the precedent cells, “!,” the top left cell of the precedent range, “:” and the bottom right cell of the precedent range. Press “Ctrl,” “Shift” and “Enter” simultaneously to complete the array formula. Each dependent cell is now linked to the cell in the precedent range that’s in the same respective location within the range. In this example, type “=Sheet2!A1:A4” and press “Ctrl,” “Shift” and “Enter” simultaneously. Cells C1 through C4 on “Sheet1” now contain the array formula “{=Sheet2!A1:A4}” surrounded by curly brackets, and show the same data as the precedent cells in “Sheet2.”

Good Luck !!!

Escape double quote in VB string

Another example:

Dim myPath As String = """" & Path.Combine(part1, part2) & """"

Good luck!

List of Stored Procedures/Functions Mysql Command Line

To show just yours:

SELECT
  db, type, specific_name, param_list, returns
FROM
  mysql.proc
WHERE
  definer LIKE
  CONCAT('%', CONCAT((SUBSTRING_INDEX((SELECT user()), '@', 1)), '%'));

Python using enumerate inside list comprehension

Try this:

[(i, j) for i, j in enumerate(mylist)]

You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:

[pair for pair in enumerate(mylist)]

Either way, the result that gets returned is as expected:

> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Filter Java Stream to 1 and only 1 element

For the sake of completeness, here is the ‘one-liner’ corresponding to @prunge’s excellent answer:

User user1 = users.stream()
        .filter(user -> user.getId() == 1)
        .reduce((a, b) -> {
            throw new IllegalStateException("Multiple elements: " + a + ", " + b);
        })
        .get();

This obtains the sole matching element from the stream, throwing

  • NoSuchElementException in case the stream is empty, or
  • IllegalStateException in case the stream contains more than one matching element.

A variation of this approach avoids throwing an exception early and instead represents the result as an Optional containing either the sole element, or nothing (empty) if there are zero or multiple elements:

Optional<User> user1 = users.stream()
        .filter(user -> user.getId() == 1)
        .collect(Collectors.reducing((a, b) -> null));

Get the string value from List<String> through loop for display

Use the For-Each loop which came with Java 1.5, and it work on Types which are iterable.

ArrayList<String> data = new ArrayList<String>();
data.add("Vivek");
data.add("Vadodara");
data.add("Engineer");
data.add("Feelance");

for (String s : data){

 System.out.prinln("Data of "+data.indexOf(s)+" "+s);

 }

How do I access nested HashMaps in Java?

If you plan on constructing HashMaps with variable depth, use a recursive data structure.

Below is an implementation providing a sample interface:

class NestedMap<K, V> {

    private final HashMap<K, NestedMap> child;
    private V value;

    public NestedMap() {
        child = new HashMap<>();
        value = null;
    }

    public boolean hasChild(K k) {
        return this.child.containsKey(k);
    }

    public NestedMap<K, V> getChild(K k) {
        return this.child.get(k);
    }

    public void makeChild(K k) {
        this.child.put(k, new NestedMap());
    }

    public V getValue() {
        return value;
    }

    public void setValue(V v) {
        value = v;
    }
}

and example usage:

class NestedMapIllustration {
    public static void main(String[] args) {

        NestedMap<Character, String> m = new NestedMap<>();

        m.makeChild('f');
        m.getChild('f').makeChild('o');
        m.getChild('f').getChild('o').makeChild('o');
        m.getChild('f').getChild('o').getChild('o').setValue("bar");

        System.out.println(
            "nested element at 'f' -> 'o' -> 'o' is " +
            m.getChild('f').getChild('o').getChild('o').getValue());
    }
}

How to compare strings in sql ignoring case?

To avoid string conversions comparisons, use COLLATE SQL_Latin1_General_CP1_CI_AS.

EXAMPLE:

SELECT UserName FROM Users
WHERE UserName **COLLATE SQL_Latin1_General_CP1_CI_AS** = 'Angel'

That will return any usernames, whether ANGEL, angel, or Angel, etc.

Logging POST data from $request_body

nginx log format taken from here: http://nginx.org/en/docs/http/ngx_http_log_module.html

no need to install anything extra

worked for me for GET and POST requests:

upstream my_upstream {
   server upstream_ip:upstream_port;
}

location / {
    log_format postdata '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$request_body"';
    access_log /path/to/nginx_access.log postdata;
    proxy_set_header Host $http_host;
    proxy_pass http://my_upstream;
    }
}

just change upstream_ip and upstream_port

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I was getting this same issue but in a different situation. I had a list of items in a list box. The user can click an item and select delete but I am using a stored proc to delete the item because there is a lot of logic involved in deleting the item. When I call the stored proc the delete works fine but any future call to SaveChanges will cause the error. My solution was to call the stored proc outside of EF and this worked fine. For some reason when I call the stored proc using the EF way of doing things it leaves something open.

Static way to get 'Context' in Android?

Assuming we're talking about getting the Application Context, I implemented it as suggested by @Rohit Ghatol extending Application. What happened then, it's that there's no guarantee that the context retrieved in such a way will always be non-null. At the time you need it, it's usually because you want to initialize an helper, or get a resource, that you cannot delay in time; handling the null case will not help you. So I understood I was basically fighting against the Android architecture, as stated in the docs

Note: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), include Context.getApplicationContext() as a Context argument when invoking your singleton's getInstance() method.

and explained by Dianne Hackborn

The only reason Application exists as something you can derive from is because during the pre-1.0 development one of our application developers was continually bugging me about needing to have a top-level application object they can derive from so they could have a more "normal" to them application model, and I eventually gave in. I will forever regret giving in on that one. :)

She is also suggesting the solution to this problem:

If what you want is some global state that can be shared across different parts of your app, use a singleton. [...] And this leads more naturally to how you should be managing these things -- initializing them on demand.

so what I did was getting rid of extending Application, and pass the context directly to the singleton helper's getInstance(), while saving a reference to the application context in the private constructor:

private static MyHelper instance;
private final Context mContext;    

private MyHelper(@NonNull Context context) {
    mContext = context.getApplicationContext();
}

public static MyHelper getInstance(@NonNull Context context) {
    synchronized(MyHelper.class) {
        if (instance == null) {
            instance = new MyHelper(context);
        }
        return instance;
    }
}

the caller will then pass a local context to the helper:

Helper.getInstance(myCtx).doSomething();

So, to answer this question properly: there are ways to access the Application Context statically, but they all should be discouraged, and you should prefer passing a local context to the singleton's getInstance().


For anyone interested, you can read a more detailed version at fwd blog

Change Spinner dropdown icon

Try applying following style to your spinner using

style="@style/SpinnerTheme"

//Spinner Style:

<style name="SpinnerTheme" parent="android:Widget.Spinner">
    <item name="android:background">@drawable/bg_spinner</item>
</style>

//bg_spinner.xml Replace the arrow_down_gray with your arrow

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

    <item>

        <layer-list>

            <item>
                <shape>
                    <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear" />

                    <stroke android:width="0.33dp" android:color="#0fb1fa" />

                    <corners android:radius="0dp" />

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
                </shape>
            </item>

            <item android:right="5dp">

                <bitmap android:gravity="center_vertical|right" android:src="@drawable/arrow_down_gray" />

            </item>

        </layer-list>

    </item>

</selector>

jQuery set radio button

Using .filter() also works, and is flexible for id, value, name:

$('input[name="cols"]').filter("[value='Site']").attr('checked', true);

(seen on this blog)

What does the red exclamation point icon in Eclipse mean?

The solution that worked for me is the following one given by Steve Hansen Smythe. I am just pasting it here. Thanks Steve.

"I found another scenario in which the red exclamation mark might appear. I copied a directory from one project to another. This directory included a hidden .svn directory (the original project had been committed to version control). When I checked my new project into SVN, the copied directory still contained the old SVN information, incorrectly identifying itself as an element in its original project.

I discovered the problem by looking at the Properties for the directory, selecting SVN Info, and reviewing the Resource URL. I fixed the problem by deleting the hidden .svn directory for my copied directory and refreshing my project. The red exclamation mark disappeared, and I was able to check in the directory and its contents correctly."

ImportError: No module named apiclient.discovery

You should be able to get these dependencies with this simple install:

sudo pip install --upgrade google-api-python-client

This is described on the quick start page for python.

How to debug a Flask app

From the 1.1.x documentation, you can enable debug mode by exporting an environment variable to your shell prompt:

export FLASK_APP=/daemon/api/views.py  # path to app
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0

slideToggle JQuery right to left

include Jquery and Jquery UI plugins and try this

 $("#LeftSidePane").toggle('slide','left',400);

EOFException - how to handle?

Alternatively, you could write out the number of elements first (as a header) using:

out.writeInt(prices.length);

When you read the file, you first read the header (element count):

int elementCount = in.readInt();

for (int i = 0; i < elementCount; i++) {
     // read elements
}

Using an IF Statement in a MySQL SELECT query

How to use an IF statement in the MySQL "select list":

select if (1>2, 2, 3);                         //returns 3
select if(1<2,'yes','no');                     //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes');  //returns no

How to use an IF statement in the MySQL where clause search condition list:

create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')

select * from penguins where 3 = id
-->3    skipper

select * from penguins where (if (true, 2, 3)) = id
-->2    kowalski

How to use an IF statement in the MySQL "having clause search conditions":

select * from penguins 
where 1=1
having (if (true, 2, 3)) = id
-->1    rico

Use an IF statement with a column used in the select list to make a decision:

select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1

If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.

List of installed gems?

This lists all the gems I have installed.

gem query --local

http://guides.rubygems.org/command-reference/#gem-list

See 2.7 Listing all installed gems

Read Numeric Data from a Text File in C++

The input operator for number skips leading whitespace, so you can just read the number in a loop:

while (myfile >> a)
{
    // ...
}

Rails: How can I rename a database column in a Ruby on Rails migration?

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Under Available Transformations

rename_column(table_name, column_name, new_column_name):

Renames a column but keeps the type and content.

php foreach with multidimensional array

I know this is quite an old answer. Here is a faster solution without using foreach:

Use array_column

print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'

Also you can check before executing the above operation

if(array_key_exists('firstname', $array)){
   print_r(array_column($array, 'firstname'));
}

How do I fill arrays in Java?

Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.

To fill the array with something else you can use Arrays.fill() or as part of the declaration

int[] a = new int[] {0, 0, 0, 0};

There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.

Render HTML string as real HTML in a React component

You can also use parseReactHTMLComponent from Jumper Package. Just look at it, it's easy and you don't need to use JSX syntax.

https://codesandbox.io/s/jumper-module-react-simple-parser-3b8c9?file=/src/App.js .

More on Jumper:

https://github.com/Grano22/jumper/blob/master/components.js

NPM Package:

https://www.npmjs.com/package/jumper_react

How to convert FormData (HTML5 object) to JSON

I am arriving late here. However, I made a simple method that checks for the input type="checkbox"

var formData = new FormData($form.get(0));
        var objectData = {};
        formData.forEach(function (value, key) {
            var updatedValue = value;
            if ($('input[name="' + key + '"]').attr("type") === "checkbox" && $('input[name="' + key + '"]').is(":checked")) {
                updatedValue = true; // we don't set false due to it is by default on HTML
            }
            objectData[key] = updatedValue;
        });
var jsonData = JSON.stringify(objectData);

I hope this helps somebody else.

SQL Server: Get table primary key using sql query

From memory, it's either this

SELECT * FROM sys.objects
WHERE type = 'PK' 
AND  object_id = OBJECT_ID ('tableName')

or this..

SELECT * FROM sys.objects
WHERE type = 'PK' 
AND  parent_object_id = OBJECT_ID ('tableName')

I think one of them should probably work depending on how the data is stored but I am afraid I have no access to SQL to actually verify the same.

Multi-statement Table Valued Function vs Inline Table Valued Function

Your examples, I think, answer the question very well. The first function can be done as a single select, and is a good reason to use the inline style. The second could probably be done as a single statement (using a sub-query to get the max date), but some coders may find it easier to read or more natural to do it in multiple statements as you have done. Some functions just plain can't get done in one statement, and so require the multi-statement version.

I suggest using the simplest (inline) whenever possible, and using multi-statements when necessary (obviously) or when personal preference/readability makes it wirth the extra typing.

Java: Check if command line arguments are null

@jjnguy's answer is correct in most circumstances. You won't ever see a null String in the argument array (or a null array) if main is called by running the application is run from the command line in the normal way.

However, if some other part of the application calls a main method, it is conceivable that it might pass a null argument or null argument array.

However(2), this is clearly a highly unusual use-case, and it is an egregious violation of the implied contract for a main entry-point method. Therefore, I don't think you should bother checking for null argument values in main. In the unlikely event that they do occur, it is acceptable for the calling code to get a NullPointerException. After all, it is a bug in the caller to violate the contract.

Android: I am unable to have ViewPager WRAP_CONTENT

I have faced this issue in several project already and never had a complete solution. So I created a WrapContentViewPager github project as a in-place replacement for ViewPager.

https://github.com/rnevet/WCViewPager

The solution was inspired by some of the answers here, but improves on:

  • Dynamically changes the ViewPager height according to current View including while scrolling.
  • Takes into consideration the height of "decor" views like PagerTabStrip.
  • Takes into consideration all Padding.

Updated for support library version 24 which broke previous implementation.

Adding a background image to a <div> element

Yes:

<div style="background-image: url(../images/image.gif); height: 400px; width: 400px;">Text here</div>

What is <scope> under <dependency> in pom.xml for?

The <scope> element can take 6 values: compile, provided, runtime, test, system and import.

This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.

compile

This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

provided

This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

runtime

This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

test

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

system

This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

import (only available in Maven 2.0.9 or later)

This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

To answer the second part of your question:

How can we use it for running test?

Note that the test scope allows to use dependencies only for the test phase.

Read the documentation for full details.

jQuery lose focus event

Like this:

$(selector).focusout(function () {
    //Your Code
});

Bash or KornShell (ksh)?

I don't have experience with ksh, but I have used both bash and zsh. I prefer zsh over bash because of its support for very powerful file globbing, variable expansion modifiers, and faster tab completion.

Here's a quick intro: http://friedcpu.wordpress.com/2007/07/24/zsh-the-last-shell-youll-ever-need/

Spring Boot application as a Service

My SysVInit script for Centos 6 / RHEL (not ideal yet). This script requires ApplicationPidListener.

Source of /etc/init.d/app

#!/bin/sh
#
# app Spring Boot Application 
#
# chkconfig:   345 20 80
# description: App Service
#           

### BEGIN INIT INFO
# Provides: App
# Required-Start: $local_fs $network
# Required-Stop: $local_fs $network
# Default-Start: 3 4 5 
# Default-Stop: 0 1 2 6
# Short-Description: Application
# Description:      
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

exec="/usr/bin/java"
prog="app"
app_home=/home/$prog/
user=$prog

[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

lockfile=/var/lock/subsys/$prog    
pid=$app_home/$prog.pid

start() {

    [ -x $exec ] || exit 5
    [ -f $config ] || exit 6
    # Check that networking is up.
    [ "$NETWORKING" = "no" ] && exit 1
    echo -n $"Starting $prog: "
    cd $app_home
    daemon --check $prog --pidfile $pid --user $user $exec $app_args &
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc -p $pid $prog
    retval=$?
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    restart
}

force_reload() {
    restart
}

rh_status() {
    status -p $pid $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        restart
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac
exit $?

Sample config file /etc/sysconfig/app:

exec=/opt/jdk1.8.0_05/jre/bin/java

user=myuser
app_home=/home/mysuer/

app_args="-jar app.jar"

pid=$app_home/app.pid

How to get last 7 days data from current datetime to last 7 days in sql server

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on    
from News    
WHERE CreatedDate>=DATEADD(DAY,-7,GETDATE())

Gradle - Could not find or load main class

For Netbeans 11 users, this works for me:

apply plugin: 'java'
apply plugin: 'application'

// This comes out to package + '.' + mainClassName
mainClassName = 'com.hello.JavaApplication1'

Here generally is my tree:

C:\...\NETBEANSPROJECTS\JAVAAPPLICATION1
¦   build.gradle
+---src
¦   +---main
¦   ¦   +---java
¦   ¦       +---com
¦   ¦           +---hello
¦   ¦                   JavaApplication1.java
¦   ¦
¦   +---test
¦       +---java
+---test

Swift programmatically navigate to another view controller/scene

According to @jaiswal Rajan in his answer. You can do a pushViewController like this:

let storyBoard: UIStoryboard = UIStoryboard(name: "NewBotStoryboard", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
self.navigationController?.pushViewController(newViewController, animated: true)

Make hibernate ignore class variables that are not mapped

Placing @Transient on getter with private field worked for me.

private String name;

    @Transient
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

Check if a value is in an array or not with Excel VBA

This Question was asked here: VBA Arrays - Check strict (not approximative) match

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

org.hibernate.MappingException: Unknown entity: annotations.Users

If you are using 5.0x version,configuration with standard service registry is deprecated.

Instead you should bootstrap it with Metadata: In your HibernateUtil class, you should add

private static SessionFactory buildSessionFactory() {
    try {           
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
            .configure( "hibernate.cfg.xml" )
            .build();

        Metadata metadata = new MetadataSources( standardRegistry )
            .getMetadataBuilder()
            .build();

        return metadata.getSessionFactoryBuilder().build();
    } catch(...) {
        ...
    }
}

Convert a python UTC datetime to a local datetime using only python standard library?

You can't do it with standard library. Using pytz module you can convert any naive/aware datetime object to any other time zone. Lets see some examples using Python 3.

Naive objects created through class method utcnow()

To convert a naive object to any other time zone, first you have to convert it into aware datetime object. You can use the replace method for converting a naive datetime object to an aware datetime object. Then to convert an aware datetime object to any other timezone you can use astimezone method.

The variable pytz.all_timezones gives you the list of all available time zones in pytz module.

import datetime,pytz

dtobj1=datetime.datetime.utcnow()   #utcnow class method
print(dtobj1)

dtobj3=dtobj1.replace(tzinfo=pytz.UTC) #replace method

dtobj_hongkong=dtobj3.astimezone(pytz.timezone("Asia/Hong_Kong")) #astimezone method
print(dtobj_hongkong)

Naive objects created through class method now()

Because now method returns current date and time, so you have to make the datetime object timezone aware first. The localize function converts a naive datetime object into a timezone-aware datetime object. Then you can use the astimezone method to convert it into another timezone.

dtobj2=datetime.datetime.now()

mytimezone=pytz.timezone("Europe/Vienna") #my current timezone
dtobj4=mytimezone.localize(dtobj2)        #localize function

dtobj_hongkong=dtobj4.astimezone(pytz.timezone("Asia/Hong_Kong")) #astimezone method
print(dtobj_hongkong)

Display the binary representation of a number in C?

There is no direct format specifier for this in the C language. Although I wrote this quick python snippet to help you understand the process step by step to roll your own.

#!/usr/bin/python

dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""

while dec >= base:
    solution = str(dec%base) + solution
    dec = dec/base
if dec > 0:
    solution = str(dec) + solution

print solution

Explained:

dec = input("Enter a decimal number to convert: ") - prompt the user for numerical input (there are multiple ways to do this in C via scanf for example)

base = 2 - specify our base is 2 (binary)

solution = "" - create an empty string in which we will concatenate our solution

while dec >= base: - while our number is bigger than the base entered

solution = str(dec%base) + solution - get the modulus of the number to the base, and add it to the beginning of our string (we must add numbers right to left using division and remainder method). the str() function converts the result of the operation to a string. You cannot concatenate integers with strings in python without a type conversion.

dec = dec/base - divide the decimal number by the base in preperation to take the next modulo

if dec > 0: solution = str(dec) + solution - if anything is left over, add it to the beginning (this will be 1, if anything)

print solution - print the final number

Accessing Google Account Id /username via Android

This Method to get Google Username:

 public String getUsername() {
    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<String>();

    for (Account account : accounts) {
        // TODO: Check possibleEmail against an email regex or treat
        // account.name as an email address only for certain account.type
        // values.
        possibleEmails.add(account.name);
    }

    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        String email = possibleEmails.get(0);
        String[] parts = email.split("@");
        if (parts.length > 0 && parts[0] != null)
            return parts[0];
        else
            return null;
    } else
        return null;
}

simple this method call ....

And Get Google User in Gmail id::

 accounts = AccountManager.get(this).getAccounts();
    Log.e("", "Size: " + accounts.length);
    for (Account account : accounts) {

        String possibleEmail = account.name;
        String type = account.type;

        if (type.equals("com.google")) {
            strGmail = possibleEmail;

            Log.e("", "Emails: " + strGmail);
            break;
        }
    }

After add permission in manifest;

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

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

MySQL - UPDATE multiple rows with different values in one query

UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3

Here col4 & col1 are in Table1. col2 & col3 are in Table2
I Am trying to update each col1 where col4 = col3 different value for each row

Android SDK location should not contain whitespace, as this cause problems with NDK tools

Just change

C:\Users\Giacomo B\AppData\Local\Android\sdk

to

C:\Users\Giacomo_B\AppData\Local\Android\sdk

SQL : BETWEEN vs <= and >=

Logically there are no difference at all. Performance-wise there are -typically, on most DBMSes- no difference at all.

How can a web application send push notifications to iOS devices?

To be more specific, in order for a web application to send push notifications to a mobile device, such as the iPhone, the mobile device must have registered to receive push notifications for a particular application. The registration for push notification is done through a native app and can only be performed through a native app. Once the native app is registered for push notification, it can send the authorization token to the server, which can be used in conjunction with the certificate used to provision the native client, to send the push notifications to the mobile device.

As specified in another answer, one option is to 'wrap' your web application in a native application. Meaning that you would create a native application that basically presents a UIWebView (for iPhone dev) to the user showing your web application. While this pretty much functions in the same manner as the native browser, you would be able to add the ability to register for push notifications using the native controls.

It would be beneficial to you to review the Apple's push notification document as it provides some pretty good information on how push messaging functions on the iPhone.

See these links provided by Peter Hosey:

Spark: subtract two DataFrames

I tried subtract, but the result was not consistent. If I run df1.subtract(df2), not all lines of df1 are shown on the result dataframe, probably due distinct cited on the docs.

This solved my problem: df1.exceptAll(df2)

Android: install .apk programmatically

Thank you for sharing this. I have it implemented and working. However:

1) I install ver 1 of my app (working no problem)
2) I place ver 2 on the server. the app retrieves ver2 and saves to SD card and prompts user to install the new package ver2
3) ver2 installs and works as expected
4) Problem is, every time the app starts it wants the user to re-install version 2 again.

So I was thinking the solution was simply delete the APK on the sdcard, but them the Async task wil simply retrieve ver2 again for the server.

So the only way to stop in from trying to install the v2 apk again is to remove from sdcard and from remote server.

As you can imagine that is not really going to work since I will never know when all users have received the lastest version.

Any help solving this is greatly appreciated.

I IMPLEMENTED THE "ldmuniz" method listed above.

NEW EDIT: Was just thinking all me APK's are named the same. Should I be naming the myapk_v1.0xx.apk and and in that version proactivily set the remote path to look for v.2.0 whenever it is released?

I tested the theory and it does SOLVE the issue. You need to name your APK file file some sort of versioning, remembering to always set your NEXT release version # in your currently released app. Not ideal but functional.

How to start an application without waiting in a batch file?

If start can't find what it's looking for, it does what you describe.

Since what you're doing should work, it's very likely you're leaving out some quotes (or putting extras in).

angular2 submit form by pressing enter without submit button

Just simply add (keyup.enter)="yourFunction()"

Round button with text and icon in flutter

Congrats to the previous answers... But I realised if the icons are in a row (say three icons as represented in the image above), you need to play around with columns and rows.

Here is the code

 Column(
        crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  FlatButton(
                      onPressed: () {},
                      child: Icon(
                        Icons.call,
                      )),
                  FlatButton(
                      onPressed: () {},
                      child: Icon(
                        Icons.message,
                      )),
                  FlatButton(
                      onPressed: () {},
                      child: Icon(
                        Icons.block,
                        color: Colors.red,
                      )),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Text(
                    '   Call',
                  ),
                  Text(
                    'Message',
                  ),
                  Text(
                    'Block',
                    style: TextStyle(letterSpacing: 2.0, color: Colors.red),
                  ),
                ],
              ),
            ],
          ),

Here is the result

What exactly is Spring Framework for?

Basically Spring is a framework for which is a pattern that allows building very decoupled systems.

The problem

For example, suppose you need to list the users of the system and thus declare an interface called UserLister:

public interface UserLister {
    List<User> getUsers();
}

And maybe an implementation accessing a database to get all the users:

public class UserListerDB implements UserLister {
    public List<User> getUsers() {
        // DB access code here
    }
}

In your view you'll need to access an instance (just an example, remember):

public class SomeView {
    private UserLister userLister;

    public void render() {
        List<User> users = userLister.getUsers();
        view.render(users);
    }
}

Note that the code above hasn't initialized the variable userLister. What should we do? If I explicitly instantiate the object like this:

UserLister userLister = new UserListerDB();

...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case, I would go to my code again and change the above line to:

UserLister userLister = new UserListerCommaSeparatedFile();

This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes? The maintenance becomes a nightmare!

Spring (Dependency Injection) approach

What Spring does is to wire the classes up by using an XML file or annotations, this way all the objects are instantiated and initialized by Spring and injected in the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).

Going back to the example in Spring we just need to have a setter for the userLister field and have either an XML file like this:

<bean id="userLister" class="UserListerDB" />

<bean class="SomeView">
    <property name="userLister" ref="userLister" />
</bean>

or more simply annotate the filed in our view class with @Inject:

@Inject
private UserLister userLister;

This way when the view is created it magically will have a UserLister ready to work.

List<User> users = userLister.getUsers();  // This will actually work
                                           // without adding any line of code

It is great! Isn't it?

  • What if you want to use another implementation of your UserLister interface? Just change the XML.
  • What if don't have a UserLister implementation ready? Program a temporal mock implementation of UserLister and ease the development of the view.
  • What if I don't want to use Spring anymore? Just don't use it! Your application isn't coupled to it. Inversion of Control states: "The application controls the framework, not the framework controls the application".

There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also, Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.

Hope this helps. Anyway, I encourage you to read Martin Fowler's article about Dependency Injection and Inversion of Control because he does it better than me. After understanding the basics take a look at Spring Documentation, in my opinion, it is used to be the best Spring book ever.

PostgreSQL: Why psql can't connect to server?

So for me and my pals working on a Node.js app (with Postgres and Sequelize), we had to

  1. brew install postgresql (one of us was missing postgres, one of us was not, and yet we were getting the same error msg as listed above)

  2. brew services start postgresql **** (utilize Homebrew to start postgres)

  3. createdb <name of database in config.json file>

  4. node_modules/.bin/sequelize db:migrate

  5. npm start

How to show all privileges from a user in oracle?

You can try these below views.

SELECT * FROM USER_SYS_PRIVS; 
SELECT * FROM USER_TAB_PRIVS;
SELECT * FROM USER_ROLE_PRIVS;

DBAs and other power users can find the privileges granted to other users with the DBA_ versions of these same views. They are covered in the documentation .

Those views only show the privileges granted directly to the user. Finding all the privileges, including those granted indirectly through roles, requires more complicated recursive SQL statements:

select * from dba_role_privs connect by prior granted_role = grantee start with grantee = '&USER' order by 1,2,3;
select * from dba_sys_privs  where grantee = '&USER' or grantee in (select granted_role from dba_role_privs connect by prior granted_role = grantee start with grantee = '&USER') order by 1,2,3;
select * from dba_tab_privs  where grantee = '&USER' or grantee in (select granted_role from dba_role_privs connect by prior granted_role = grantee start with grantee = '&USER') order by 1,2,3,4;

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it in production code. Joda is better.

import java.sql.Timestamp;

public class DateTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new Timestamp(System.currentTimeMillis()));
    }
}

window.close and self.close do not close the window in Chrome

Ordinary javascript cannot close windows willy-nilly. This is a security feature, introduced a while ago, to stop various malicious exploits and annoyances.

From the latest working spec for window.close():

The close() method on Window objects should, if all the following conditions are met, close the browsing context A:

  • The corresponding browsing context A is script-closable.
  • The browsing context of the incumbent script is familiar with the browsing context A.
  • The browsing context of the incumbent script is allowed to navigate the browsing context A.

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.

This means, with one small exception, javascript must not be allowed to close a window that was not opened by that same javascript.

Chrome allows that exception -- which it doesn't apply to userscripts -- however Firefox does not. The Firefox implementation flat out states:

This method is only allowed to be called for windows that were opened by a script using the window.open method.


If you try to use window.close from a Greasemonkey / Tampermonkey / userscript you will get:
Firefox: The error message, "Scripts may not close windows that were not opened by script."
Chrome: just silently fails.



The long-term solution:

The best way to deal with this is to make a Chrome extension and/or Firefox add-on instead. These can reliably close the current window.

However, since the security risks, posed by window.close, are much less for a Greasemonkey/Tampermonkey script; Greasemonkey and Tampermonkey could reasonably provide this functionality in their API (essentially packaging the extension work for you).
Consider making a feature request.



The hacky workarounds:

Chrome is currently was vulnerable to the "self redirection" exploit. So code like this used to work in general:

open(location, '_self').close();

This is buggy behavior, IMO, and is now (as of roughly April 2015) mostly blocked. It will still work from injected code only if the tab is freshly opened and has no pages in the browsing history. So it's only useful in a very small set of circumstances.

However, a variation still works on Chrome (v43 & v44) plus Tampermonkey (v3.11 or later). Use an explicit @grant and plain window.close(). EG:

// ==UserScript==
// @name        window.close demo
// @include     http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant       GM_addStyle
// ==/UserScript==

setTimeout (window.close, 5000);

Thanks to zanetu for the update. Note that this will not work if there is only one tab open. It only closes additional tabs.


Firefox is secure against that exploit. So, the only javascript way is to cripple the security settings, one browser at a time.

You can open up about:config and set
allow_scripts_to_close_windows to true.

If your script is for personal use, go ahead and do that. If you ask anyone else to turn that setting on, they would be smart, and justified, to decline with prejudice.

There currently is no equivalent setting for Chrome.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

first I had to delete my registry by using npm config delete registry and register new value using npm config set registry "http://registry.npmjs.org"

How to instantiate a File object in JavaScript?

Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File

var file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});

webpack: Module not found: Error: Can't resolve (with relative path)

Had the same issue with module not found. Turns out I had a component import Picture from './Picture/Picture'; at the very bottom of all the imports. When I moved it below import React, { Component } from 'react';, it worked.

What are the aspect ratios for all Android phone and tablet devices?

the best way to calculate the equation is simplified. That is, find the maximum divisor between two numbers and divide:

ex.

1920:1080 maximum common divisor 120 = 16:9
1024:768  maximum common divisor 256 = 4:3
1280:768  maximum common divisor 256 = 5:3

may happen also some approaches

Confirm deletion using Bootstrap 3 modal box

Create modal dialog in HTML with id="confirmation" and use function showConfirmation.

Also remember you should to unbind (modal.unbind()) cancel and success buttons after hide modal dialog. If you do not make this you will get double binding. For example: if you open dialog once and press 'Cancel' and then open dialog in second time and press 'Ok' you will get 2 executions of success callback.

showConfirmation = function(title, message, success, cancel) {
    title = title ? title : 'Are you sure?';
    var modal = $("#confirmation");
    modal.find(".modal-title").html(title).end()
        .find(".modal-body").html(message).end()
        .modal({ backdrop: 'static', keyboard: false })
        .on('hidden.bs.modal', function () {
            modal.unbind();
        });
    if (success) {
        modal.one('click', '.modal-footer .btn-primary', success);
    }
    if (cancel) {
        modal.one('click', '.modal-header .close, .modal-footer .btn-default', cancel);
    }
};

// bind confirmation dialog on delete buttons
$(document).on("click", ".delete-event, .delete-all-event", function(event){
    event.preventDefault();
    var self = $(this);
    var url = $(this).data('url');
    var success = function(){
        alert('window.location.href=url');
    }
    var cancel = function(){
        alert('Cancel');
    };
    if (self.data('confirmation')) {
        var title = self.data('confirmation-title') ? self.data('confirmation-title') : undefined;
        var message = self.data('confirmation');
        showConfirmation(title, message, success, cancel);
    } else {
        success();
    }
});

https://jsfiddle.net/yiiBoy/hne9sp6g/

Flatten List in LINQ

If you have a List<List<int>> k you can do

List<int> flatList= k.SelectMany( v => v).ToList();

Where is Java's Array indexOf?

The List interface has an indexOf() method, and you can obtain a List from your array with Array's asList() method. Other than that, Array itself has no such method. It does have a binarySearch() method for sorted arrays.

Animation CSS3: display + opacity

I used this to achieve it. They fade on hover but take no space when hidden, perfect!

.child {
    height: 0px;
    opacity: 0;
    visibility: hidden;
    transition: all .5s ease-in-out;
}

.parent:hover .child {
    height: auto;
    opacity: 1;
    visibility: visible;
}

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

PHP - Extracting a property from an array of objects

Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

Builtin loops in PHP are faster then interpreted loops, so it actually makes sense to make this one a one-liner:

$result = array();
array_walk($cats, create_function('$value, $key, &$result', '$result[] = $value->id;'), $result)

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

Intel's HAXM equivalent for AMD on Windows OS

Posting a new answer since it is 2019.

TLDR: AMD is now supported on both Windows and Linux via WHPX and yes, Genymotion is faster as it is using x86 architecture virtualization.

From the Android docs (January 2019):

Though we recommend using HAXM on Windows, it is possible to use Windows Hypervisor Platform (WHPX) with the emulator. You should use WHPX with the emulator if you are using an AMD CPU or if you need to use Hyper-V at the same time.

To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.

Additionally, the following changes must be made in the BIOS settings:

Intel CPU: VT-x must be enabled. AMD CPU: Virtualization or SVM must be enabled.

Diff from 2016:

Virtualization extension requirements

Before attempting to use acceleration, you should first determine if your CPU supports one of the following virtualization extensions technologies:

  1. Intel Virtualization Technology (VT, VT-x, vmx) extensions
  2. AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

Most modern computers do. If you use an older computer and you're not sure, consult the specifications from the manufacturer of your CPU to determine if it supports virtualization extensions. If your CPU doesn't support one of these virtualization technologies, then you can't use VM acceleration.

Virtualization extensions are typically enabled through your computer BIOS and are frequently turned off by default. Check the documentation for your motherboard to find out how to enable virtualization extensions.

Can I do a max(count(*)) in SQL?

SELECT * from 
(
SELECT yr as YEAR, COUNT(title) as TCOUNT
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr
order by TCOUNT desc
) res
where rownum < 2

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Refer to here

write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,

ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);

List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
    parameters.add(a.getId());

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);     
return sql;

How do I install Composer on a shared hosting?

You can do it that way:

  • Create a directory where you want to install composer (let's say /home/your_username/composer)
  • Go to this directory - cd /home/your_username/composer
  • Then run the following command:

    php -r "readfile('https://getcomposer.org/installer');" | php

  • After that if you want to run composer, you can do it this way (in this caseyou must be in the composer's dir): php composer.phar

  • As a next step, you can do this:

    alias composer="/home/your_username/composer/composer.phar".

    And run commands like you do it normally: $ composer install

Hope that helps

getFilesDir() vs Environment.getDataDirectory()

Try this

getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()

How do I declare a 2d array in C++ using new?

declaring 2D array dynamically:

    #include<iostream>
    using namespace std;
    int main()
    {
        int x = 3, y = 3;

        int **ptr = new int *[x];

        for(int i = 0; i<y; i++)
        {
            ptr[i] = new int[y];
        }
        srand(time(0));

        for(int j = 0; j<x; j++)
        {
            for(int k = 0; k<y; k++)
            {
                int a = rand()%10;
                ptr[j][k] = a;
                cout<<ptr[j][k]<<" ";
            }
            cout<<endl;
        }
    }

Now in the above code we took a double pointer and assigned it a dynamic memory and gave a value of the columns. Here the memory allocated is only for the columns, now for the rows we just need a for loop and assign the value for every row a dynamic memory. Now we can use the pointer just the way we use a 2D array. In the above example we then assigned random numbers to our 2D array(pointer).Its all about DMA of 2D array.

Bootstrap 4 Center Vertical and Horizontal Alignment

Bootstrap has text-center to center a text. For example

<div class="container text-center">

You change the following

<div class="row justify-content-center align-items-center">

to the following

<div class="row text-center">

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

In what cases do I use malloc and/or new?

new will initialise the default values of the struct and correctly links the references in it to itself.

E.g.

struct test_s {
    int some_strange_name = 1;
    int &easy = some_strange_name;
}

So new struct test_s will return an initialised structure with a working reference, while the malloc'ed version has no default values and the intern references aren't initialised.

In PHP with PDO, how to check the final SQL parametrized query?

You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .

Multiple selector chaining in jQuery?

like:

$('#Create .myClass, #Edit .myClass').plugin({ 
    options: here
});

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

ngFor with index as value in attribute

I think its already been answered before, but just a correction if you are populating an unordered list, the *ngFor will come in the element which you want to repeat. So it should be insdide <li>. Also, Angular2 now uses let to declare a variable.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">     
               {{item}}
    </li>
</ul>

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

Creating a Menu in Python

This should do it. You were missing a ) and you only need """ not 4 of them. Also you don't need a elif at the end.

ans=True
while ans:
    print("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ")
    if ans=="1":
      print("\nStudent Added")
    elif ans=="2":
      print("\n Student Deleted")
    elif ans=="3":
      print("\n Student Record Found")
    elif ans=="4":
      print("\n Goodbye") 
      ans = None
    else:
       print("\n Not Valid Choice Try again")

What is an Intent in Android?

From the paper Deep Dive into Android IPC/Binder Framework atAndroid Builders Summit 2013 link

The intent is understood in some small but effective lines

  1. Android supports a simple form of IPC(inter process communication) via intents
  2. Intent messaging is a framework for asynchronous communication among Android components (activity, service, content providers, broadcast receiver )
  3. Those components may run in the same or across different apps (i.e. processes)
  4. Enables both point-to-point as well as publish subscribe messaging domains
  5. The intent itself represents a message containing the description of the operation to be performed as well as data to be passed to the recipient(s).

From this thread a simple answer of android architect Dianne Hackborn states it as a data container which it actually is.

From android architecture point of view :

Intent is a data container that is used for inter process communication. It is built on top of the Binder from android architecture point of view.

Is Eclipse the best IDE for Java?

Eclipse was the first IDE to move me off of XEmacs. However, when my employer offered to buy me a Intellij IDEA license if I wanted one it only took 3 days with an evaluation copy to convince me to go for it.

It seems like so many small things are just nicer.

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

values_of_objArray = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

private ValueId : number = 0 // this will be used for multi access like 
                             // update, deleting the obj with id.
private selectedObj : any;

private selectedValueObj(id: any) {
  this.ValueId = (id.srcElement || id.target).value;
  for (let i = 0; i < this.values_of_objArray.length; i++) {
    if (this.values_of_objArray[i].id == this.ValueId) {
      this.selectedObj = this.values_of_objArray[i];
    }
  }
}

Now play with this.selectedObj which has the selected obj from the view.

HTML:

<select name="values_of_obj" class="form-control" [(ngModel)]="ValueId"  
        (change)="selectedValueObj($event)" required>

  <option *ngFor="let Value of values_of_objArray"
          [value]="Value.id">{{Value.name}}</option>    
</select>

How to get a list of current open windows/process with Java?

package com.vipul;

import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class BatchExecuteService extends Applet {
    public Choice choice;

    public void init() 
    {
        setFont(new Font("Helvetica", Font.BOLD, 36));
        choice = new Choice();
    }

    public static void main(String[] args) {
        BatchExecuteService batchExecuteService = new BatchExecuteService();
        batchExecuteService.run();
    }

    List<String> processList = new ArrayList<String>();

    public void run() {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("D:\\server.bat");
            process.getOutputStream().close();
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedrReader = new BufferedReader(
                    inputstreamreader);
            BufferedReader bufferedrReader1 = new BufferedReader(
                    inputstreamreader);

            String strLine = "";
            String x[]=new String[100];
            int i=0;
            int t=0;
            while ((strLine = bufferedrReader.readLine()) != null) 
            {
        //      System.out.println(strLine);
                String[] a=strLine.split(",");
                x[i++]=a[0];
            }
    //      System.out.println("Length : "+i);

            for(int j=2;j<i;j++)
            {
                System.out.println(x[j]);
            }
        }
        catch (IOException ioException) 
        {
            ioException.printStackTrace();
        }

    }
}
   You can create batch file like 

TASKLIST /v /FI "STATUS eq running" /FO "CSV" /FI "Username eq LHPL002\soft" /FI "MEMUSAGE gt 10000" /FI "Windowtitle ne N/A" /NH

Breadth First Vs Depth First

Understanding the terms:

This picture should give you the idea about the context in which the words breadth and depth are used.

Understanding Breadth and Depth


Depth-First Search:

Depth-First Search

  • Depth-first search algorithm acts as if it wants to get as far away from the starting point as quickly as possible.

  • It generally uses a Stack to remember where it should go when it reaches a dead end.

  • Rules to follow: Push first vertex A on to the Stack

    1. If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
    2. If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
    3. If you can’t follow Rule 1 or Rule 2, you’re done.
  • Java code:

    public void searchDepthFirst() {
        // Begin at vertex 0 (A)
        vertexList[0].wasVisited = true;
        displayVertex(0);
        stack.push(0);
        while (!stack.isEmpty()) {
            int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
            // If no such vertex
            if (adjacentVertex == -1) {
                stack.pop();
            } else {
                vertexList[adjacentVertex].wasVisited = true;
                // Do something
                stack.push(adjacentVertex);
            }
        }
        // Stack is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Depth-first searches are often used in simulations of games (and game-like situations in the real world). In a typical game you can choose one of several possible actions. Each choice leads to further choices, each of which leads to further choices, and so on into an ever-expanding tree-shaped graph of possibilities.


Breadth-First Search:

Breadth-First Search

  • The breadth-first search algorithm likes to stay as close as possible to the starting point.
  • This kind of search is generally implemented using a Queue.
  • Rules to follow: Make starting Vertex A the current vertex
    1. Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
    2. If you can’t carry out Rule 1 because there are no more unvisited vertices, remove a vertex from the queue (if possible) and make it the current vertex.
    3. If you can’t carry out Rule 2 because the queue is empty, you’re done.
  • Java code:

    public void searchBreadthFirst() {
        vertexList[0].wasVisited = true;
        displayVertex(0);
        queue.insert(0);
        int v2;
        while (!queue.isEmpty()) {
            int v1 = queue.remove();
            // Until it has no unvisited neighbors, get one
            while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
                vertexList[v2].wasVisited = true;
                // Do something
                queue.insert(v2);
            }
        }
        // Queue is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++) 
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Breadth-first search first finds all the vertices that are one edge away from the starting point, then all the vertices that are two edges away, and so on. This is useful if you’re trying to find the shortest path from the starting vertex to a given vertex.

Hopefully that should be enough for understanding the Breadth-First and Depth-First searches. For further reading I would recommend the Graphs chapter from an excellent data structures book by Robert Lafore.

Is it possible to have a default parameter for a mysql stored procedure?

No, this is not supported in MySQL stored routine syntax.

Feel free to submit a feature request at bugs.mysql.com.

Dump all documents of Elasticsearch

We can use elasticdump to take the backup and restore it, We can move data from one server/cluster to another server/cluster.

1. Commands to move one index data from one server/cluster to another using elasticdump.

# Copy an index from production to staging with analyzer and mapping:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=analyzer
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=data

2. Commands to move all indices data from one server/cluster to another using multielasticdump.

Backup

multielasticdump \
  --direction=dump \
  --match='^.*$' \
  --limit=10000 \
  --input=http://production.es.com:9200 \
  --output=/tmp 

Restore

multielasticdump \
  --direction=load \
  --match='^.*$' \
  --limit=10000 \
  --input=/tmp \
  --output=http://staging.es.com:9200 

Note:

  • If the --direction is dump, which is the default, --input MUST be a URL for the base location of an ElasticSearch server (i.e. http://localhost:9200) and --output MUST be a directory. Each index that does match will have a data, mapping, and analyzer file created.

  • For loading files that you have dumped from multi-elasticsearch, --direction should be set to load, --input MUST be a directory of a multielasticsearch dump and --output MUST be a Elasticsearch server URL.

  • The 2nd command will take a backup of settings, mappings, template and data itself as JSON files.

  • The --limit should not be more than 10000 otherwise, it will give an exception.

  • Get more details here.

how can the textbox width be reduced?

Is not nice to define textbox width without using CSS, be warned ;-)

<input type="text" name="d" value="4" size="4" />

Do while loop in SQL Server 2008

You can also use an exit variable if you want your code to be a bit more readable:

DECLARE @Flag int = 0
DECLARE @Done bit = 0

WHILE @Done = 0 BEGIN
    SET @Flag = @Flag + 1
    PRINT @Flag
    IF @Flag >= 5 SET @Done = 1
END

This would probably be more relevant when you have a more complicated loop and are trying to keep track of the logic. As stated loops are expensive so try and use other methods if you can.

Aligning textviews on the left and right edges in Android layout

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Hello world" />

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Gud bye" />

Fetch the row which has the Max value for a column

The answer here is Oracle only. Here's a bit more sophisticated answer in all SQL:

Who has the best overall homework result (maximum sum of homework points)?

SELECT FIRST, LAST, SUM(POINTS) AS TOTAL
FROM STUDENTS S, RESULTS R
WHERE S.SID = R.SID AND R.CAT = 'H'
GROUP BY S.SID, FIRST, LAST
HAVING SUM(POINTS) >= ALL (SELECT SUM (POINTS)
FROM RESULTS
WHERE CAT = 'H'
GROUP BY SID)

And a more difficult example, which need some explanation, for which I don't have time atm:

Give the book (ISBN and title) that is most popular in 2008, i.e., which is borrowed most often in 2008.

SELECT X.ISBN, X.title, X.loans
FROM (SELECT Book.ISBN, Book.title, count(Loan.dateTimeOut) AS loans
FROM CatalogEntry Book
LEFT JOIN BookOnShelf Copy
ON Book.bookId = Copy.bookId
LEFT JOIN (SELECT * FROM Loan WHERE YEAR(Loan.dateTimeOut) = 2008) Loan 
ON Copy.copyId = Loan.copyId
GROUP BY Book.title) X
HAVING loans >= ALL (SELECT count(Loan.dateTimeOut) AS loans
FROM CatalogEntry Book
LEFT JOIN BookOnShelf Copy
ON Book.bookId = Copy.bookId
LEFT JOIN (SELECT * FROM Loan WHERE YEAR(Loan.dateTimeOut) = 2008) Loan 
ON Copy.copyId = Loan.copyId
GROUP BY Book.title);

Hope this helps (anyone).. :)

Regards, Guus

Android - border for button

I know its about a year late, but you can also create a 9 path image There's a tool that comes with android SDK which helps in creating such image See this link: http://developer.android.com/tools/help/draw9patch.html

PS: the image can be infinitely scaled as well

Difference between using "chmod a+x" and "chmod 755"

chmod a+x modifies the argument's mode while chmod 755 sets it. Try both variants on something that has full or no permissions and you will notice the difference.

Accessing attributes from an AngularJS directive

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

Select n random rows from SQL Server table

It appears newid() can't be used in where clause, so this solution requires an inner query:

SELECT *
FROM (
    SELECT *, ABS(CHECKSUM(NEWID())) AS Rnd
    FROM MyTable
) vw
WHERE Rnd % 100 < 10        --10%

Convert string to JSON Object

only with js

   JSON.parse(jsonObj);

reference

ImportError: No module named 'selenium'

pip3 install selenium

Try this if you have python3.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Have a look at wxArt2d it is a complete framework for 2d editing and plotting. See the screenshots for more examples.

Some interesting features:

  • Reading and writing SVG and CVG
  • Several views of the same document
  • Changes are updated when idle
  • Optimized drawing of 2d objects

Sending SMS from PHP

Clickatell is a popular SMS gateway. It works in 200+ countries.

Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

The HTTP/S method is as simple as this:

http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home

You can also test the gateway (incoming and outgoing) for free from your browser

How to export a table dataframe in PySpark to csv?

If data frame fits in a driver memory and you want to save to local files system you can convert Spark DataFrame to local Pandas DataFrame using toPandas method and then simply use to_csv:

df.toPandas().to_csv('mycsv.csv')

Otherwise you can use spark-csv:

  • Spark 1.3

    df.save('mycsv.csv', 'com.databricks.spark.csv')
    
  • Spark 1.4+

    df.write.format('com.databricks.spark.csv').save('mycsv.csv')
    

In Spark 2.0+ you can use csv data source directly:

df.write.csv('mycsv.csv')

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

Converting a view to Bitmap without displaying it in Android?

here is my solution:

public static Bitmap getBitmapFromView(View view) {
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable =view.getBackground();
    if (bgDrawable!=null) 
        bgDrawable.draw(canvas);
    else 
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

Enjoy :)

HTML CSS How to stop a table cell from expanding

No javascript, just CSS. Works fine!

   .no-break-out {
      /* These are technically the same, but use both */
      overflow-wrap: break-word;
      word-wrap: break-word;

      -ms-word-break: break-all;
      /* This is the dangerous one in WebKit, as it breaks things wherever */
      word-break: break-all;
      /* Instead use this non-standard one: */
      word-break: break-word;

      /* Adds a hyphen where the word breaks, if supported (No Blink) */
      -ms-hyphens: auto;
      -moz-hyphens: auto;
      -webkit-hyphens: auto;
      hyphens: auto;

    }

How to detect Safari, Chrome, IE, Firefox and Opera browser?

There is also a less "hacky" method which works for all popular browsers. Google has included a browser-check in their Closure Library. In particular, have a look at goog.userAgent and goog.userAgent.product. In this way, you are also up to date if something changes in the way the browsers present themselves (given that you always run the latest version of the closure compiler.)

Http Basic Authentication in Java using HttpClient?

Have you tried this (using HttpClient version 4):

String encoding = Base64Encoder.encode(user + ":" + pwd);
HttpPost httpPost = new HttpPost("http://host:post/test/login");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);

System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();

Javascript: Load an Image from url and display

You were just missing an image tag to change the "src" attribute of:

    <html>
<body>
<form>
<input type="text" value="" id="imagename">
<input type="button" onclick="document.getElementById('img1').src =          'http://webpage.com/images/' + document.getElementById('imagename').value +'.png'"     value="GO">
<br/>
<img id="img1" src="defaultimage.png" />
</form>
</body>
</html>

Can't ignore UserInterfaceState.xcuserstate

Had a friend show me this amazing site https://www.gitignore.io/. Enter the IDE of your choice or other options and it will automatically generate a gitignore file consisting of useful ignores, one of which is the xcuserstate. You can preview the gitignore file before downloading.

How do I update a formula with Homebrew?

I think the correct way to do is

brew upgrade mongodb

It will upgrade the mongodb formula. If you want to upgrade all outdated formula, simply

brew upgrade

What to put in a python module docstring?

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

then:

>>> import x; help(x)

shows:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

Combine [NgStyle] With Condition (if..else)

One can also use this kind of condition:

<div [ngStyle]="myBooleanVar && {'color': 'red'}"></div>

It requires a bit less string concatenation...

Forward declaring an enum in C++

If you really don't want your enum to appear in your header file AND ensure that it is only used by private methods, then one solution can be to go with the pimpl principle.

It's a technique that ensure to hide the class internals in the headers by just declaring:

class A 
{
public:
    ...
private:
    void* pImpl;
};

Then in your implementation file (cpp), you declare a class that will be the representation of the internals.

class AImpl
{
public:
    AImpl(A* pThis): m_pThis(pThis) {}

    ... all private methods here ...
private:
    A* m_pThis;
};

You must dynamically create the implementation in the class constructor and delete it in the destructor and when implementing public method, you must use:

((AImpl*)pImpl)->PrivateMethod();

There are pros for using pimpl, one is that it decouple your class header from its implementation, no need to recompile other classes when changing one class implementation. Another is that is speeds up your compilation time because your headers are so simple.

But it's a pain to use, so you should really ask yourself if just declaring your enum as private in the header is that much a trouble.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.

Is JavaScript guaranteed to be single-threaded?

That's a good question. I'd love to say “yes”. I can't.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

However, in reality this isn't quite true, in sneaky nasty ways.

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
var i= document.getElementById('inp');_x000D_
i.onblur= function() {_x000D_
    l.value+= 'blur\n';_x000D_
};_x000D_
setTimeout(function() {_x000D_
    l.value+= 'log in\n';_x000D_
    l.focus();_x000D_
    l.value+= 'log out\n';_x000D_
}, 100);_x000D_
i.focus();
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<input id="inp">
_x000D_
_x000D_
_x000D_

Results in log in, blur, log out on all except IE. These events don't just fire because you called focus() directly, they could happen because you called alert(), or opened a pop-up window, or anything else that moves the focus.

This can also result in other events. For example add an i.onchange listener and type something in the input before the focus() call unfocuses it, and the log order is log in, change, blur, log out, except in Opera where it's log in, blur, log out, change and IE where it's (even less explicably) log in, change, log out, blur.

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

(I'm using the direct on... event handler properties here, but the same happens with addEventListener and attachEvent.)

There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
document.getElementById('act').onclick= function() {_x000D_
    l.value+= 'alert in\n';_x000D_
    alert('alert!');_x000D_
    l.value+= 'alert out\n';_x000D_
};_x000D_
window.onresize= function() {_x000D_
    l.value+= 'resize\n';_x000D_
};
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<button id="act">alert</button>
_x000D_
_x000D_
_x000D_

Hit alert and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out in the textarea.

You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.

You might think, well, it's only resize (and probably a few more like scroll) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.

Places where events that you can cause to be generated can be raised whilst script is still threaded:

  • when the modal popups (alert, confirm, prompt) are open, in all browsers but Opera;

  • during showModalDialog on browsers that support it;

  • the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.

  • a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).

  • probably more. It's been a while since I tested this and browsers have gained complexity since.

In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.

If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage will also hopefully soothe the pain of cross-document scripting in the future.

How to remove underline from a link in HTML?

<style="text-decoration: none">

The above code will be enough.Just paste this into the link you want to remove underline from.

Get multiple elements by Id

If you're not religious about keeping your HTML valid then I can see use cases where having the same ID on multiple elements may be useful.

One example is testing. Often we identify elements to test against by finding all elements with a particular class. However, if we find ourselves adding classes purely for testing purposes, then I would contend that that's wrong. Classes are for styling, not identification.

If IDs are for identification, why must it be that only one element can have a particular identifier? Particularly in today's frontend world, with reusable components, if we don't want to use classes for identification, then we need to use IDs. But, if we use multiples of a component, we'll have multiple elements with the same ID.

I'm saying that's OK. If that's anathema to you, that's fine, I understand your view. Let's agree to disagree and move on.

If you want a solution that actually finds all IDs of the same name though, then it's this:

function getElementsById(id) {
    const elementsWithId = []
    const allElements = document.getElementsByTagName('*')
    for(let key in allElements) {
        if(allElements.hasOwnProperty(key)) {
            const element = allElements[key]
            if(element.id === id) {
                elementsWithId.push(element)
            }        
        }
    }
    return elementsWithId
}

EDIT, ES6 FTW:

function getElementsById(id) {
    return [...document.getElementsByTagName('*')].filter(element => element.id === id)
}

How can I list all foreign keys referencing a given table in SQL Server?

This gets any foreign key that involves the chosen table. *Assumes a _FIRSTABLENAME_SECONDTABLENAME format.

 declare @tablename as varchar(MAX)
 SET @tablename = 'yourtablename'
 SELECT name
 FROM YOURDATABASE.sys.objects
 WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and (name LIKE '%_' + @tablename + 'empdb_%' or name LIKE '%_' + @tablename )

This is a more general form:

 SELECT name
 FROM YOURDATABASE_PROD.sys.objects
 WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and name LIKE '%' + @tablename + '%' and
 name NOT LIKE '[a-zA-Z0-9]' + @tablename + '%' and name NOT LIKE '%' + @tablename + '[a-zA-Z0-9]' 

mySQL Error 1040: Too Many Connection

The issue noted clearly in https://dev.mysql.com/doc/refman/8.0/en/too-many-connections.html:

If clients encounter Too many connections errors when attempting to connect to the MySQL server, all available connections are in use by other clients.

I got resolved the issue after a few minutes, it seems that connection was been released by other clients, also I tried with restarting vs and workbench at same time.

Swift: print() vs println() vs NSLog()

Moreover, Swift 2 has debugPrint() (and CustomDebugStringConvertible protocol)!

Don't forget about debugPrint() which works like print() but most suitable for debugging.

Examples:

  • Strings
    • print("Hello World!") becomes Hello World
    • debugPrint("Hello World!") becomes "Hello World" (Quotes!)
  • Ranges
    • print(1..<6) becomes 1..<6
    • debugPrint(1..<6) becomes Range(1..<6)

Any class can customize their debug string representation via CustomDebugStringConvertible protocol.

How to find a value in an excel column by vba code Cells.Find

Just use

Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

Else
    'do it another thing
End If

How to open the Google Play Store directly from my Android application?

Go on Android Developer official link as tutorial step by step see and got the code for your application package from play store if exists or play store apps not exists then open application from web browser.

Android Developer official link

https://developer.android.com/distribute/tools/promote/linking.html

Linking to a Application Page

From a web site: https://play.google.com/store/apps/details?id=<package_name>

From an Android app: market://details?id=<package_name>

Linking to a Product List

From a web site: https://play.google.com/store/search?q=pub:<publisher_name>

From an Android app: market://search?q=pub:<publisher_name>

Linking to a Search Result

From a web site: https://play.google.com/store/search?q=<search_query>&c=apps

From an Android app: market://search?q=<seach_query>&c=apps

Init method in Spring Controller (annotation version)

Alternatively you can have your class implement the InitializingBean interface to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed.

Convert wchar_t to char

Technically, 'char' could have the same range as either 'signed char' or 'unsigned char'. For the unsigned characters, your range is correct; theoretically, for signed characters, your condition is wrong. In practice, very few compilers will object - and the result will be the same.

Nitpick: the last && in the assert is a syntax error.

Whether the assertion is appropriate depends on whether you can afford to crash when the code gets to the customer, and what you could or should do if the assertion condition is violated but the assertion is not compiled into the code. For debug work, it seems fine, but you might want an active test after it for run-time checking too.

How to print the values of slices

I wrote a package named Pretty Slice. You can use it to visualize slices, and their backing arrays, etc.

package main

import pretty "github.com/inancgumus/prettyslice"

func main() {
    nums := []int{1, 9, 5, 6, 4, 8}
    odds := nums[:3]
    evens := nums[3:]

    nums[1], nums[3] = 9, 6
    pretty.Show("nums", nums)
    pretty.Show("odds : nums[:3]", odds)
    pretty.Show("evens: nums[3:]", evens)
}

This code is going produce and output like this one:

enter image description here


For more details, please read: https://github.com/inancgumus/prettyslice

Docker: How to delete all local Docker images

For Unix

To delete all containers including its volumes use,

docker rm -vf $(docker ps -a -q)

To delete all the images,

docker rmi -f $(docker images -a -q)

Remember, you should remove all the containers before removing all the images from which those containers were created.

For Windows

In case you are working on Windows (Powershell),

$images = docker images -a -q
foreach ($image in $images) { docker image rm $image -f }

Based on the comment from CodeSix, one liner for Windows Powershell,

docker images -a -q | % { docker image rm $_ -f }

For Windows using command line,

for /F %i in ('docker images -a -q') do docker rmi -f %i

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

Some operations in Excel are limited by available Memory. If you repeat the same process over and over it could produce a memory overflow and excel will not be able to repeat it anymore. This happened to me while trying to create several sheets in the same workbook.

Remove ALL styling/formatting from hyperlinks

You can simply define a style for links, which would override a:hover, a:visited etc.:

a {
  color: blue;
  text-decoration: none; /* no underline */
}

You can also use the inherit value if you want to use attributes from parent styles instead:

body {
  color: blue;
}
a {
  color: inherit; /* blue colors for links too */
  text-decoration: inherit; /* no underline */
}

how to convert object to string in java

The question how do I convert an object to a String, despite the several answers you see here, and despite the existence of the Object.toString method, is unanswerable, or has infinitely many answers. Because what is being asked for is some kind of text representation or description of the object, and there are infinitely many possible representations. Each representation encodes a particular object instance using a special purpose language (probably a very limited language) or format that is expressive enough to encode all possible object instances.

Before code can be written to convert an object to a String, you must decide on the language/format to be used.

How to convert AAR to JAR

Android Studio (version: 1.3.2) allows you to seamlessly access the .jar inside a .aar.

Bonus: it automatically decompiles the classes!

Simply follow these steps:

  1. File > New > New Module > Import .JAR/.AAR Package to import you .aar as a module

  2. Add the newly created module as a dependency to your main project (not sure if needed)

  3. Right click on "classes.jar" as shown in the capture below, and click "Show in explorer". Here is your .jar.

access .jar from .aar

How can I use grep to show just filenames on Linux?

From the grep(1) man page:

  -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)

JQuery datepicker language

You need to do something like this,

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '<Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

for sv data follow the following link

http://code.google.com/p/logicss/source/browse/trunk/media/jquery/jquery.ui.i18n.all.min.js?r=41

Stopping Excel Macro executution when pressing Esc won't work

I've found that sometimes whem I open a second Excel window and run a macro on that second window, the execution of the first one stops. I don't know why it doesn't work all the time, but you may try.

Angular 2 optional route parameter

rerezz's answer is pretty nice but it has one serious flaw. It causes User component to re-run the ngOnInit method.

It might be problematic when you do some heavy stuff there and don't want it to be re-run when you switch from the non-parametric route to the parametric one. Though those two routes are meant to imitate an optional url parameter, not become 2 separate routes.

Here's what I suggest to solve the problem:

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      { path: ':id', component: UserWithParam, name: 'Usernew' }
    ]
  }
];

Then you can move the logic responsible for handling the param to the UserWithParam component and leave the base logic in the User component. Whatever you do in User::ngOnInit won't be run again when you navigate from /user to /user/123.

Don't forget to put the <router-outlet></router-outlet> in the User's template.

Retrofit and GET using parameters

I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:

public interface LocationService {    
    @GET("/example/")
    void getLocation(@Query(value="latlng", encoded=true) String latlng);
}

Note the encoded=true is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:

String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);

How to convert a String to a Date using SimpleDateFormat?

you can solve the problem much simple like First convert the the given string to the date object eg:

java.util.Date date1 = new Date("11/19/2015"); 
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd yyyy HH:mma");
String format = formatter.format(date);
System.out.println(format);

Sorting an Array of int using BubbleSort

public class Bubblesort{

  public static int arr[];

  public static void main(String args[]){

    System.out.println("Enter number of element you have in array for performing bubblesort");

    int numbofele = Integer.parseInt(args[0]);

    System.out.println("numer of element entered is"+ "\n" + numbofele);

    arr= new int[numbofele];

    System.out.println("Enter Elements of array");

    System.out.println("The given array is");


    for(int i=0,j=1;i<numbofele;i++,j++){

      arr[i]=Integer.parseInt(args[j]);

      System.out.println(arr[i]);

    }

    boolean swapped = false;

    System.out.println("The sorted array is");

    for(int k=0;k<numbofele-1;k++){


      for(int l=0;l+1<numbofele-k;l++){

        if(arr[l]>arr[l+1]){

          int temp = arr[l];
          arr[l]= arr[l+1];
          arr[l+1]=temp;
          swapped=true;

        } 

      }

         if(!swapped){

            for(int m=0;m<numbofele;m++){

       System.out.println(arr[m]);

    }

      return;

      }


    }

    for(int m=0;m<numbofele;m++){

       System.out.println(arr[m]);

    }


  }


}

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

Jquery Smooth Scroll To DIV - Using ID value from Link

Here is my solution:

<!-- jquery smooth scroll to id's -->   
<script>
$(function() {
  $('a[href*=\\#]:not([href=\\#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

With just this snippet you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.

I already explained how it works in another thread here: https://stackoverflow.com/a/28631803/4566435 (or here's a direct link to my blog post)

For clarifications, let me know. Hope it helps!

How to change line-ending settings

For a repository setting solution, that can be redistributed to all developers, check out the text attribute in the .gitattributes file. This way, developers dont have to manually set their own line endings on the repository, and because different repositories can have different line ending styles, global core.autocrlf is not the best, at least in my opinion.

For example unsetting this attribute on a given path [. - text] will force git not to touch line endings when checking in and checking out. In my opinion, this is the best behavior, as most modern text editors can handle both type of line endings. Also, if you as a developer still want to do line ending conversion when checking in, you can still set the path to match certain files or set the eol attribute (in .gitattributes) on your repository.

Also check out this related post, which describes .gitattributes file and text attribute in more detail: What's the best CRLF (carriage return, line feed) handling strategy with Git?

Tomcat 8 is not able to handle get request with '|' in query parameters?

The parameter tomcat.util.http.parser.HttpParser.requestTargetAllow is deprecated since Tomcat 8.5: tomcat official doc.

You can use relaxedQueryChars / relaxedPathChars in the connectors definition to allow these chars: tomcat official doc.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

For me, the solution was to ensure all projects were building for the same CPU - in my case x86

Building executable jar with maven?

The answer of Pascal Thivent helped me out, too. But if you manage your plugins within the <pluginManagement>element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>


    <build>
        <pluginManagement>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>main.App</mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                    <executions>
                        <execution>
                            <id>make-assembly</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

            </plugins>

        </pluginManagement>

        <plugins> <!-- did NOT work without this  -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
            </plugin>
        </plugins>

    </build>


    <dependencies>
       <!--  dependencies commented out to shorten example -->
    </dependencies>

</project>

What is the purpose of the "final" keyword in C++11 for functions?

Supplement to Mario Knezovic 's answer:

class IA
{
public:
  virtual int getNum() const = 0;
};

class BaseA : public IA
{
public:
 inline virtual int getNum() const final {return ...};
};

class ImplA : public BaseA {...};

IA* pa = ...;
...
ImplA* impla = static_cast<ImplA*>(pa);

//the following line should cause compiler to use the inlined function BaseA::getNum(), 
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it

int n = impla->getNum();

The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.

SQL query to find record with ID not in another table

SELECT COUNT(ID) FROM tblA a
WHERE a.ID NOT IN (SELECT b.ID FROM tblB b)    --For count


SELECT ID FROM tblA a
WHERE a.ID NOT IN (SELECT b.ID FROM tblB b)    --For results

android adb turn on wifi via adb

In my ROM, it's stored in the "global" database, rather than "secure". So D__'s answer is correct, but the sql line needs to connect to a different database:

sqlite3 /data/data/com.android.providers.settings/databases/settings.db
update global set value=1 where name='wifi_on';

javascript Unable to get property 'value' of undefined or null reference

You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:

document.getElementById("frm_new_user_request")

So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

INSERT ... ON DUPLICATE KEY (do nothing)

Use ON DUPLICATE KEY UPDATE ...,
Negative : because the UPDATE uses resources for the second action.

Use INSERT IGNORE ...,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.

How to add a touch event to a UIView?

Create a gesture recognizer (subclass), that will implement touch events, like touchesBegan. You can add it to the view after that.

This way you'll use composition instead subclassing (which was the request).

Oracle DB: How can I write query ignoring case?

In version 12.2 and above, the simplest way to make the query case insensitive is this:

SELECT * FROM TABLE WHERE TABLE.NAME COLLATE BINARY_CI Like 'IgNoReCaSe'

How to generate a GUID in Oracle?

It is not clear what you mean by auto-generate a guid into an insert statement but at a guess, I think you are trying to do something like the following:

INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Adams');
INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Baker');

In that case I believe the ID column should be declared as RAW(16);

I am doing this off the top of my head. I don't have an Oracle instance handy to test against, but I think that is what you want.

how to use math.pi in java

Replace

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;

What is the difference between an int and a long in C++?

It depends on your compiler. You are guaranteed that a long will be at least as large as an int, but you are not guaranteed that it will be any longer.

unknown type name 'uint8_t', MinGW

Try including stdint.h or inttypes.h.

Angular2, what is the correct way to disable an anchor element?

I have used

tabindex="{{isEditedParaOrder?-1:0}}" 
[style.pointer-events]="isEditedParaOrder ?'none':'auto'" 

in my anchor tag so that they can not move to anchor tag by using tab to use "enter" key and also pointer itself we are setting to 'none' based on property 'isEditedParaO rder' whi

How to show an alert box in PHP?

I don't know about php but i belive the problem is from this :

echo '<script language="javascript>';
echo 'alery("message successfully sent")';
echo '</script>';

Try to change this with :

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

What is the difference between window, screen, and document in Javascript?

The window is the actual global object.

The screen is the screen, it contains properties about the user's display.

The document is where the DOM is.

Why should you use strncpy instead of strcpy?

While I know the intent behind strncpy, it is not really a good function. Avoid both. Raymond Chen explains.

Personally, my conclusion is simply to avoid strncpy and all its friends if you are dealing with null-terminated strings. Despite the "str" in the name, these functions do not produce null-terminated strings. They convert a null-terminated string into a raw character buffer. Using them where a null-terminated string is expected as the second buffer is plain wrong. Not only do you fail to get proper null termination if the source is too long, but if the source is short you get unnecessary null padding.

See also Why is strncpy insecure?

How to run the sftp command with a password from Bash script?

You can use sshpass for it. Below are the steps

  1. Install sshpass For Ubuntu - sudo apt-get install sshpass
  2. Add the Remote IP to your known-host file if it is first time For Ubuntu -> ssh user@IP -> enter 'yes'
  3. give a combined command of scp and sshpass for it. Below is a sample code for war coping to remote tomcat sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user@#RemoteIP:/var/lib/tomcat7/webapps

PHP - Check if the page run on Mobile or Desktop browser

You can do it manually if you want.

Reference: http://php.net/manual/en/function.get-browser.php

preg_match('/windows|win32/i', $_SERVER['HTTP_USER_AGENT'])

preg_match('/iPhone|iPod|iPad/', $_SERVER['HTTP_USER_AGENT'])

You can even make it a script

$device = 'Blackberry'

preg_match("/$device/", $_SERVER['HTTP_USER_AGENT'])

Here is somewhat of a small list

                        '/windows nt 6.2/i'     =>  'Windows 8',
                        '/windows nt 6.1/i'     =>  'Windows 7',
                        '/windows nt 6.0/i'     =>  'Windows Vista',
                        '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                        '/windows nt 5.1/i'     =>  'Windows XP',
                        '/windows xp/i'         =>  'Windows XP',
                        '/windows nt 5.0/i'     =>  'Windows 2000',
                        '/windows me/i'         =>  'Windows ME',
                        '/win98/i'              =>  'Windows 98',
                        '/win95/i'              =>  'Windows 95',
                        '/win16/i'              =>  'Windows 3.11',
                        '/macintosh|mac os x/i' =>  'Mac OS X',
                        '/mac_powerpc/i'        =>  'Mac OS 9',
                        '/linux/i'              =>  'Linux',
                        '/ubuntu/i'             =>  'Ubuntu',
                        '/iphone/i'             =>  'iPhone',
                        '/ipod/i'               =>  'iPod',
                        '/ipad/i'               =>  'iPad',
                        '/android/i'            =>  'Android',
                        '/blackberry/i'         =>  'BlackBerry',
                        '/webos/i'              =>  'Mobile'

Browsers

                        '/msie/i'       =>  'Internet Explorer',
                        '/firefox/i'    =>  'Firefox',
                        '/safari/i'     =>  'Safari',
                        '/chrome/i'     =>  'Chrome',
                        '/opera/i'      =>  'Opera',
                        '/netscape/i'   =>  'Netscape',
                        '/maxthon/i'    =>  'Maxthon',
                        '/konqueror/i'  =>  'Konqueror',
                        '/mobile/i'     =>  'Handheld Browser'

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

The error means that it didn't receive a response from the port it expected to find the server on. The causes range from contacting the wrong machine (For one of a number of reasons) to the server not being on the expected port.

Check which port your server is bound to in /etc/mysql/my.cnf. Does that correspond to what is in your connect statement. If they match then try connecting with mysql from the server itself and from the command line of the machine where you are running the client. If it works form one place and not another then you may have a firewall / router configuration issue.

Disable sorting for a particular column in jQuery DataTables

To update Bhavish's answer (which I think is for an older version of DataTables and didn't work for me). I think they changed the attribute name. Try this:

<thead>
    <tr>
        <td data-sortable="false">Requirements</td>
        <td data-sortable="false">Automated</td>
        <td>Created On</td>
    </tr>
</thead>
<tbody>
    <tr>
        <td>

Remove all the elements that occur in one list from another

Expanding on Donut's answer and the other answers here, you can get even better results by using a generator comprehension instead of a list comprehension, and by using a set data structure (since the in operator is O(n) on a list but O(1) on a set).

So here's a function that would work for you:

def filter_list(full_list, excludes):
    s = set(excludes)
    return (x for x in full_list if x not in s)

The result will be an iterable that will lazily fetch the filtered list. If you need a real list object (e.g. if you need to do a len() on the result), then you can easily build a list like so:

filtered_list = list(filter_list(full_list, excludes))

How to insert data into SQL Server

string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();

Passing parameters to addTarget:action:forControlEvents

There is another one way, in which you can get indexPath of the cell where your button was pressed:

using usual action selector like:

 UIButton *btn = ....;
    [btn addTarget:self action:@selector(yourFunction:) forControlEvents:UIControlEventTouchUpInside];

and then in in yourFunction:

   - (void) yourFunction:(id)sender {

    UIButton *button = sender;
    CGPoint center = button.center;
    CGPoint rootViewPoint = [button.superview convertPoint:center toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
    //the rest of your code goes here
    ..
}

since you get an indexPath it becames much simplier.

Adding a view controller as a subview in another view controller

This code will work for Swift 4.2.

let controller:SecondViewController = 
self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as! 
SecondViewController
controller.view.frame = self.view.bounds;
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

Why do I get the "Unhandled exception type IOException"?

I got the Error even though i was catching the exception.

    try {
        bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
    } catch (IOException e) {
        Log.e("blabla", "Error", e);
        finish();
    }

Issue was that the IOException wasn't imported

import java.io.IOException;

Finding an element in an array in Java

There is a contains method for lists, so you should be able to do:

Arrays.asList(yourArray).contains(yourObject);

Warning: this might not do what you (or I) expect, see Tom's comment below.