Programs & Examples On #Helper

Additional functionality not defined in a class that the helper operates on.

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

You need to double check the PATH environment setting. C:\Program Files\Java\jdk-13 you currently have there is not correct. Please make sure you have the bin subdirectory for the latest JDK version at the top of the PATH list.

java.exe executable is in C:\Program Files\Java\jdk-13\bin directory, so that is what you need to have in PATH.

Use this tool to quickly verify or edit the environment variables on Windows. It allows to reorder PATH entries. It will also highlight invalid paths in red.

If you want your code to run on lower JDK versions as well, change the target bytecode version in the IDE. See this answer for the relevant screenshots.

See also this answer for the Java class file versions. What happens is that you build the code with Java 13 and 13 language level bytecode (target) and try to run it with Java 8 which is the first (default) Java version according to the PATH variable configuration.

The solution is to have Java 13 bin directory in PATH above or instead of Java 8. On Windows you may have C:\Program Files (x86)\Common Files\Oracle\Java\javapath added to PATH automatically which points to Java 8 now:

javapath

If it's the case, remove the highlighted part from PATH and then logout/login or reboot for the changes to have effect. You need to Restart as administrator first to be able to edit the System variables (see the button on the top right of the system variables column).

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

How to update core-js to core-js@3 dependency?

For npm

 npm install --save core-js@^3

for yarn

yarn add core-js@^3

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I suggest removing the below code from getMails

 .catch(error => { throw error})

In your main function you should put await and related code in Try block and also add one catch block where you failure code.


you function gmaiLHelper.getEmails should return a promise which has reject and resolve in it.

Now while calling and using await put that in try catch block(remove the .catch) as below.

router.get("/emailfetch", authCheck, async (req, res) => {
  //listing messages in users mailbox 
try{
  let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
}
catch (error) { 
 // your catch block code goes here
})

Center content vertically on Vuetify

Here's another approach using Vuetify grid system available in Vuetify 2.x: https://vuetifyjs.com/en/components/grids

<v-container>
    <v-row align="center">
        Hello I am center to vertically using "grid".
    </v-row>
</v-container>

git clone: Authentication failed for <URL>

Go to > Control Panel\User Accounts\Credential Manager > Manage Windows Credentials and remove all generic credentials involving Git. This way you're resetting all the credentials; After this, when you clone, you'll be newly and securely asked your username and password instead of Authentication error. Similar logic can be applied for Mac users.

Hope it helps.

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

You don't need to downgrade your gulp from gulp 4. Use gulp.series() to combine multiple tasks. At first install gulp globally with

npm install --global gulp-cli

and then install locally on your working directory with

npm install --save-dev gulp

see details here

Example:

package.json

{
  "name": "gulp-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.26.3",
    "gulp": "^4.0.0",
    "gulp-sass": "^4.0.2"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "jquery": "^3.3.1",
    "popper.js": "^1.14.7"
  }
}

gulpfile.js

var gulp = require("gulp");
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

// Specific Task
function js() {
    return gulp
    .src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/umd/popper.min.js'])
    .pipe(gulp.dest('src/js'))
    .pipe(browserSync.stream());
}
gulp.task(js);

// Specific Task
function gulpSass() {
    return gulp
    .src(['src/scss/*.scss'])
    .pipe(sass())
    .pipe(gulp.dest('src/css'))
    .pipe(browserSync.stream());
}
gulp.task(gulpSass);

// Run multiple tasks
gulp.task('start', gulp.series(js, gulpSass));

Run gulp start to fire multiple tasks & run gulp js or gulp gulpSass for specific task.

Not able to change TextField Border Color

That is not changing due to the default theme set to the screen.

So just change them for the widget you are drawing by wrapping your TextField with new ThemeData()

child: new Theme(
          data: new ThemeData(
            primaryColor: Colors.redAccent,
            primaryColorDark: Colors.red,
          ),
          child: new TextField(
            decoration: new InputDecoration(
                border: new OutlineInputBorder(
                    borderSide: new BorderSide(color: Colors.teal)),
                hintText: 'Tell us about yourself',
                helperText: 'Keep it short, this is just a demo.',
                labelText: 'Life story',
                prefixIcon: const Icon(
                  Icons.person,
                  color: Colors.green,
                ),
                prefixText: ' ',
                suffixText: 'USD',
                suffixStyle: const TextStyle(color: Colors.green)),
          ),
        ));

enter image description here

await is only valid in async function

Yes, await / async was a great concept, but the implementation is completely broken.

For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.

Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.

This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.

If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.

So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...

  • await can only be used to CALL async functions.
  • await can appear in any kind of function, synchronous or asynchronous.
  • Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

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?

I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI

npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli

I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again if npm version is < 5 then use npm cache clean --force

npm install -g @angular/cli@latest

and created a new project file and create a new angular project.

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

you need just run this below commands:

$ rm -rf node_modules
$ rm -rf yarn.lock
$ yarn install

and finally

$ ./node_modules/.bin/electron-rebuild

don't forget to yarn add electron-rebuild if it doesn't exist in your dependencies.

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

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had approximately the same problem with Laravel 5.5 on ubuntu, finally i've found a solution here to switch between the versions of php used by apache :

  1. sudo a2dismod php5
  2. sudo a2enmod php7.1
  3. sudo service apache2 restart

and it works

Passing headers with axios POST request

Interceptors

I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

Error: the entity type requires a primary key

I came here with similar error:

System.InvalidOperationException: 'The entity type 'MyType' requires a primary key to be defined.'

After reading answer by hvd, realized I had simply forgotten to make my key property 'public'. This..

namespace MyApp.Models.Schedule
{
    public class MyType
    {
        [Key]
        int Id { get; set; }

        // ...

Should be this..

namespace MyApp.Models.Schedule
{
    public class MyType
    {
        [Key]
        public int Id { get; set; }  // must be public!

        // ...

Hibernate Error executing DDL via JDBC Statement

Dialects are removed in recent SQL so use

  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>

Class JavaLaunchHelper is implemented in two places

You can find all the details here:

  • IDEA-170117 "objc: Class JavaLaunchHelper is implemented in both ..." warning in Run consoles

It's the old bug in Java on Mac that got triggered by the Java Agent being used by the IDE when starting the app. This message is harmless and is safe to ignore. Oracle developer's comment:

The message is benign, there is no negative impact from this problem since both copies of that class are identical (compiled from the exact same source). It is purely a cosmetic issue.

The problem is fixed in Java 9 and in Java 8 update 152.

If it annoys you or affects your apps in any way (it shouldn't), the workaround for IntelliJ IDEA is to disable idea_rt launcher agent by adding idea.no.launcher=true into idea.properties (Help | Edit Custom Properties...). The workaround will take effect on the next restart of the IDE.

I don't recommend disabling IntelliJ IDEA launcher agent, though. It's used for such features as graceful shutdown (Exit button), thread dumps, workarounds a problem with too long command line exceeding OS limits, etc. Losing these features just for the sake of hiding the harmless message is probably not worth it, but it's up to you.

Cannot find module '@angular/compiler'

This command is working fine for me ubuntu 16.04 LTS:

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

All com.android.support libraries must use the exact same version specification

It just simple just force all v7 and v4 libraries to use the library version you have set just before your dependencies.

configurations.all {
                    // To resolve the conflict for com.android.databinding
                    // dependency on support-v4:21.0.3
                    resolutionStrategy.force 'com.android.support:support-v4:28.0.0'
                    resolutionStrategy.force 'com.android.support:support-v7:28.0.0'
                }

pandas: merge (join) two data frames on multiple columns

Another way of doing this: new_df = A_df.merge(B_df, left_on=['A_c1','c2'], right_on = ['B_c1','c2'], how='left')

How to upgrade Angular CLI project?

USEFUL:

Use the official Angular Update Guide select your current version and the version you wish to upgrade to for the relevant upgrade guide. https://update.angular.io/

See GitHub repository Angular CLI diff for comparing Angular CLI changes. https://github.com/cexbrayat/angular-cli-diff/

UPDATED 26/12/2018:

Use the official Angular Update Guide mentioned in the useful section above. It provides the most up to date information with links to other resources that may be useful during the upgrade.

UPDATED 08/05/2018:

Angular CLI 1.7 introduced ng update.

ng update

A new Angular CLI command to help simplify keeping your projects up to date with the latest versions. Packages can define logic which will be applied to your projects to ensure usage of latest features as well as making changes to reduce or eliminate the impact related to breaking changes.

Configuration information for ng update can be found here

1.7 to 6 update

CLI 1.7 does not support an automatic v6 update. Manually install @angular/cli via your package manager, then run the update migration schematic to finish the process.

npm install @angular/cli@^6.0.0
ng update @angular/cli --migrate-only --from=1

UPDATED 30/04/2017:

1.0 Update

You should now follow the Angular CLI migration guide


UPDATED 04/03/2017:

RC Update

You should follow the Angular CLI RC migration guide


UPDATED 20/02/2017:

Please be aware 1.0.0-beta.32 has breaking changes and has removed ng init and ng update

The pull request here states the following:

BREAKING CHANGE: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Update functionality will return to the CLI, until then manual updates of applications will need done.

The angular-cli CHANGELOG.md states the following:

BREAKING CHANGES - @angular/cli: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Once RC is released, we won't need to use those to update anymore as the step will be as simple as installing the latest version of the CLI.


UPDATED 17/02/2017:

Angular-cli has now been added to the NPM @angular package. You should now replace the above command with the following -

Global package:

npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # On Windows use rmdir /s /q node_modules dist
npm install --save-dev @angular/cli@latest
npm install
ng init

ORIGINAL ANSWER

You should follow the steps from the README.md on GitHub for updating angular via the angular-cli.

Here they are:

Updating angular-cli

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

Global package:

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

Local project package:

rm -rf node_modules dist tmp # On Windows use rmdir /s /q node_modules dist tmp
npm install --save-dev angular-cli@latest
npm install
ng init

Running ng init will check for changes in all the auto-generated files created by ng new and allow you to update yours. You are offered four choices for each changed file: y (overwrite), n (don't overwrite), d (show diff between your file and the updated file) and h (help).

Carefully read the diffs for each code file, and either accept the changes or incorporate them manually after ng init finishes.

Mongodb: failed to connect to server on first connect

While connected to a wifi network, mongodb://localhost/db_name worked as expected.

When I wasn't connected to any wifi network, this couldn't work. Instead I used, mongodb://127.0.0.1/db_name and it worked.

Probably a problem to do with ip configurations.

can not find module "@angular/material"

I followed each of the suggestions here (I'm using Angular 7), but nothing worked. My app refused to acknowledge that @angular/material existed, so it showed an error on this line:

import { MatCheckboxModule } from '@angular/material';

Even though I was using the --save parameter to add Angular Material to my project:

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

...it refused to add anything to my "package.json" file.

I even tried deleting the package-lock.json file, as some articles suggest that this causes problems, but this had no effect.

To fix this issue, I had to manually add these two lines to my "package.json" file.

{
    "devDependencies": {
        ...
        "@angular/material": "~7.2.2",
        "@angular/cdk": "~7.2.2",
        ...

What I can't tell is whether this is an issue related to using Angular 7, or if it's been around for years....

Find object by its property in array of objects with AngularJS way

For complete M B answer, if you want to access to an specific attribute of this object already filtered from the array in your HTML, you will have to do it in this way:

{{ (myArray | filter : {'id':73})[0].name }}

So, in this case, it will print john in the HTML.

Regards!

Reload child component when variables on parent component changes. Angular2

You can use @input with ngOnChanges, to see the changes when it happened.

reference: https://angular.io/api/core/OnChanges

(or)

If you want to pass data between multiple component or routes then go with Rxjs way.

Service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MessageService {
  private subject = new Subject<any>();

  sendMessage(message: string) {
    this.subject.next({ text: message });
  }

  clearMessages() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }
}

Component.ts

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

import { MessageService } from './_services/index';

@Component({
  selector: 'app',
  templateUrl: 'app.component.html'
})

export class AppComponent implements OnDestroy {
  messages: any[] = [];
  subscription: Subscription;

  constructor(private messageService: MessageService) {
    // subscribe to home component messages
    this.subscription = this.messageService.getMessage().subscribe(message => {
      if (message) {
        this.messages.push(message);
      } else {
        // clear messages when empty message received
        this.messages = [];
      }
    });
  }

  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }
}

Reference: http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

I faced the same issue. I was using Java 9 and the following dependency in pom file:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

The issue was resolved after adding the dependency below in pom:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

Angular 2 : No NgModule metadata found

This error says necessary data for your module can't be found. In my case i missed an @ symbol in start of NgModule.

Correct NgModule definition:

 @NgModule ({ 
    ... 
 })
 export class AppModule {

 }

My case (Wrong case) :

NgModule ({ // => this line must starts with @
   ... 
})
export class AppModule {

}

Error: Unexpected value 'undefined' imported by the module

Make sure you should not import a module/component like this:

import { YOUR_COMPONENT } from './';

But it should be

import { YOUR_COMPONENT } from './YOUR_COMPONENT.ts';

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

ImportError: No module named google.protobuf

When pip tells you that you already have protobuf, but PyCharm (or other) tells you that you don't have it, it means that pip and PyCharm are using a different Python interpreter. This is a very common issue, especially on a Mac, with no standard Python package management.

The best way to completely eliminate such issues is using a virtualenv per Python project, which is essentially a directory of Python packages and environment variable settings to isolate the Python environment of the project from everything else.

Create a virtualenv for your project like this:

cd project
virtualenv --distribute virtualenv -p /path/to/python/executable

This creates a directory called virtualenv inside your project. (Make sure to configure your VCS (for example Git) to ignore this directory.)

To install packages in this virtualenv, you need to activate the environment variable settings:

. virtualenv/bin/activate

Verify that pip will use the right Python executable inside the virtualenv, by running pip -V. It should tell you the Python library path used, which should be inside the virtualenv.

Now you can use pip to install protobuf as you did.

And finally, you need to make PyCharm use this virtualenv instead of the system libraries. Somewhere in the project settings you can configure an interpreter for the project, select the Python executable inside the virtualenv.

Get only specific attributes with from Laravel Collection

I have now come up with an own solution to this:

1. Created a general function to extract specific attributes from arrays

The function below extract only specific attributes from an associative array, or an array of associative arrays (the last is what you get when doing $collection->toArray() in Laravel).

It can be used like this:

$data = array_extract( $collection->toArray(), ['id','url'] );

I am using the following functions:

function array_is_assoc( $array )
{
        return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}



function array_extract( $array, $attributes )
{
    $data = [];

    if ( array_is_assoc( $array ) )
    {
        foreach ( $attributes as $attribute )
        {
            $data[ $attribute ] = $array[ $attribute ];
        }
    }
    else
    {
        foreach ( $array as $key => $values )
        {
            $data[ $key ] = [];

            foreach ( $attributes as $attribute )
            {
                $data[ $key ][ $attribute ] = $values[ $attribute ];
            }
        }   
    }

    return $data;   
}

This solution does not focus on performance implications on looping through the collections in large datasets.

2. Implement the above via a custom collection i Laravel

Since I would like to be able to simply do $collection->extract('id','url'); on any collection object, I have implemented a custom collection class.

First I created a general Model, which extends the Eloquent model, but uses a different collection class. All you models need to extend this custom model, and not the Eloquent Model then.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
    public function newCollection(array $models = [])
    {
        return new Collection( $models );
    }    
}
?>

Secondly I created the following custom collection class:

<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
    public function extract()
    {
        $attributes = func_get_args();
        return array_extract( $this->toArray(), $attributes );
    }
}   
?>

Lastly, all models should then extend your custom model instead, like such:

<?php
namespace App\Models;
class Article extends Model
{
...

Now the functions from no. 1 above are neatly used by the collection to make the $collection->extract() method available.

How to create helper file full of functions in react native?

i prefer to create folder his name is Utils and inside create page index that contain what that think you helper by

const findByAttr = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

const FUNCTION_NAME = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

export {findByAttr, FUNCTION_NAME}

When you need to use this it should be imported as use "{}" because you did not use the default keyword look

 import {FUNCTION_NAME,findByAttr} from'.whare file is store/utils/index'

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

getting error while updating Composer

After installing packages from given answers, i still get some errors then i install following package and it works fine:

  • php-xml

for specific version:

  • php7.0-xml

command for php 7.0

sudo apt-get install php7.0-xml

in some cases you also needs a package php7.0-common . install it same as above command.

How to return history of validation loss in Keras

Just an example started from

history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=0)

You can use

print(history.history.keys())

to list all data in history.

Then, you can print the history of validation loss like this:

print(history.history['val_loss'])

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

try in cmd: mvn clean install -Dskiptests=true

that'll skip all unit test. Might be It'll work fine for you.

Unsupported major.minor version 52.0 in my app

I installed Android Studio alongside to Xamarin Visual Studio (was already installed). After the installation (excluded SDK, because they were already installed) I started Android Studio and it downloaded, installed and added missing SDKs (after giving the path to the SDK location). As a result I got the error message on build

java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0

As a solution I installed jdk-8u101-windows-i586.exe without JRE (because it was already installed). Before I tried the x64 version, but it disappeared ... Then you have to change the Java Development Kit location.

Change JDK location

This is done in Visual Studio by clicking Tools > Options > Xamarin > Android Settings. Here you can navigate to the correct location. In my case it was C:\Program Files (x86)\Java\jdk1.8.0_101.

Finally, clean your project and make a new build :-)

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

This is probably due to its lack of connections to the Hive Meta Store,my hive Meta Store is stored in Mysql,so I need to visit Mysql,So I add a dependency in my build.sbt

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.38"

and the problem is solved!

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

In my case problem was that my version of gradle was incompatible with jdk14, but despite in project structure dialog was selected 8jdk, it was necessarily to set jdk home for gradle separately in gradle.propperties

org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home

Select Tag Helper in ASP.NET Core MVC

In Get:

public IActionResult Create()
{
    ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
    return View();
}

In Post:

var selectedIds= Request.Form["Tags"];

In View :

<label>Tags</label>
<select  asp-for="Tags"  id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>

How to add a recyclerView inside another recyclerView

I would like to suggest to use a single RecyclerView and populate your list items dynamically. I've added a github project to describe how this can be done. You might have a look. While the other solutions will work just fine, I would like to suggest, this is a much faster and efficient way of showing multiple lists in a RecyclerView.

The idea is to add logic in your onCreateViewHolder and onBindViewHolder method so that you can inflate proper view for the exact positions in your RecyclerView.

I've added a sample project along with that wiki too. You might clone and check what it does. For convenience, I am posting the adapter that I have used.

public class DynamicListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int FOOTER_VIEW = 1;
    private static final int FIRST_LIST_ITEM_VIEW = 2;
    private static final int FIRST_LIST_HEADER_VIEW = 3;
    private static final int SECOND_LIST_ITEM_VIEW = 4;
    private static final int SECOND_LIST_HEADER_VIEW = 5;

    private ArrayList<ListObject> firstList = new ArrayList<ListObject>();
    private ArrayList<ListObject> secondList = new ArrayList<ListObject>();

    public DynamicListAdapter() {
    }

    public void setFirstList(ArrayList<ListObject> firstList) {
        this.firstList = firstList;
    }

    public void setSecondList(ArrayList<ListObject> secondList) {
        this.secondList = secondList;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // List items of first list
        private TextView mTextDescription1;
        private TextView mListItemTitle1;

        // List items of second list
        private TextView mTextDescription2;
        private TextView mListItemTitle2;

        // Element of footer view
        private TextView footerTextView;

        public ViewHolder(final View itemView) {
            super(itemView);

            // Get the view of the elements of first list
            mTextDescription1 = (TextView) itemView.findViewById(R.id.description1);
            mListItemTitle1 = (TextView) itemView.findViewById(R.id.title1);

            // Get the view of the elements of second list
            mTextDescription2 = (TextView) itemView.findViewById(R.id.description2);
            mListItemTitle2 = (TextView) itemView.findViewById(R.id.title2);

            // Get the view of the footer elements
            footerTextView = (TextView) itemView.findViewById(R.id.footer);
        }

        public void bindViewSecondList(int pos) {

            if (firstList == null) pos = pos - 1;
            else {
                if (firstList.size() == 0) pos = pos - 1;
                else pos = pos - firstList.size() - 2;
            }

            final String description = secondList.get(pos).getDescription();
            final String title = secondList.get(pos).getTitle();

            mTextDescription2.setText(description);
            mListItemTitle2.setText(title);
        }

        public void bindViewFirstList(int pos) {

            // Decrease pos by 1 as there is a header view now.
            pos = pos - 1;

            final String description = firstList.get(pos).getDescription();
            final String title = firstList.get(pos).getTitle();

            mTextDescription1.setText(description);
            mListItemTitle1.setText(title);
        }

        public void bindViewFooter(int pos) {
            footerTextView.setText("This is footer");
        }
    }

    public class FooterViewHolder extends ViewHolder {
        public FooterViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListHeaderViewHolder extends ViewHolder {
        public FirstListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListItemViewHolder extends ViewHolder {
        public FirstListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListHeaderViewHolder extends ViewHolder {
        public SecondListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListItemViewHolder extends ViewHolder {
        public SecondListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v;

        if (viewType == FOOTER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_footer, parent, false);
            FooterViewHolder vh = new FooterViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_ITEM_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list, parent, false);
            FirstListItemViewHolder vh = new FirstListItemViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list_header, parent, false);
            FirstListHeaderViewHolder vh = new FirstListHeaderViewHolder(v);
            return vh;

        } else if (viewType == SECOND_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list_header, parent, false);
            SecondListHeaderViewHolder vh = new SecondListHeaderViewHolder(v);
            return vh;

        } else {
            // SECOND_LIST_ITEM_VIEW
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list, parent, false);
            SecondListItemViewHolder vh = new SecondListItemViewHolder(v);
            return vh;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        try {
            if (holder instanceof SecondListItemViewHolder) {
                SecondListItemViewHolder vh = (SecondListItemViewHolder) holder;
                vh.bindViewSecondList(position);

            } else if (holder instanceof FirstListHeaderViewHolder) {
                FirstListHeaderViewHolder vh = (FirstListHeaderViewHolder) holder;

            } else if (holder instanceof FirstListItemViewHolder) {
                FirstListItemViewHolder vh = (FirstListItemViewHolder) holder;
                vh.bindViewFirstList(position);

            } else if (holder instanceof SecondListHeaderViewHolder) {
                SecondListHeaderViewHolder vh = (SecondListHeaderViewHolder) holder;

            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder vh = (FooterViewHolder) holder;
                vh.bindViewFooter(position);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null) return 0;

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0)
            return 1 + firstListSize + 1 + secondListSize + 1;   // first list header, first list size, second list header , second list size, footer
        else if (secondListSize > 0 && firstListSize == 0)
            return 1 + secondListSize + 1;                       // second list header, second list size, footer
        else if (secondListSize == 0 && firstListSize > 0)
            return 1 + firstListSize;                            // first list header , first list size
        else return 0;
    }

    @Override
    public int getItemViewType(int position) {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null)
            return super.getItemViewType(position);

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else if (position == firstListSize + 1)
                return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1 + firstListSize + 1)
                return FOOTER_VIEW;
            else if (position > firstListSize + 1)
                return SECOND_LIST_ITEM_VIEW;
            else return FIRST_LIST_ITEM_VIEW;

        } else if (secondListSize > 0 && firstListSize == 0) {
            if (position == 0) return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1) return FOOTER_VIEW;
            else return SECOND_LIST_ITEM_VIEW;

        } else if (secondListSize == 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else return FIRST_LIST_ITEM_VIEW;
        }

        return super.getItemViewType(position);
    }
}

There is another way of keeping your items in a single ArrayList of objects so that you can set an attribute tagging the items to indicate which item is from first list and which one belongs to second list. Then pass that ArrayList into your RecyclerView and then implement the logic inside adapter to populate them dynamically.

Hope that helps.

Visual Studio Code always asking for git credentials

After fighting with something like this for a little while, I think I came up with a good solution, especially when having multiple accounts across both GitHub and BitBucket. However for VSCode, it ultimately ended up as start it from a Git Bash terminal so that it inherited the environment variables from the bash session and it knew which ssh-agent to look at.

I realise this is an old post but I still really struggled to find one place to get the info I needed. Plus since 2017, ssh-agent got the ability to prompt you for a passphrase only when you try to access a repo.

I put my findings down here if anyone is interested:

android : Error converting byte to dex

In my case, I put

apply plugin: 'com.google.gms.google-services'

at the bottom of build.gradle file and set multiDexEnabled true in defaultConfig. Then just run and it works.

There is no argument given that corresponds to the required formal parameter - .NET Error

You have a constructor which takes 2 parameters. You should write something like:

new ErrorEventArg(errorMsv, lastQuery)

It's less code and easier to read.

EDIT

Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:

public ErrorEventArg() {}

The type or namespace name 'System' could not be found

You can check the framework on which system was created and developed, and then changes the framework of your current solution to the old framework. You can do this by right click on the solution and then choose properties. In Application section you can change the framework.

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

NodeJS accessing file with relative path

Simple! The folder named .. is the parent folder, so you can make the path to the file you need as such

var foobar = require('../config/dev/foobar.json');

If you needed to go up two levels, you would write ../../ etc

Some more details about this in this SO answer and it's comments

Git: How to remove proxy

This is in the case if first answer does not work The latest version of git does not require to set proxy it directly uses system proxy settings .so just do these

unset HTTP_PROXY
unset HTTPS_PROXY

in some systems you may also have to do

unset http_proxy
unset https_proxy

if you want to permanantly remove proxy then

sudo gsettings set org.gnome.system.proxy mode 'none'

Does bootstrap have builtin padding and margin classes?

There are built in classes, namely:

.padding-xs { padding: .25em; }
.padding-sm { padding: .5em; }
.padding-md { padding: 1em; }
.padding-lg { padding: 1.5em; }
.padding-xl { padding: 3em; }

.padding-x-xs { padding: .25em 0; }
.padding-x-sm { padding: .5em 0; }
.padding-x-md { padding: 1em 0; }
.padding-x-lg { padding: 1.5em 0; }
.padding-x-xl { padding: 3em 0; }

.padding-y-xs { padding: 0 .25em; }
.padding-y-sm { padding: 0 .5em; }
.padding-y-md { padding: 0 1em; }
.padding-y-lg { padding: 0 1.5em; }
.padding-y-xl { padding: 0 3em; }

.padding-top-xs { padding-top: .25em; }
.padding-top-sm { padding-top: .5em; }
.padding-top-md { padding-top: 1em; }
.padding-top-lg { padding-top: 1.5em; }
.padding-top-xl { padding-top: 3em; }

.padding-right-xs { padding-right: .25em; }
.padding-right-sm { padding-right: .5em; }
.padding-right-md { padding-right: 1em; }
.padding-right-lg { padding-right: 1.5em; }
.padding-right-xl { padding-right: 3em; }

.padding-bottom-xs { padding-bottom: .25em; }
.padding-bottom-sm { padding-bottom: .5em; }
.padding-bottom-md { padding-bottom: 1em; }
.padding-bottom-lg { padding-bottom: 1.5em; }
.padding-bottom-xl { padding-bottom: 3em; }

.padding-left-xs { padding-left: .25em; }
.padding-left-sm { padding-left: .5em; }
.padding-left-md { padding-left: 1em; }
.padding-left-lg { padding-left: 1.5em; }
.padding-left-xl { padding-left: 3em; }

.margin-xs { margin: .25em; }
.margin-sm { margin: .5em; }
.margin-md { margin: 1em; }
.margin-lg { margin: 1.5em; }
.margin-xl { margin: 3em; }

.margin-x-xs { margin: .25em 0; }
.margin-x-sm { margin: .5em 0; }
.margin-x-md { margin: 1em 0; }
.margin-x-lg { margin: 1.5em 0; }
.margin-x-xl { margin: 3em 0; }

.margin-y-xs { margin: 0 .25em; }
.margin-y-sm { margin: 0 .5em; }
.margin-y-md { margin: 0 1em; }
.margin-y-lg { margin: 0 1.5em; }
.margin-y-xl { margin: 0 3em; }

.margin-top-xs { margin-top: .25em; }
.margin-top-sm { margin-top: .5em; }
.margin-top-md { margin-top: 1em; }
.margin-top-lg { margin-top: 1.5em; }
.margin-top-xl { margin-top: 3em; }

.margin-right-xs { margin-right: .25em; }
.margin-right-sm { margin-right: .5em; }
.margin-right-md { margin-right: 1em; }
.margin-right-lg { margin-right: 1.5em; }
.margin-right-xl { margin-right: 3em; }

.margin-bottom-xs { margin-bottom: .25em; }
.margin-bottom-sm { margin-bottom: .5em; }
.margin-bottom-md { margin-bottom: 1em; }
.margin-bottom-lg { margin-bottom: 1.5em; }
.margin-bottom-xl { margin-bottom: 3em; }

.margin-left-xs { margin-left: .25em; }
.margin-left-sm { margin-left: .5em; }
.margin-left-md { margin-left: 1em; }
.margin-left-lg { margin-left: 1.5em; }
.margin-left-xl { margin-left: 3em; }

Getting absolute URLs using ASP.NET Core

You can get the url like this:

Request.Headers["Referer"]

Explanation

The Request.UrlReferer will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).

As for using Request.ServerVariables, per MSDN:

Request.ServerVariables Collection

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Request.Headers Property

Gets a collection of HTTP headers.

I guess I don't understand why you would prefer the Request.ServerVariables over Request.Headers, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.

So the best solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.

Unknown URL content://downloads/my_downloads

I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.

else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }

This the method used to get the filepath

   public static String getFilePath(Context context, Uri uri) {

    Cursor cursor = null;
    final String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

Guzzle 6: no more json() method for responses

I use json_decode($response->getBody()) now instead of $response->json().

I suspect this might be a casualty of PSR-7 compliance.

How to disable spring security for particular url

When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup");
}

And remove that line from the HttpSecurity part. This will tell Spring Security to ignore this URL and don't apply any filters to them.

How to solve a timeout error in Laravel 5

I had a similar problem just now. However, this had nothing to do with modifying the php.ini file. It was from a for loop. If you are having nested for loops, make sure you are using the iterator properly. In my case, I was iterating the outer iterator from my inner iterator.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Also you should know that you can force TLS v1.2 for Android 4.0 devices that don't have it enabled by default:

Put this code in onCreate() of your Application file:

try {
        ProviderInstaller.installIfNeeded(getApplicationContext());
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);
        sslContext.createSSLEngine();
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
            | NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

HttpClient - A task was cancelled?

in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception

My solution is

catch (Exception ex)
            {
                if (ex.InnerException is TimeoutException)
                {
                    ex = ex.InnerException;
                }
                else if (ex is TaskCanceledException)
                {
                    if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                    {
                        ex = new TimeoutException("Timeout occurred");
                    }
                }                
                Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);
            }

Karma: Running a single test file from command line

Even though --files is no longer supported, you can use an env variable to provide a list of files:

// karma.conf.js
function getSpecs(specList) {
  if (specList) {
    return specList.split(',')
  } else {
    return ['**/*_spec.js'] // whatever your default glob is
  }
}

module.exports = function(config) {
  config.set({
    //...
    files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
  });
});

Then in CLI:

$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

Update cordova plugins in one command

You can't update it. What you can do is uninstall the cordova plugin and add it again.

cordova plugin rm https://github.com/apache/cordova-plugin-camera --save
cordova plugin add https://github.com/apache/cordova-plugin-camera --save

How to resolve Value cannot be null. Parameter name: source in linq?

When you call a Linq statement like this:

// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));

You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:

var count = Enumerable.Count(x, s => s.StartsWith("x"));

So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.

How to pass multiple parameters from ajax to mvc controller?

function toggleCheck(employeeId) {
    var data =  'referenceid= '+ employeeId +'&referencestatus=' 1;
    console.log(data);
    $.ajax({
        type : 'POST',
        url : 'edit',
        data : data,
        cache: false,
        async : false,
        success : function(employeeId) {
            alert("Success");
            window.redirect = "Users.jsp";
        }
    });

}

Best Practices for Custom Helpers in Laravel 5

Custom Classes in Laravel 5, the Easy Way

This answer is applicable to general custom classes within Laravel. For a more Blade-specific answer, see Custom Blade Directives in Laravel 5.

Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}

Step 2: Create an alias:

<?php // Code within config/app.php

    'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...

Step 3: Run composer dump-autoload in the project root

Step 4: Use it in your Blade template:

<!-- Code within resources/views/template.blade.php -->

{!! Helper::shout('this is how to use autoloading correctly!!') !!}

Extra Credit: Use this class anywhere in your Laravel app:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::shout('now i\'m using my helper class in a controller!!');
    }
    ...

Source: http://www.php-fig.org/psr/psr-4/

Why it works: https://github.com/laravel/framework/blob/master/src/Illuminate/Support/ClassLoader.php

Where autoloading originates from: http://php.net/manual/en/language.oop5.autoload.php

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Goto Properties -> maven Remove the pom.xml from the activate profiles and follow the below steps.

Steps :

  1. Delete the .m2 repository
  2. Restart the Eclipse IDE
  3. Refresh and Rebuild it

How to include External CSS and JS file in Laravel 5

Place your assets in public directory and use the following

URL::to()

example

<link rel="stylesheet" type="text/css" href="{{ URL::to('css/style.css') }}">
<script type="text/javascript" src="{{ URL::to('js/jquery.min.js') }}"></script>

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

In my case I had to go to

File -> Settings -> Build, Execution, Deployment -> Gradle

and then I changed the Service directory path, which was pointing to a wrong location.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}

Git credential helper - update password

First find the version you are using with the Git command git --version. If you have a newer version than 1.7.10, then simply use this command:

git config --global credential.helper wincred

Then do the git fetch , then it prompts for the password update.

Now, it won't prompt for the password for multiple times in Git.

Changing specific text's color using NSMutableAttributedString in Swift

This extension works well when configuring the text of a label with an already set default color.

public extension String {
    func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
        let range = (self as NSString).range(of: substring)
        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        return attributedString
    }
}

For example

let text = "Hello World!"
let attributedText = text.setColor(.blue, ofSubstring: "World")

let myLabel = UILabel()
myLabel.textColor = .white
myLabel.attributedText = attributedText

Pycharm does not show plot

In my case, I wanted to do the following:

    plt.bar(range(len(predictors)), scores)
    plt.xticks(range(len(predictors)), predictors, rotation='vertical')
    plt.show()

Following a mix of the solutions here, my solution was to add before that the following commands:

    matplotlib.get_backend()
    plt.interactive(False)
    plt.figure()

with the following two imports

   import matplotlib
   import matplotlib.pyplot as plt

It seems that all the commands are necessary in my case, with a MBP with ElCapitan and PyCharm 2016.2.3. Greetings!

Why am I getting a "401 Unauthorized" error in Maven?

If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847

The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.

Custom Listview Adapter with filter Android

please check below code it will help you

DrawerActivity.userListview
            .setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    int pos = position;
                    Intent intent = new Intent(getContext(),
                            UserDetail.class);
                    intent.putExtra("model", list.get(position));
                    context.startActivity(intent);
                }
            });
    return convertView;
}

@Override
public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {

            ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
            UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
                    getContext(), getCount(), updatelist);

            if (results.equals(constraint)) {
                updatelist.add(modelobj);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {

                notifyDataSetInvalidated();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults filterResults = new FilterResults();
            list = new ArrayList<UserListModel>();

            if (constraint != null && DrawerActivity.userlist != null) {

                constraint = constraint.toString().toLowerCase();
                int length = DrawerActivity.userlist.size();
                int i = 0;
                while (i < length) {

                    UserListModel modelobj = DrawerActivity.userlist.get(i);
                    String data = modelobj.getFirstName() + " "
                            + modelobj.getLastName();
                    if (data.toLowerCase().contains(constraint.toString())) {
                        list.add(modelobj);
                    }

                    i++;
                }
                filterResults.values = list;
                filterResults.count = list.size();
            }
            return filterResults;
        }
    };
}

@Override
public int getCount() {
    return list.size();
}

@Override
public UserListModel getItem(int position) {

    return list.get(position);
}

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

I solved the simmilar problem, when i tried to push to repo via gitlab ci/cd pipeline by the command "gem install rake && bundle install"

How to add "required" attribute to mvc razor viewmodel text input editor

You can use the required html attribute if you want:

@Html.TextBoxFor(m => m.ShortName, 
new { @class = "form-control", placeholder = "short name", required="required"})

or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.

OR

You can get really advanced:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = new Dictionary<string, object>(
    Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));

 attributes.Add("class", "form-control");
 attributes.Add("placeholder", "short name");

  if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
  {
   attributes.Add("required", "required");
  }

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

or if you need it for multiple editor templates:

public static class ViewPageExtensions
{
  public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
  {
    // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
    var attributes = new Dictionary<string, object>(
      instance.Html.GetUnobtrusiveValidationAttributes(
         instance.ViewData.TemplateInfo.HtmlFieldPrefix));

    if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
    {
      attributes.Add("required", "required");
    }
  }
}

then in your templates:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = this.GetAttributes();

  attributes.Add("class", "form-control");
  attributes.Add("placeholder", "short name");

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

Update 1 (for Tomas who is unfamilar with ViewData).

What's the difference between ViewData and ViewBag?

Excerpt:

So basically it (ViewBag) replaces magic strings:

ViewData["Foo"]

with magic properties:

ViewBag.Foo

Laravel: Get base url

This:

echo url('/');

And this:

echo asset('/');

both displayed the home url in my case :)

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

hibernate.cfg.xml file should have the mapping for the tables like below. Check if it is missing in your file.

......
<hibernate-configuration>
......
......
  <session-factory>
......
<mapping class="com.test.bean.dbBean.testTableHibernate"/>
......
 </session-factory>

</hibernate-configuration>
.....

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

How to create a laravel hashed password

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

How to resolve this System.IO.FileNotFoundException

I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.

To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.

public MainWindow()
{
    try
    {
        InitializeComponent();
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}

Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.

Added the reference and problem solved.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of the answers, including the checked one did not work for me.

The solution was far more simple. I first removed the references from my BUS layer. Then deleted the dll's from the project (to make sure it's gone), then reinstalled JSON.NET from nuget packeges. And, the tricky part was, "turning it off and on again".

I just restarted visual studio, and there it worked!

So, if you try everything possible and still can't solve the problem, just try turning visual studio off and on again, it might help.

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

Just to add up my bit:
Remember, you're gonna need to have at least 2 areas in your MVC application to get the routeValues: { area="" } working; otherwise the area value will be used as a query-string parameter and you link will look like this: /?area=

If you don't have at least 2 areas, you can fix this behavior by:
1. editing the default route in RouteConfig.cs like this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

OR
2. Adding a dummy area to your MVC project.

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I think this problem occurs when you try to access your web driver object after

1) a window has closed and you haven't yet switched to the parent

2) you switched to a window that wasn't quite ready and has been updated since you switched

waiting for the windowhandles.count to be what you're expecting doesn't take into account the page content nor does document.ready. I'm still searching for a solution to this problem

Multiple radio button groups in MVC 4 Razor

I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.

For XLS file: HSSFWorkbook & HSSFSheet
For XLSX file: XSSFSheet & XSSFSheet

So in place of XSSFWorkbook use HSSFWorkbook and in place of XSSFSheet use HSSFSheet.

So your code should look like this after the changes are made:

HSSFWorkbook workbook = new HSSFWorkbook(file);

HSSFSheet sheet = workbook.getSheetAt(0);

Could not load file or assembly Exception from HRESULT: 0x80131040

If your solution contains two projects interacting with each other and both using one same reference, And if version of respective reference is different in both projects; Then also such errors occurred. Keep updating all references to latest one.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

You can create database & table like

public class DbHelper extends SQLiteOpenHelper {
private static final String DBNAME = "testdatbase.db";
private static final int VERSION = 1;

public DbHelper(Context context) {
    super(context, DBNAME, null, VERSION);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("create table BookDb(id integer primary key autoincrement,BookName text,Author text,IssuedOn text,DueDate text,Fine text,Totalfine text");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS BookDb");
    onCreate(db);
  }
}

Note : if you want create another table or add columns or no such table, just increment the VERSION

Error: [ng:areq] from angular controller

you forgot to include the controller in your index.html. The controller doesn't exist.

<script src="js/controllers/Controller.js"></script>

CSS height 100% percent not working

I believe you need to make sure that all the container div tags above the 100% height div also has 100% height set on them including the body tag and html.

Locking pattern for proper use of .NET MemoryCache

To avoid the global lock, you can use SingletonCache to implement one lock per key, without exploding memory usage (the lock objects are removed when no longer referenced, and acquire/release is thread safe guaranteeing that only 1 instance is ever in use via compare and swap).

Using it looks like this:

SingletonCache<string, object> keyLocks = new SingletonCache<string, object>();

const string CacheKey = "CacheKey";
static string GetCachedData()
{
    string expensiveString =null;
    if (MemoryCache.Default.Contains(CacheKey))
    {
        return MemoryCache.Default[CacheKey] as string;
    }

    // double checked lock
    using (var lifetime = keyLocks.Acquire(url))
    {
        lock (lifetime.Value)
        {
           if (MemoryCache.Default.Contains(CacheKey))
           {
              return MemoryCache.Default[CacheKey] as string;
           }

           cacheItemPolicy cip = new CacheItemPolicy()
           {
              AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
           };
           expensiveString = SomeHeavyAndExpensiveCalculation();
           MemoryCache.Default.Set(CacheKey, expensiveString, cip);
           return expensiveString;
        }
    }      
}

Code is here on GitHub: https://github.com/bitfaster/BitFaster.Caching

Install-Package BitFaster.Caching

There is also an LRU implementation that is lighter weight than MemoryCache, and has several advantages - faster concurrent reads and writes, bounded size, no background thread, internal perf counters etc. (disclaimer, I wrote it).

how to get the base url in javascript

var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I encountered a similar problem with glassfish application server and Oracle JDK/JRE but not in Open JDK/JRE.

When connecting to a SSL domain I always ran into:

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
...
Caused by: java.io.EOFException: SSL peer shut down incorrectly

The solution for me was to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files because the server only understood certificates that are not included in Oracle JDK by default, only OpenJDK includes them. After installing everything worked like charme.


JCE 7: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

JCE 8: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Posting form to different MVC post action depending on the clicked submit button

you can use ajax calls to call different methods without a postback

$.ajax({
    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something
     }
});

android studio 0.4.2: Gradle project sync failed error

After following Carlos steps I ended up deleting the

C:\Users\MyPath.AndroidStudioPreview Directory

Then re imported the project it seemed to fix my issue completely for the meanwhile, And speedup my AndroidStudio

Hope it helps anyone

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I removed the linkbutton from the UpdatePanel and also commented the Response.End() Success!!!

Cannot find firefox binary in PATH. Make sure firefox is installed

Did you add firefox to your path after you have started the selenium server? If that is the case selenium will still use old path. The solution is to tear down & restart selenium so that it will use the updated Path environment variable.

To check if firefox is added in your path correctly you can just launch a command line terminal "cmd" and type "firefox" + ENTER there. If firefox starts then everything is alright and restarting selenium server should fix the problem.

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.

The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

In our case we were getting UnmarshalException because a wrong Java package was specified in the following. The issue was resolved once the right package was in place:

@Bean
public Unmarshaller tmsUnmarshaller() {
    final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller
            .setPackagesToScan("java.package.to.generated.java.classes.for.xsd");
    return jaxb2Marshaller;
}

"The system cannot find the file specified"

I had this error and I found that the name of one of my connection strings was wrong. Check the names as well as the actual string.

Android sqlite how to check if a record exists

You can use like this:

String Query = "Select * from " + TABLE_NAME + " where " + Cust_id + " = " + cust_no;

Cursor cursorr = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursorr.close();
}
cursor.close();

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

Make sure the package version is equal across the solution. I just downgraded & upgraded Microsoft.AspNet.Mvc package across the solution and the problem solved.

Could not resolve placeholder in string value

In your configuration you have 2 PropertySourcesPlaceholderConfigurer instances.

applicationContext.xml

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="environment">
        <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
    </property>
</bean>

infraContext.xml

<context:property-placeholder location="classpath:context-core.properties"/>

By default a PlaceholderConfigurer is going to fail-fast, so if a placeholder cannot be resolved it will throw an exception. The instance from the applicationContext.xml file has no properties and as such will fail on all placeholders.

Solution: Remove the one from applicationContext.xml as it doesn't add anything it only breaks things.

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

this resolved this issue by adding namespace to Global.asax.cs file.

using System.Web.Http;

this resolved the issue.

could not extract ResultSet in hibernate

I Used the following properties in my application.properties file and the issue got resolved

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

and

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

earlier was getting an error

There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is 
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:280)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:254)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

Display string as html in asp.net mvc view

you can use @Html.Raw(str)

See MSDN for more

Returns markup that is not HTML encoded.

This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.

Twitter Bootstrap 3: How to center a block

center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

Web API Put Request generates an Http 405 Method Not Allowed error

WebDav-SchmebDav.. ..make sure you create the url with the ID correctly. Don't send it like http://www.fluff.com/api/Fluff?id=MyID, send it like http://www.fluff.com/api/Fluff/MyID.

Eg.

PUT http://www.fluff.com/api/Fluff/123 HTTP/1.1
Host: www.fluff.com
Content-Length: 11

{"Data":"1"}

This was busting my balls for a small eternity, total embarrassment.

URL.Action() including route values

outgoing url in mvc generated based on the current routing schema.

because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.

to solve this problem you should use UrlParameter.Optional:

 <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>

cannot load such file -- bundler/setup (LoadError)

I ran into the same issue, but I think it was due to spring caching some gems and configurations. I fixed it by running gem pristine --all.

This restores installed gems to pristine condition from files located in the gem cache.

or you can just try for your gem like

gem pristine your_gem_name

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Not sure if this is the cause of the problem, but I got this issue only after installing JVM Monitor.

Uninstalling JVM Monitor solved the issue for me.

PHP array() to javascript array()

<?php 
            $ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
            $disabledDaysRange = array();
            foreach($this->reservedDates as $dates) {
                 $date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
                 $disabledDaysRange[] = $date;
                 array_push($disabledDaysRange, $date);
            }

            $finalArr = json_encode($disabledDaysRange);
?>
<script>
var disabledDaysRange = <?=$finalArr?>;

</script>

apache server reached MaxClients setting, consider raising the MaxClients setting

Did you consider using nginx (or other event based web server) instead of apache?

nginx shall allow higher number of connections and consume much less resources (as it is event based and does not create separate process per connection). Anyway, you will need some processes, doing real work (like WSGI servers or so) and if they stay on the same server as the front end web server, you only shift the performance problem to a bit different place.

Latest apache version shall allow similar solution (configure it in event based manner), but this is not my area of expertise.

Location of hibernate.cfg.xml in project?

You can put the file "hibernate.cfg.xml" to the src folder (src\hibernate.cfg.xml) and then init the config as the code below:

Configuration configuration = new Configuration();          
sessionFactory =configuration.configure().buildSessionFactory();

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

Just posting in case it help someone else. The cause of this error for me was a missing do after creating a form with form_with. Hope that may help someone else

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

android.view.WindowManager$BadTokenException: Unable to add window"

Problem :

This exception occurs when the app is trying to notify the user from the background thread (AsyncTask) by opening a Dialog.

If you are trying to modify the UI from background thread (usually from onPostExecute() of AsyncTask) and if the activity enters finishing stage i.e.) explicitly calling finish(), user pressing home or back button or activity clean up made by Android then you get this error.

Reason :

The reason for this exception is that, as the exception message says, the activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.

Solution:

Use isFinishing() method which is called by Android to check whether this activity is in the process of finishing: be it explicit finish() call or activity clean up made by Android. By using this method it is very easy to avoid opening dialog from background thread when activity is finishing.

Also maintain a weak reference for the activity (and not a strong reference so that activity can be destroyed once not needed) and check if the activity is not finishing before performing any UI using this activity reference (i.e. showing a dialog).

eg.

private class chkSubscription extends AsyncTask<String, Void, String>{

  private final WeakReference<login> loginActivityWeakRef;

  public chkSubscription (login loginActivity) {
    super();
    this.loginActivityWeakRef= new WeakReference<login >(loginActivity)
  }

  protected String doInBackground(String... params) {
    //web service call
  }

  protected void onPostExecute(String result) {
    if(page.contains("error")) //when not subscribed
    {
      if (loginActivityWeakRef.get() != null && !loginActivityWeakRef.get().isFinishing()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
        builder.setCancelable(true);
        builder.setMessage(sucObject);
        builder.setInverseBackgroundForced(true);

        builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){
            dialog.dismiss();
          }
        });

        builder.show();
      }
    }
  }
}

Update :

Window Tokens:

As its name implies, a window token is a special type of Binder token that the window manager uses to uniquely identify a window in the system. Window tokens are important for security because they make it impossible for malicious applications to draw on top of the windows of other applications. The window manager protects against this by requiring applications to pass their application's window token as part of each request to add or remove a window. If the tokens don't match, the window manager rejects the request and throws a BadTokenException. Without window tokens, this necessary identification step wouldn't be possible and the window manager wouldn't be able to protect itself from malicious applications.

 A real-world scenario:

When an application starts up for the first time, the ActivityManagerService creates a special kind of window token called an application window token, which uniquely identifies the application's top-level container window. The activity manager gives this token to both the application and the window manager, and the application sends the token to the window manager each time it wants to add a new window to the screen. This ensures secure interaction between the application and the window manager (by making it impossible to add windows on top of other applications), and also makes it easy for the activity manager to make direct requests to the window manager.

Trigger an action after selection select2

//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

Selenium and xpath: finding a div with a class/id and verifying text inside

For class and text xpath-

//div[contains(@class,'Caption') and (text(),'Model saved')]

and

For class and id xpath-

//div[contains(@class,'gwt-HTML') and @id="alertLabel"]

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

Exception of type 'System.OutOfMemoryException' was thrown.

If you're using IIS Express, select Show All Application from IIS Express in the task bar notification area, then select Stop All.

Now re-run your application.

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Since the question was "display" :

@Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}")

How can I render a list select box (dropdown) with bootstrap?

Test: http://jsfiddle.net/brynner/hkwhaqsj/6/

HTML

<div class="input-group-btn select" id="select1">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><span class="selected">One</span> <span class="caret"></span></button>
    <ul class="dropdown-menu option" role="menu">
        <li id="1"><a href="#">One</a></li>
        <li id="2"><a href="#">Two</a></li>
    </ul>
</div>

jQuery

$('body').on('click','.option li',function(){
    var i = $(this).parents('.select').attr('id');
    var v = $(this).children().text();
    var o = $(this).attr('id');
    $('#'+i+' .selected').attr('id',o);
    $('#'+i+' .selected').text(v);
});

CSS

.select button {width:100%; text-align:left;}
.select .caret {position:absolute; right:10px; margin-top:10px;}
.select:last-child>.btn {border-top-left-radius:5px; border-bottom-left-radius:5px;}
.selected {padding-right:10px;}
.option {width:100%;}

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Make sure that the column values u added in entity class having get set properties also in the same order which is present in target table.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem with 'org.codehaus.mojo'-'jaxws-maven-plugin': could not resolve dependencies. Fortunately, I was able to do a Project > Clean in Eclipse, which resolved the issue.

Allow anything through CORS Policy

I had issues, especially with Chrome as well. What you did looks essentially like what I did in my application. The only difference is that I am responding with a correct hostnames in my Origin CORS headers and not a wildcard. It seems to me that Chrome is picky with this.

Switching between development and production is a pain, so I wrote this little function which helps me in development mode and also in production mode. All of the following things happen in my application_controller.rb unless otherwise noted, it might not be the best solution, but rack-cors didn't work for me either, I can't remember why.

def add_cors_headers
  origin = request.headers["Origin"]
  unless (not origin.nil?) and (origin == "http://localhost" or origin.starts_with? "http://localhost:")
    origin = "https://your.production-site.org"
  end
  headers['Access-Control-Allow-Origin'] = origin
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
  allow_headers = request.headers["Access-Control-Request-Headers"]
  if allow_headers.nil?
    #shouldn't happen, but better be safe
    allow_headers = 'Origin, Authorization, Accept, Content-Type'
  end
  headers['Access-Control-Allow-Headers'] = allow_headers
  headers['Access-Control-Allow-Credentials'] = 'true'
  headers['Access-Control-Max-Age'] = '1728000'
end

And then I have this little thing in my application_controller.rb because my site requires a login:

before_filter :add_cors_headers
before_filter {authenticate_user! unless request.method == "OPTIONS"}

In my routes.rb I also have this thing:

match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}

and this method looks like this:

def empty
  render :nothing => true
end

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Add these two lines to your build.gradle in the android section:

android{
    compileOptions {
            sourceCompatibility 1.8
            targetCompatibility 1.8
        }
}

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

Gradle: Execution failed for task ':processDebugManifest'

compile 'com.github.wenchaojiang:AndroidSwipeableCardStack:0.1.1'

If this is the dependency you have added then change it to:

compile 'com.github.wenchaojiang:AndroidSwipeableCardStack:0.1.4'

and make sure that target sdk should not be less then 15.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

Change this part in your Web.config, according to the below code.(try this, it works to me.)

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.; Integrated Security=True; MultipleActiveResultSets=True" />   
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

UITableView with fixed section headers

You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.

jQuery UI Dialog - missing close icon

I know this question is old but I just had this issue with jquery-ui v1.12.0.

Short Answer Make sure you have a folder called Images in the same place you have jquery-ui.min.css. The images folder must contains the images found with a fresh download of the jquery-ui

Long answer

My issue is that I am using gulp to merge all of my css files into a single file. When I do that, I am changing the location of the jquery-ui.min.css. The css code for the dialog expects a folder called Images in the same directory and inside this folder it expects default icons. since gulp was not copying the images into the new destination it was not showing the x icon.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Add before OpenDatabase this lines:

File outFile = new File(Environment.getDataDirectory(), outFileName);
outFile.setWritable(true);
SQLiteDatabase.openDatabase(outFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

I came into this issue when I copy my local repository.

sudo cp -r original_repo backup_repo
cd backup_repo
git status
fatal: Not a git repository (or any parent up to mount point /data)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).

I've try git init as some answer suggested, but it doesn't work.

sudo git init
Reinitialized existing Git repository in /data/HQ/SC_Educations/hq_htdocs/HQ_Educations_bak/.git/

I solved it by change the owner of the repo

sudo chown -R www:www ../backup_repo
git status
# On branch develop
nothing to commit, working directory clean

The remote server returned an error: (403) Forbidden

We should access the website using the name given in the certificate.enter image description here

JDBC connection to MSSQL server in windows authentication mode

For the current MS SQL JDBC driver (6.4.0) tested under Windows 7 from within DataGrip:

  1. as per documentation on authenticationScheme use fully qualified domain name as host e.g. server.your.domain not just server; the documentation also mentions the possibility to specify serverSpn=MSSQLSvc/fqdn:port@REALM, but I can not provide you with details on how to use this. When specifying a fqdn as host the spn is auto-generated.
  2. set authenticationScheme=JavaKerberos
  3. set integratedSecurity=true
  4. use your unqualified user-name (and password) to log in

As this is using JavaKerberos I would appreciate feedback on whether or not this works from outside Windows. I believe that no .dll is needed, but as I used DataGrip to create the connection I am uncertain; I would also appreciate Feedback on this!

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

setting JAVA_HOME & CLASSPATH in CentOS 6

Providing javac is set up through /etc/alternatives/javac, you can add to your .bash_profile:

JAVA_HOME=$(l=$(which javac) ; while : ; do nl=$(readlink ${l}) ; [ "$nl" ] || break ; l=$nl ; done ; echo $(cd $(dirname $l)/.. ; pwd) )
export JAVA_HOME

symfony2 twig path with parameter url creation

In Twig:

{% for l in locations %}

<tr>
    <td>
        <input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
        <label for="filled-in-box-{{ l.idLocation }}"></label>
    </td>
    <td>{{ l.loc }}</td>
    <td>{{ l.mun }}</td>
    <td>{{ l.pro }}</td>
    <td>{{ l.cou }}</td>
    {#<td>
        {% if l.active == 1  %}
            <span class="fa fa-check"></span>
        {% else %}
            <span class="fa fa-close"></span>
        {% endif %}
    </td>#}
    <td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
    </td>
</tr>{% endfor %}

The route admin_edit_location:

admin_edit_location:
  path: /edit_location/{id}
  defaults: { _controller: "AppBundle:Admin:editLocation" }
  methods: GET

And the controller

public function editLocationAction($id){
    // use $id 

    $em = $this->getDoctrine()->getManager();
    $location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
    'id'    => $id
    ));
}

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

AngularJS: How do I manually set input to $valid in controller?

It is very simple. For example : in you JS controller use this:

$scope.inputngmodel.$valid = false;

or

$scope.inputngmodel.$invalid = true;

or

$scope.formname.inputngmodel.$valid = false;

or

$scope.formname.inputngmodel.$invalid = true;

All works for me for different requirement. Hit up if this solve your problem.

notifyDataSetChange not working from custom adapter

I had the same problem using ListAdapter

I let Android Studio implement methods for me and this is what I got:

public class CustomAdapter implements ListAdapter {
    ...
    @Override
    public void registerDataSetObserver(DataSetObserver observer) {

    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {

    }
    ...
}

The problem is that these methods do not call super implementations so notifyDataSetChange is never called.

Either remove these overrides manually or add super calls and it should work again.

@Override
public void registerDataSetObserver(DataSetObserver observer) {
    super.registerDataSetObserver(observer);
}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    super.unregisterDataSetObserver(observer);
}

Remove credentials from Git

Try using the below command.

git credential-manager

Here you can get various options to manage your credentials (check the below screen).

Enter image description here

Or you can even directly try this command:

git credential-manager uninstall

This will start prompting for passwords again on each server interaction request.

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

My problem was solved that way:

Your username is probably restricted, You must grant full access to the user.

  1. Right Click on Project and select Properties
  2. Click on Tab Security
  3. Click Edit button
  4. Found Current User and Permission for User Allow Full Control

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

The only difference between files that causing the issue is the 8th byte of file

CA FE BA BE 00 00 00 33 - Java 7

vs.

CA FE BA BE 00 00 00 32 - Java 6

Setting -XX:-UseSplitVerifier resolves the issue. However, the cause of this issue is https://bugs.eclipse.org/bugs/show_bug.cgi?id=339388

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      Console.Write("*");         
      await Task.Delay(1000);
  }
}, token);

Console.WriteLine("Press enter to stop the task"); 
Console.ReadLine(); 
cancellationTokenSource.Cancel(); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
{                 
    while (!token.IsCancellationRequested) {
         Console.Write("*");                      
         await Task.Delay(1000);                
    }           
    token.ThrowIfCancellationRequested();               
}, token)
.ContinueWith(t =>
 {
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
 },TaskContinuationOptions.OnlyOnCanceled);  
 
Console.WriteLine("Press enter to stop the task");                 
Console.ReadLine();                 
cancellationTokenSource.Cancel();                 
task.Wait(); 

Hope this helps to understand better.

Can you change a path without reloading the controller in AngularJS?

For those who need path() change without controllers reload - Here is plugin: https://github.com/anglibs/angular-location-update

Usage:

$location.update_path('/notes/1');

Based on https://stackoverflow.com/a/24102139/1751321

P.S. This solution https://stackoverflow.com/a/24102139/1751321 contains bug after path(, false) called - it will break browser navigation back/forward until path(, true) called

CS0234: Mvc does not exist in the System.Web namespace

I had this problem, but all the applications in IIS were broken when they had been working previously. None of the marked solutions helped me. The problem ended up being an extra copy of web.config had been introduced to my root directory. I removed that file and problem solved.

What is Bootstrap?

Bootstrap is Open source HTML Framework. which compatible at almost every Browser. Basically Large Screen Browser width is >992px and extra Large 1200px. so by using Bootstrap defined classes we can adjust screen resolution for displaying contents at every screen from small mobiles to Larger Screen. I tried to explain very short. for Example :

<div class="col-sm-3">....</div>
<div class="col-sm-9">....</div>

MVC 4 client side validation not working

For me this was a lot of searching. Eventually I decided to use NuGet instead of downloading the files myself. I deleted all involved scripts and scriptbundles and got the following packages (latest versions as of now)

  • jQuery (3.1.1)
  • jQuery Validation (1.15.1)
  • Microsoft jQuery Ubobtrusive Ajax (3.2.3)
  • Microsoft jQuery Unobtrusive Validation (3.2.3)

Then I added these bundles to the BundleConfig file:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate.js",
                "~/Scripts/jquery.validate.unobtrusive.js",
                "~/Scripts/jquery.unobtrusive-ajax.js"));

I added this reference to _Layout.cshtml:

@Scripts.Render("~/bundles/jquery")

And I added this reference to whichever view I needed validation:

@Scripts.Render("~/bundles/jqueryval")

Now everything worked.

Don't forget these things (many people forget them):

  • Form tags (@using (Html.BeginForm()))
  • Validation Summary (@Html.ValidationSummary())
  • Validation Message on your input (Example: @Html.ValidationMessageFor(model => model.StartDate))
  • Configuration ()
  • The order of the files added to the bundle (as stated above)

Android ListView not refreshing after notifyDataSetChanged

An answer from AlexGo did the trick for me:

getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
         messages.add(m);
         adapter.notifyDataSetChanged();
         getListView().setSelection(messages.size()-1);
        }
});

List Update worked for me before when the update was triggered from a GUI event, thus being in the UI thread.

However, when I update the list from another event/thread - i.e. a call from outside the app, the update would not be in the UI thread and it ignored the call to getListView. Calling the update with runOnUiThread as above did the trick for me. Thanks!!

Using other keys for the waitKey() function of opencv

If you want to pause the program to take screenshots of the progress

(shown in let's say cv2.imshow)

cv2.waitKey(0) would continue after pressing "Scr" button (or its combination), but you can try this

cv2.waitKey(0)
input('')

cv2.waitkey(0) to give the program enough time to process everything you want to see in the imshow and input('')

to make it wait for you to press Enter in the console window

this works on python 3

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.

In Jelly Bean it is: Settings > Data Usage > mobile data

Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.

For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.

It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.

Hibernate table not mapped error in HQL query

In addition to the accepted answer, one other check is to make sure that you have the right reference to your entity package in sessionFactory.setPackagesToScan(...) while setting up your session factory.

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

I recommend just disabling this rule in Sonar, there is no real benefit of introducing a private constructor, just redundant characters in your codebase other people need to read and computer needs to store and process.

Set Focus on EditText

    mEditText.setFocusableInTouchMode(true);
    mEditText.requestFocus();

    if(mEditText.requestFocus()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

How to change already compiled .class file without decompile?

You can follow these steps to modify your java class:

  1. Decompile the .class file as you have done and save it as .java
  2. Create a project in Eclipse with that java file, the original JAR as library, and all its dependencies
  3. Change the .java and compile
  4. Get the modified .class file and put it again inside the original JAR.

How create a new deep copy (clone) of a List<T>?

List<Book> books_2 = new List<Book>(books_2.ToArray());

That should do exactly what you want. Demonstrated here.

Use ASP.NET MVC validation with jquery ajax?

You can do it this way:

(Edit: Considering that you're waiting for a response json with dataType: 'json')

.NET

public JsonResult Edit(EditPostViewModel data)
{
    if(ModelState.IsValid) 
    {
       // Save  
       return Json(new { Ok = true } );
    }

    return Json(new { Ok = false } );
}

JS:

success: function (data) {
    if (data.Ok) {
      alert('success');
    }
    else {
      alert('problem');
    }
},

If you need I can also explain how to do it by returning a error 500, and get the error in the event error (ajax). But in your case this may be an option

Updating records codeigniter

In your_controller write this...

public function update_title() 
{   
    $data = array
      (
        'table_id' => $this->input->post('table_id'),
        'table_title' => $this->input->post('table_title')
      );

    $this->load->model('your_model'); // First load the model
    if($this->your_model->update_title($data)) // call the method from the controller
    {
        // update successful...
    }
    else
    {
        // update not successful...
    }

}

While in your_model...

public function update_title($data)
{
   $this->db->set('table_title',$data['title'])
         ->where('table_id',$data['table_id'])
        ->update('your_table');
}

This will works fine...

Jersey client: How to add a list as query parameter

If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:

@Path("/service/echo") public class MyServiceImpl {
    public MyServiceImpl() {
        super();
    }

    @GET
    @Path("/withlist")
    @Produces(MediaType.TEXT_PLAIN)
    public Response echoInputList(@QueryParam("list") final List<String> inputList) {
        return Response.ok(inputList).build();
    }
}

Your client would send a request corresponding to:

GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye

Which would result in inputList being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'

Pass data to layout that are common to all pages

There's another way to handle this. Maybe not the cleanest way from an architectural point of view, but it avoids a lot of pain involved with the other answers. Simply inject a service in the Razor layout and then call a method that gets the necessary data:

@inject IService myService

Then later in the layout view:

@if (await myService.GetBoolValue()) {
   // Good to go...
}

Again, not clean in terms of architecture (obviously the service shouldn't be injected directly in the view), but it gets the job done.

How can I sort an ArrayList of Strings in Java?

You can use TreeSet that automatically order list values:

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");

        TreeSet <String>tree = new TreeSet<String>();
        tree.add("aaa");
        tree.add("acbbb");
        tree.add("aab");
        tree.add("c");
        tree.add("a");

        Iterator iterator;
        iterator = tree.iterator();

        System.out.print("Tree set data: ");

        //Displaying the Tree set data
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
    }

}

I lastly add 'a' but last element must be 'c'.

Proper usage of .net MVC Html.CheckBoxFor

That isn't the proper syntax

The first parameter is not checkbox value but rather view model binding for the checkbox hence:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes. I'm not 100% sure that the above attribute will initially check your checkbox, but you can try. But beware. Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to false.

The correct way

Although my proper suggestion would be to provide initialized model to your view with that particular boolean property initialized to true.

Property types

As per Asp.net MVC HtmlHelper extension methods and inner working, checkboxes need to bind to boolean values and not integers what seems that you'd like to do. In that case a hidden field could store the id.

Other helpers

There are of course other helper methods that you can use to get greater flexibility about checkbox values and behaviour:

@Html.CheckBox("templateId", new { value = item.TemplateID, @checked = true });

Note: checked is an HTML element boolean property and not a value attribute which means that you can assign any value to it. The correct HTML syntax doesn't include any assignments, but there's no way of providing an anonymous C# object with undefined property that would render as an HTML element property.

Visual Studio debugging/loading very slow

For me, I implemented this tip which basically drastically improved performance by adding the following two attributes to compilation tag in web.config

<compilation ... batch="false" optimizeCompilations="true"> ... </compilation>

What does batch="false" do?

It makes pre-compilation more selective by compiling only pages that have changed and require re-compiling

What exactly is the optimizeCompilations doing? Source

ASP.NET uses a per application hash code which includes the state of a number of things, including the bin and App_Code folder, and global.asax. Whenever an ASP.NET app domain starts, it checks if this hash code has changed from what it previously computed. If it has, then the entire codegen folder (where compiled and shadow copied assemblies live) is wiped out.

When this optimization is turned on (via optimizeCompilations="true"), the hash no longer takes into account bin, App_Code and global.asax. As a result, if those change we don't wipe out the codegen folder.

Reference: Compilation element on MSDN

How to JUnit test that two List<E> contain the same elements in the same order?

The equals() method on your List implementation should do elementwise comparison, so

assertEquals(argumentComponents, returnedComponents);

is a lot easier.

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Make sure that you haven't already used header in another file, or you will get a nasty error. See the docs for more.

Sorting dropdown alphabetically in AngularJS

For anyone who wants to sort the variable in third layer:

<select ng-option="friend.pet.name for friend in friends"></select>

you can do it like this

<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>

How to retrieve data from sqlite database in android and display it in TextView

on button click, first open the database, fetch the data and close the data base like this

public class cytaty extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.galeria);

        Button bLosuj = (Button) findViewById(R.id.button1);
        bLosuj.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            myDatabaseHelper = new DatabaseHelper(cytaty.this);
            myDatabaseHelper.openDataBase();

            String text = myDatabaseHelper.getYourData(); //this is the method to query

            myDatabaseHelper.close(); 
            // set text to your TextView
            }
        });
    }
}

and your getYourData() in database class would be like this

public String[] getAppCategoryDetail() {

    final String TABLE_NAME = "name of table";

    String selectQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db  = this.getReadableDatabase();
    Cursor cursor      = db.rawQuery(selectQuery, null);
    String[] data      = null;

    if (cursor.moveToFirst()) {
        do {
           // get the data into array, or class variable
        } while (cursor.moveToNext());
    }
    cursor.close();
    return data;
}

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

Razor Views not seeing System.Web.Mvc.HtmlHelper

I had run a project clean, and installed or reinstalled everything and was still getting lots of Intellisense errors, even though my site was compiling and running fine. Intellisense finally worked for me when I changed the version numbers in my web.config file in the Views folder. In my case I'm coding a module in Orchard, which runs in an MVC area, but I think this will help anyone using the latest release of MVC. Here is my web.config from the Views folder

    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
          <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
      </configSections>

      <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="Orchard.Mvc.ViewEngines.Razor.WebViewPage">
          <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Linq" />
            <add namespace="System.Collections.Generic" />
          </namespaces>
        </pages>
      </system.web.webPages.razor>

      <system.web>

        <!--
            Enabling request validation in view pages would cause validation to occur
            after the input has already been processed by the controller. By default
            MVC performs request validation before a controller processes the input.
            To change this behavior apply the ValidateInputAttribute to a
            controller or action.
        -->
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
          <controls>
            <add assembly="System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" namespace="System.Web.Mvc" tagPrefix="mvc" />
          </controls>
        </pages>
      </system.web>

      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />

        <handlers>
          <remove name="BlockViewHandler"/>
          <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
      </system.webServer>
    </configuration>

Android SQLite Example

Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.

http://technologyguid.com/android-sqlite-database-app-example/

Call static method with reflection

You could really, really, really optimize your code a lot by paying the price of creating the delegate only once (there's also no need to instantiate the class to call an static method). I've done something very similar, and I just cache a delegate to the "Run" method with the help of a helper class :-). It looks like this:

static class Indent{    
     public static void Run(){
         // implementation
     }
     // other helper methods
}

static class MacroRunner {

    static MacroRunner() {
        BuildMacroRunnerList();
    }

    static void BuildMacroRunnerList() {
        macroRunners = System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(x => x.Namespace.ToUpper().Contains("MACRO"))
            .Select(t => (Action)Delegate.CreateDelegate(
                typeof(Action), 
                null, 
                t.GetMethod("Run", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
            .ToList();
    }

    static List<Action> macroRunners;

    public static void Run() {
        foreach(var run in macroRunners)
            run();
    }
}

It is MUCH faster this way.

If your method signature is different from Action you could replace the type-casts and typeof from Action to any of the needed Action and Func generic types, or declare your Delegate and use it. My own implementation uses Func to pretty print objects:

static class PrettyPrinter {

    static PrettyPrinter() {
        BuildPrettyPrinterList();
    }

    static void BuildPrettyPrinterList() {
        printers = System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(x => x.Name.EndsWith("PrettyPrinter"))
            .Select(t => (Func<object, string>)Delegate.CreateDelegate(
                typeof(Func<object, string>), 
                null, 
                t.GetMethod("Print", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
            .ToList();
    }

    static List<Func<object, string>> printers;

    public static void Print(object obj) {
        foreach(var printer in printers)
            print(obj);
    }
}

How to get index in Handlebars each helper?

Arrays:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

If you have arrays of objects... you can iterate through the children:

{{#each array}}
    //each this = { key: value, key: value, ...}
    {{#each this}}
        //each key=@key and value=this of child object 
        {{@key}}: {{this}}
        //Or get index number of parent array looping
        {{@../index}}
    {{/each}}
{{/each}}

Objects:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

If you have nested objects you can access the key of parent object with {{@../key}}

Javascript : calling function from another file

Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.

https://jsfiddle.net/mvora/mrLmkxmo/

 /******** PUT THIS CODE IN ONE JS FILE *******/

    var secondFileFuntion = function(){
        this.name = 'XYZ';
    }

    secondFileFuntion.prototype.getSurname = function(){
     return 'ABC';
    }


    var secondFileObject = new secondFileFuntion();

    /******** Till Here *******/

    /******** PUT THIS CODE IN SECOND JS FILE *******/

    function firstFileFunction(){
      var name = secondFileObject.name;
      var surname = secondFileObject.getSurname()
      alert(name);
      alert(surname );
    }

    firstFileFunction();

If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.

Just take care of sequence of including these files in index.html

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

The collection comments in your model class Topic is lazily loaded, which is the default behaviour if you don't annotate it with fetch = FetchType.EAGER specifically.

It is mostly likely that your findTopicByID service is using a stateless Hibernate session. A stateless session does not have the first level cache, i.e., no persistence context. Later on when you try to iterate comments, Hibernate will throw an exception.

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: mvc3.model.Topic.comments, no session or session was closed

The solution can be:

  1. Annotate comments with fetch = FetchType.EAGER

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)   
    private Collection<Comment> comments = new LinkedHashSet<Comment>();
    
  2. If you still would like comments to be lazily loaded, use Hibernate's stateful sessions, so that you'll be able to fetch comments later on demand.

git: 'credential-cache' is not a git command

We had the same issue with our Azure DevOps repositories after our domain changed, i.e. from @xy.com to @xyz.com. To fix this issue, we generated a fresh personal access token with the following permissions:

Code: read & write Packaging: read

Then we opened the Windows Credential Manager, added a new generic windows credential with the following details:

Internet or network address: "git:{projectname}@dev.azure.com/{projectname}" - alternatively you should use your git repository name here.
User name: "Personal Access Token"
Password: {The generated Personal Access Token}

Afterwards all our git operations were working again. Hope this helps someone else!

How to change the display name for LabelFor in razor in mvc3?

Decorate the model property with the DisplayName attribute.

Android Error - Open Failed ENOENT

With sdk, you can't write to the root of internal storage. This cause your error.

Edit :

Based on your code, to use internal storage with sdk:

final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");

Multiple files upload (Array) with CodeIgniter 2.0

        // Change $_FILES to new vars and loop them
        foreach($_FILES['files'] as $key=>$val)
        {
            $i = 1;
            foreach($val as $v)
            {
                $field_name = "file_".$i;
                $_FILES[$field_name][$key] = $v;
                $i++;   
            }
        }
        // Unset the useless one ;)
        unset($_FILES['files']);

        // Put each errors and upload data to an array
        $error = array();
        $success = array();

        // main action to upload each file
        foreach($_FILES as $field_name => $file)
        {
            if ( ! $this->upload->do_upload($field_name))
            {
                echo ' failed ';
            }else{
                echo ' success ';
            }
        }

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

Serialize form data to JSON

I couldn't find an answer that would solve this:

[{name:"Vehicle.Make", value: "Honda"}, {name:"Vehicle.VIN", value: "123"}]

This calls for this object:

{Vehicle: {Make: "Honda", "VIN": "123"}}

So I had to write a serializer of my own that would solve this:

function(formArray){
        var obj = {};
        $.each(formArray, function(i, pair){
            var cObj = obj, pObj, cpName;
            $.each(pair.name.split("."), function(i, pName){
                pObj = cObj;
                cpName = pName;
                cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
            });
            pObj[cpName] = pair.value;
        });
        return obj;
    }

Maybe it will help somebody.

Pass a simple string from controller to a view MVC3

If you are trying to simply return a string to a View, try this:

public string Test()
{
     return "test";
}

This will return a view with the word test in it. You can insert some html in the string.

You can also try this:

public ActionResult Index()
{
    return Content("<html><b>test</b></html>");
}

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

These guys gave you the reason why is failing but not how to solve it. This problem may appear even if you have a jdk which matches JVM which you are trying it into.

Project -> Properties -> Java Compiler

Enable project specific settings.

Then select Compiler Compliance Level to 1.6 or 1.5, build and test your app.

Now, it should be fine.

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

If you still facing the issue try this:

Open your IIS Manager -> Application Pools -> select your app pool -> Advance Setting -> Under 'Process Model' set 'Load User Profile' setting as True

enter image description here

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

I got the same error with vlc component when i changed the framework from 4.5 to 4. but it worked for me when I changed the platform from Any CPU to x86.

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

For whatever reason, TWO of my solutions have web projects that spontaneously uninstalled asp.net MVC somehow. I installed it from Nuget and now they both work again. This happened after a recent batch of windows updates that included .net framework updates for the version I was using (4.5.1).

Edit: From the .Net Web Development and Tools Blog:

Microsoft Asp.Net MVC Security Update MS14-059 broke my build!

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

After much pain, googling and hair pulling, I ended up uninstalling MVC 4 using nuget, deleting all references to MVC, razor and infrastructure from the web config, deleting the dlls from the bin folder - then using nuget to reinstall everything. It took less time then trying to figure out why the dlls did not match.

MVC 4 @Scripts "does not exist"

Import System.Web.Optimization on top of your razor view as follows:

@using System.Web.Optimization

In PowerShell, how can I test if a variable holds a numeric value?

$itisint=$true
try{
 [int]$vartotest
}catch{
 "error converting to int"
 $itisint=$false
}

this is more universal, because this way you can test also strings (read from a file for example) if they represent number. The other solutions using -is [int] result in false if you would have "123" as string in a variable. This also works on machines with older powershell then 5.1

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

Error: "setFile(null,false) call failed" when using log4j

I suspect that the variable ${file.name} is not substituted correctly. As a result, the value of log4j.appender.FILE.File becomes logs/. As such, Java tries to create a log file named logs/, but probably it is an existing directory, so you get the exception.

As a quick remedy, change the log4j.appender.FILE.File setting to point to file by absolute path, for example /tmp/mytest.log. You should not get an exception.

After that you can proceed to debugging why ${file.name} is not replaced correctly in your runtime environment.

What are the differences between Mustache.js and Handlebars.js?

One more subtle difference is the treatment of falsy values in {{#property}}...{{/property}} blocks. Most mustache implementations will just obey JS falsiness here, not rendering the block if property is '' or '0'.

Handlebars will render the block for '' and 0, but not other falsy values. This can cause some trouble when migrating templates.

How to hide Bootstrap modal with javascript?

I used this simple code:

$("#MyModal .close").click();

How to fix System.NullReferenceException: Object reference not set to an instance of an object

I was getting this same error, but for me this was due to a method in a base class (in Project A) having the output type changed from a non-void type to void. A child class existed in Project B (which I didn't want used and had marked obsolete) that I missed when performing this update and hence started throwing this error.

1>CSC : error CS8104: An error occurred while writing the output file: System.NullReferenceException: Object reference not set to an instance of an object.

Original Code:

[Obsolete("Calling this method will throw an error")]
public override CompletionStatus Run()
{
    throw new CustomException("Run process not supported.");
}

Revised Code:

[Obsolete("Calling this method will throw an error")]
public override void Run()
{
    throw new CustomException("Run process not supported.");
}

What is difference between INNER join and OUTER join

Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. check this

How to read xml file contents in jQuery and display in html elements?

Get the XML using Ajax call, find the main element, loop through all the element and append data in table.

Sample code

 //ajax call to load XML and parse it
        $.ajax({
            type: 'GET',
            url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml',           // The file path.
            dataType: 'xml',    
            success: function(xml) {
               //find all book tags, loop them and append to table body
                $(xml).find('book').each(function() {
                    
                    // Append new data to the tbody element.
                    $('#tableBody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('genre').text() + '</td> ' +
                                '<td>' +
                                $(this).find('price').text() + '</td> ' +
                                '<td>' +
                                $(this).find('description').text() + '</td> ' +
                        '</tr>');
                });
            }
        });

Fiddle link: https://jsfiddle.net/pn9xs8hf/2/

Source: Read XML using jQuery & load it in HTML Table

How do I get Bin Path?

You could do this

    Assembly asm = Assembly.GetExecutingAssembly();
    string path = System.IO.Path.GetDirectoryName(asm.Location);

NuGet Packages are missing

I had the same error (missing exactly the same package) today. I also created a MVC + Web API project.

It happend because I moved the app files (including the .csproj) file to another location. I manually updated the .sln file but all packages dependencies are now (Visual Studio 2015) stored in .csproj file.

Editing the .csproj file and correcting the relative path to the solution folder (which contains the packages folder) solved the problem for me.

From io.Reader to string in Go

EDIT:

Since 1.10, strings.Builder exists. Example:

buf := new(strings.Builder)
n, err := io.Copy(buf, r)
// check errors
fmt.Println(buf.String())

OUTDATED INFORMATION BELOW

The short answer is that it it will not be efficient because converting to a string requires doing a complete copy of the byte array. Here is the proper (non-efficient) way to do what you want:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
s := buf.String() // Does a complete copy of the bytes in the buffer.

This copy is done as a protection mechanism. Strings are immutable. If you could convert a []byte to a string, you could change the contents of the string. However, go allows you to disable the type safety mechanisms using the unsafe package. Use the unsafe package at your own risk. Hopefully the name alone is a good enough warning. Here is how I would do it using unsafe:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
b := buf.Bytes()
s := *(*string)(unsafe.Pointer(&b))

There we go, you have now efficiently converted your byte array to a string. Really, all this does is trick the type system into calling it a string. There are a couple caveats to this method:

  1. There are no guarantees this will work in all go compilers. While this works with the plan-9 gc compiler, it relies on "implementation details" not mentioned in the official spec. You can not even guarantee that this will work on all architectures or not be changed in gc. In other words, this is a bad idea.
  2. That string is mutable! If you make any calls on that buffer it will change the string. Be very careful.

My advice is to stick to the official method. Doing a copy is not that expensive and it is not worth the evils of unsafe. If the string is too large to do a copy, you should not be making it into a string.

How to clear memory to prevent "out of memory error" in excel vba?

I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.

What is the difference between <section> and <div>?

<div> Vs <Section>

Round 1

<div>: The HTML element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as <article> or <nav>) is appropriate.

<section>: The HTML Section element (<section>) represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading.


Round 2

<div>: Browser Support enter image description here

<section>: Browser Support

The numbers in the table specifies the first browser version that fully supports the element. enter image description here

In that vein, a div is relevant only from a pure CSS or DOM perspective, whereas a section is relevant also for semantics and, in a near future, for indexing by search engines.

Remove empty elements from an array in Javascript

An in place solution:

function pack(arr) { // remove undefined values
  let p = -1
  for (let i = 0, len = arr.length; i < len; i++) {
    if (arr[i] !== undefined) { if (p >= 0) { arr[p] = arr[i]; p++ } }
    else if (p < 0) p = i
  }
  if (p >= 0) arr.length = p
  return arr
}

let a = [1, 2, 3, undefined, undefined, 4, 5, undefined, null]
console.log(JSON.stringify(a))
pack(a)
console.log(JSON.stringify(a))

How to use workbook.saveas with automatic Overwrite

I recommend that before executing SaveAs, delete the file it exists.

If Dir("f:ull\path\with\filename.xls") <> "" Then
    Kill "f:ull\path\with\filename.xls"
End If

It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

fig.add_subplot(ROW,COLUMN,POSITION)

  • ROW=number of rows
  • COLUMN=number of columns
  • POSITION= position of the graph you are plotting

Examples

`fig.add_subplot(111)` #There is only one subplot or graph  
`fig.add_subplot(211)`  *and*  `fig.add_subplot(212)` 

There are total 2 rows,1 column therefore 2 subgraphs can be plotted. Its location is 1st. There are total 2 rows,1 column therefore 2 subgraphs can be plotted.Its location is 2nd

Adding external library in Android studio

SIMPLE STEPS TO ADD ANY LIBRARY IN ANDROID STUDIO:

  1. Copy the file in question from any folder in your computer (eg. C:/documents/xyz.jar"), then go to Android Studio and right-click the Project Library folder and select paste.

  2. Now, right click on the newly added Library file and select the option "add as Library"

D.O.N.E

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

Find something in column A then show the value of B for that row in Excel 2010

I figured out such data design:

Main sheet: Column A: Pump codes (numbers)

Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'

=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)

Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.

Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B

=INDIRECT("Ruhrpumpen!A"&$B2)

Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:

=INDIRECT("Ruhrpumpen!B"&$B2)

Sheet 'Ruhrpumpen':

Column A: some data about a certain pump

Column B: some more data

Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.

Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

Radio/checkbox alignment in HTML/CSS

The following code should work :)

Regards,



<style type="text/css">
input[type=checkbox] {
    margin-bottom: 4px;
    vertical-align: middle;
}

label {
    vertical-align: middle;
}
</style>


<input id="checkBox1" type="checkbox" /><label for="checkBox1">Show assets</label><br />
<input id="checkBox2" type="checkbox" /><label for="checkBox2">Show detectors</label><br />

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

How to delete empty folders using windows command prompt?

You can use the ROBOCOPY command. It is very simple and can also be used to delete empty folders inside large hierarchy.

ROBOCOPY folder1 folder1 /S /MOVE

Here both source and destination are folder1, as you only need to delete empty folders, instead of moving other(required) files to different folder. /S option is to skip copying(moving - in the above case) empty folders. It is also faster as the files are moved inside the same drive.

How to set HTML5 required attribute in Javascript?

required is a reflected property (like id, name, type, and such), so:

element.required = true;

...where element is the actual input DOM element, e.g.:

document.getElementById("edName").required = true;

(Just for completeness.)

Re:

Then the attribute's value is not the empty string, nor the canonical name of the attribute:

edName.attributes.required = [object Attr]

That's because required in that code is an attribute object, not a string; attributes is a NamedNodeMap whose values are Attr objects. To get the value of one of them, you'd look at its value property. But for a boolean attribute, the value isn't relevant; the attribute is either present in the map (true) or not present (false).

So if required weren't reflected, you'd set it by adding the attribute:

element.setAttribute("required", "");

...which is the equivalent of element.required = true. You'd clear it by removing it entirely:

element.removeAttribute("required");

...which is the equivalent of element.required = false.

But we don't have to do that with required, since it's reflected.

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

What is an idiomatic way of representing enums in Go?

Quoting from the language specs:Iota

Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. It is reset to 0 whenever the reserved word const appears in the source and increments after each ConstSpec. It can be used to construct a set of related constants:

const (  // iota is reset to 0
        c0 = iota  // c0 == 0
        c1 = iota  // c1 == 1
        c2 = iota  // c2 == 2
)

const (
        a = 1 << iota  // a == 1 (iota has been reset)
        b = 1 << iota  // b == 2
        c = 1 << iota  // c == 4
)

const (
        u         = iota * 42  // u == 0     (untyped integer constant)
        v float64 = iota * 42  // v == 42.0  (float64 constant)
        w         = iota * 42  // w == 84    (untyped integer constant)
)

const x = iota  // x == 0 (iota has been reset)
const y = iota  // y == 0 (iota has been reset)

Within an ExpressionList, the value of each iota is the same because it is only incremented after each ConstSpec:

const (
        bit0, mask0 = 1 << iota, 1<<iota - 1  // bit0 == 1, mask0 == 0
        bit1, mask1                           // bit1 == 2, mask1 == 1
        _, _                                  // skips iota == 2
        bit3, mask3                           // bit3 == 8, mask3 == 7
)

This last example exploits the implicit repetition of the last non-empty expression list.


So your code might be like

const (
        A = iota
        C
        T
        G
)

or

type Base int

const (
        A Base = iota
        C
        T
        G
)

if you want bases to be a separate type from int.

How to implement class constants?

TypeScript 2.0 has the readonly modifier:

class MyClass {
    readonly myReadOnlyProperty = 1;

    myMethod() {
        console.log(this.myReadOnlyProperty);
        this.myReadOnlyProperty = 5; // error, readonly
    }
}

new MyClass().myReadOnlyProperty = 5; // error, readonly

It's not exactly a constant because it allows assignment in the constructor, but that's most likely not a big deal.

Alternative Solution

An alternative is to use the static keyword with readonly:

class MyClass {
    static readonly myReadOnlyProperty = 1;

    constructor() {
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }

    myMethod() {
        console.log(MyClass.myReadOnlyProperty);
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }
}

MyClass.myReadOnlyProperty = 5; // error, readonly

This has the benefit of not being assignable in the constructor and only existing in one place.

Python: Random numbers into a list

Here I use the sample method to generate 10 random numbers between 0 and 100.

Note: I'm using Python 3's range function (not xrange).

import random

print(random.sample(range(0, 100), 10))

The output is placed into a list:

[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]

Clearing NSUserDefaults

I found this:

osascript -e 'tell application "iOS Simulator" to quit'
xcrun simctl list devices | grep -v '^[-=]' | cut -d "(" -f2 | cut -d ")" -f1 | xargs -I {} xcrun simctl erase "{}"

Source: https://gist.github.com/ZevEisenberg/5a172662cb576872d1ab

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:

public Integer getId() { return id; }    
public void setId(Integer i){ id= i; }

What does "ulimit -s unlimited" do?

ulimit -s unlimited lets the stack grow unlimited.

This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.

How do you scroll up/down on the console of a Linux VM

For some commands, such as mtr + (plus) and - (minus) work to scroll up and down.

Trim last character from a string

If you want to remove the '!' character from a specific expression("world" in your case), then you can use this regular expression

string input = "Hello! world!";

string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);

// result: "Hello! world"

the $1 special character contains all the matching "world" expressions, and it is used to replace the original "world!" expression

Docker: Multiple Dockerfiles in project

Use docker-compose and multiple Dockerfile in separate directories

Don't rename your Dockerfile to Dockerfile.db or Dockerfile.web, it may not be supported by your IDE and you will lose syntax highlighting.

As Kingsley Uchnor said, you can have multiple Dockerfile, one per directory, which represent something you want to build.

I like to have a docker folder which holds each applications and their configuration. Here's an example project folder hierarchy for a web application that has a database.

docker-compose.yml
docker
+-- web
¦   +-- Dockerfile
+-- db
    +-- Dockerfile

docker-compose.yml example:

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: ./docker/web
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  db:
    # will build ./docker/db/Dockerfile
    build: ./docker/db
    ports:
      - "3306:3306"
  redis:
    # will use docker hub's redis prebuilt image from here:
    # https://hub.docker.com/_/redis/
    image: "redis:alpine"

docker-compose command line usage example:

# The following command will create and start all containers in the background
# using docker-compose.yml from current directory
docker-compose up -d

# get help
docker-compose --help

In case you need files from previous folders when building your Dockerfile

You can still use the above solution and place your Dockerfile in a directory such as docker/web/Dockerfile, all you need is to set the build context in your docker-compose.yml like this:

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    ports:
     - "5000:5000"
    volumes:
     - .:/code

This way, you'll be able to have things like this:

config-on-root.ini
docker-compose.yml
docker
+-- web
    +-- Dockerfile
    +-- some-other-config.ini

and a ./docker/web/Dockerfile like this:

FROM alpine:latest

COPY config-on-root.ini /
COPY docker/web/some-other-config.ini /

Here are some quick commands from tldr docker-compose. Make sure you refer to official documentation for more details.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Docker: How to use bash with an Alpine based docker image?

RUN /bin/sh -c "apk add --no-cache bash"

worked for me.

Mongoose query where value is not null

You should be able to do this like (as you're using the query api):

Entrant.where("pincode").ne(null)

... which will result in a mongo query resembling:

entrants.find({ pincode: { $ne: null } })

A few links that might help:

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

ADB Shell Input Events

To send a reload call to a React-Native app running in a android device: adb shell input keyboard text "rr"

How to use executables from a package installed locally in node_modules?

update: If you're on the recent npm (version >5.2)

You can use:

npx <command>

npx looks for command in .bin directory of your node_modules

old answer:

For Windows

Store the following in a file called npm-exec.bat and add it to your %PATH%

@echo off
set cmd="npm bin"
FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET modules=%%i
"%modules%"\%*

Usage

Then you can use it like npm-exec <command> <arg0> <arg1> ...

For example

To execute wdio installed in local node_modules directory, do:

npm-exec wdio wdio.conf.js

i.e. it will run .\node_modules\.bin\wdio wdio.conf.js

Run JavaScript when an element loses focus

onblur is the opposite of onfocus.

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

Get data type of field in select statement in ORACLE

I found a not-very-intuitive way to do this by using DUMP()

SELECT DUMP(A.NAME), 
       DUMP(A.surname), 
       DUMP(B.ordernum) 
FROM   customer A 
       JOIN orders B 
         ON A.id = B.id

It will return something like:

'Typ=1 Len=2: 0,48' for each column.

Type=1 means VARCHAR2/NVARCHAR2
Type=2 means NUMBER/FLOAT
Type=12 means DATE, etc.

You can refer to this oracle doc for information Datatype Code
or this for a simple mapping Oracle Type Code Mappings

If isset $_POST

Add the following attribute to the input text form: required="required". If the form is not filled, it will not allow the user to submit the form.

Your new code will be:

<form name="new user" method="post" action="step2_check.php"> 
<input type="text" name="mail" required="required"/> <br />
<input type="password" name="password" required="required"/><br />
<input type="submit"  value="continue"/>
if (isset($_POST["mail"])) {
    echo "Yes, mail is set";    
}

How to configure CORS in a Spring Boot + Spring Security application?

After much searching for the error coming from javascript CORS, the only elegant solution I found for this case was configuring the cors of Spring's own class org.springframework.web.cors.CorsConfiguration.CorsConfiguration()

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
    }

How do I access my SSH public key?

If you only have your private key available, you can generate the public key from it:

ssh-keygen -y

or

ssh-keygen -y -f path/to/private_key

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

How can I make my match non greedy in vim?

What's wrong with

%s/style="[^"]*"//g

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Answers so far did not adress the problem of sharing code with other people who don't necessarily use Eclipse. Here is one proposition. The key is to use a maven profile to solve the Eclipse Case.

It assumes you have defined a property junit5.version in your pom like:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit5.version>5.1.1</junit5.version>
</properties>

then in the profiles section add the following:

<profiles>
    <profile>
        <id>eclipse</id>
        <dependencies>
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-engine</artifactId>
            </dependency>
            <dependency>
                <groupId>org.junit.platform</groupId>
                <artifactId>junit-platform-launcher</artifactId>
            </dependency>
        </dependencies>
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>${junit5.version}</version>
                    <scope>test</scope>
                </dependency>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-launcher</artifactId>
                    <version>1.1.1</version>
                    <scope>test</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    </profile>
</profiles>

All you have to do after this is to select the profile in your local Eclipse: Right click on your project and select Maven > Select Maven Profiles... (or hit Ctrl + Alt + P), and then check the "eclipse" profile we just created.

Selection Of Maven Profile

With that you are done. Your Eclipse will run Junit 5 tests as expected, but the configuration you added won't pollute other builds or other IDE

Best way to load module/class from lib folder in Rails 3?

# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Source: Rails 3 Quicktip: Autoload lib directory including all subdirectories, avoid lazy loading

Please mind that files contained in the lib folder are only loaded when the server is started. If you want the comfort to autoreload those files, read: Rails 3 Quicktip: Auto reload lib folders in development mode. Be aware that this is not meant for a production environment since the permanent reload slows down the machine.

Is there a REAL performance difference between INT and VARCHAR primary keys?

As for Primary Key, whatever physically makes a row unique should be determined as the primary key.

For a reference as a foreign key, using an auto incrementing integer as a surrogate is a nice idea for two main reasons.
- First, there's less overhead incurred in the join usually.
- Second, if you need to update the table that contains the unique varchar then the update has to cascade down to all the child tables and update all of them as well as the indexes, whereas with the int surrogate, it only has to update the master table and it's indexes.

The drawaback to using the surrogate is that you could possibly allow changing of the meaning of the surrogate:

ex.
id value
1 A
2 B
3 C

Update 3 to D
id value
1 A
2 B
3 D

Update 2 to C
id value
1 A
2 C
3 D

Update 3 to B
id value
1 A
2 C
3 B

It all depends on what you really need to worry about in your structure and what means most.

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

How to retrieve images from MySQL database and display in an html tag

Technically, you can too put image data in an img tag, using data URIs.

<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />

There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.

How to find a value in an array and remove it by using PHP array functions?

You need to find the key of the array first, this can be done using array_search()

Once done, use the unset()

<?php
$array = array( 'apple', 'orange', 'pear' );

unset( $array[array_search( 'orange', $array )] );
?>

How to git ignore subfolders / subdirectories?

To exclude content and subdirectories:

**/bin/*

To just exclude all subdirectories but take the content, add "/":

**/bin/*/

When do you use POST and when do you use GET?

I use POST when I don't want people to see the QueryString or when the QueryString gets large. Also, POST is needed for file uploads.

I don't see a problem using GET though, I use it for simple things where it makes sense to keep things on the QueryString.

Using GET will allow linking to a particular page possible too where POST would not work.

Python send POST with header

If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers parameter.

Here is an example with a non-empty body and headers:

import requests
import json

url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(body), headers=headers)

Source

How do I remove an item from a stl vector with a certain value?

If you have an unsorted vector, then you can simply swap with the last vector element then resize().

With an ordered container, you'll be best off with ?std::vector::erase(). Note that there is a std::remove() defined in <algorithm>, but that doesn't actually do the erasing. (Read the documentation carefully).

Getting an attribute value in xml element

I think I got it. I have to use org.w3c.dom.Element explicitly. I had a different Element field too.

How to mount the android img file under linux?

Another option would be to use the File Explorer in DDMS (Eclipse SDK), you can see the whole file system there and download/upload files to the desired place. That way you don't have to mount and deal with images. Just remember to set your device as USB debuggable (from Developer Tools)

How to find sum of several integers input by user using do/while, While statement or For statement

The FOR loop worked well, I modified it a tiny bit:

#include<iostream>
using namespace std;
int main ()
{

    int sum = 0;
    int number;
    int numberitems;


    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
    {
        cout << "Enter number: \n";
        cin >> number; 

        sum=sum+number;

    }
    cout<<"sum is: "<< sum<<endl;
}

HOWEVER, the WHILE loop has got some errors on line 11 (Count was not declared in this scope). What could be the issue? Also, if you would have a solution using DO,WHILE loop it would be wonderful. Thanks

PostgreSQL IF statement

You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

How can I truncate a string to the first 20 words in PHP?

Split the string (into an array) by <space>, and then take the first 20 elements of that array.

How do you perform a left outer join using linq extension methods

Whilst the accepted answer works and is good for Linq to Objects it bugged me that the SQL query isn't just a straight Left Outer Join.

The following code relies on the LinkKit Project that allows you to pass expressions and invoke them to your query.

static IQueryable<TResult> LeftOuterJoin<TSource,TInner, TKey, TResult>(
     this IQueryable<TSource> source, 
     IQueryable<TInner> inner, 
     Expression<Func<TSource,TKey>> sourceKey, 
     Expression<Func<TInner,TKey>> innerKey, 
     Expression<Func<TSource, TInner, TResult>> result
    ) {
    return from a in source.AsExpandable()
            join b in inner on sourceKey.Invoke(a) equals innerKey.Invoke(b) into c
            from d in c.DefaultIfEmpty()
            select result.Invoke(a,d);
}

It can be used as follows

Table1.LeftOuterJoin(Table2, x => x.Key1, x => x.Key2, (x,y) => new { x,y});

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

Remove a cookie

Most of you are forgetting that this will only work on a local machine. On a domain you will need a pattern like this example.

setcookie("example_cookie", 'password', time()-3600, "/", $_SERVER['SERVER_NAME']);

How can I initialize an ArrayList with all zeroes in Java?

It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.

How to do error logging in CodeIgniter (PHP)

CodeIgniter has some error logging functions built in.

  • Make your /application/logs folder writable
  • In /application/config/config.php set
    $config['log_threshold'] = 1;
    or use a higher number, depending on how much detail you want in your logs
  • Use log_message('error', 'Some variable did not contain a value.');
  • To send an email you need to extend the core CI_Exceptions class method log_exceptions(). You can do this yourself or use this. More info on extending the core here

See http://www.codeigniter.com/user_guide/general/errors.html

Create a dropdown component

This is the code to create dropdown in Angular 7, 8, 9

.html file code

<div>
<label>Summary: </label>
<select (change)="SelectItem($event.target.value)" class="select">
  <option value="0">--All--</option>
  <option *ngFor="let item of items" value="{{item.Id.Value}}">
    {{item.Name}}
  </option>
</select>
</div>

.ts file code

SelectItem(filterVal: any)
{
    var id=filterVal;
    //code
}

items is an array which should be initialized in .ts file.

Checking session if empty or not

if (HttpContext.Current.Session["emp_num"] != null)
{
     // code if session is not null
}
  • if at all above fails.

How to make "if not true condition"?

try

if ! grep -q sysa /etc/passwd ; then

grep returns true if it finds the search target, and false if it doesn't.

So NOT false == true.

if evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).

Also, looking at your code as is, your use of the $( ... ) form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa") to see what I mean. You can take that further by using the -c (count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then which works but is rather old school.

BUT, you could use the newest shell features (arithmetic evaluation) like

if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`

which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,% and maybe a few others.

In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like

if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....

OR

if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....

Finally, there is an award called the Useless Use of Cat (UUOC). :-) Some people will jump up and down and cry gothca! I'll just say that grep can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)

I hope this helps.

Undefined index error PHP

this error occurred sometime method attribute ( valid passing method ) Error option : method="get" but called by $Fname = $_POST["name"]; or

       method="post" but  called by  $Fname = $_GET["name"];

More info visit http://www.doordie.co.in/index.php

Get the current time in C

You can use this function to get current local time. if you want gmt then use the gmtime function instead of localtime. cheers

time_t my_time;
struct tm * timeinfo; 
time (&my_time);
timeinfo = localtime (&my_time);
CCLog("year->%d",timeinfo->tm_year+1900);
CCLog("month->%d",timeinfo->tm_mon+1);
CCLog("date->%d",timeinfo->tm_mday);
CCLog("hour->%d",timeinfo->tm_hour);
CCLog("minutes->%d",timeinfo->tm_min);
CCLog("seconds->%d",timeinfo->tm_sec);

How to make space between LinearLayout children?

Use LinearLayout.LayoutParams instead of MarginLayoutParams. Here's the documentation.

jQuery select element in parent window

why not both to be sure?

if(opener.document){
  $("#testdiv",opener.document).doStuff();
}else{
  $("#testdiv",window.opener).doStuff();
}

Under what conditions is a JSESSIONID created?

CORRECTION: Please vote for Peter Štibraný's answer - it is more correct and complete!

A "JSESSIONID" is the unique id of the http session - see the javadoc here. There, you'll find the following sentence

Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.

So when you first hit a site, a new session is created and bound to the SevletContext. If you deploy multiple applications, the session is not shared.

You can also invalidate the current session and therefore create a new one. e.g. when switching from http to https (after login), it is a very good idea, to create a new session.

Hope, this answers your question.

Build error: "The process cannot access the file because it is being used by another process"

What we have discovered here, is the following: In the project properties page, Debug tab, uncheck the "Enable visual studio hosting process". I am unsure what this property is for, but it does the work once unchecked.

What does the symbol \0 mean in a string-literal?

sizeof str is 7 - five bytes for the "Hello" text, plus the explicit NUL terminator, plus the implicit NUL terminator.

strlen(str) is 5 - the five "Hello" bytes only.

The key here is that the implicit nul terminator is always added - even if the string literal just happens to end with \0. Of course, strlen just stops at the first \0 - it can't tell the difference.

There is one exception to the implicit NUL terminator rule - if you explicitly specify the array size, the string will be truncated to fit:

char str[6] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 6 (with one NUL)
char str[7] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 7 (with two NULs)
char str[8] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 8 (with three NULs per C99 6.7.8.21)

This is, however, rarely useful, and prone to miscalculating the string length and ending up with an unterminated string. It is also forbidden in C++.

How can I restore the MySQL root user’s full privileges?

If you are using WAMP on you local computer (mysql version 5.7.14) Step 1: open my.ini file Step 2: un-comment this line 'skip-grant-tables' by removing the semi-colon step 3: restart mysql server step 4: launch mySQL console step 5:

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;

Step 6: Problem solved!!!!

CSS content property: is it possible to insert HTML instead of Text?

In CSS3 paged media this is possible using position: running() and content: element().

Example from the CSS Generated Content for Paged Media Module draft:

@top-center {
  content: element(heading); 
}

.runner { 
  position: running(heading);
}

.runner can be any element and heading is an arbitrary name for the slot.

EDIT: to clarify, there is basically no browser support so this was mostly meant to be for future reference/in addition to the 'practical answers' given already.

How to keep :active css style after clicking an element

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<label for="activate-div">
  <div class="my-div">
    //MY DIV CONTENT
  </div>
</label>
_x000D_
_x000D_
_x000D_

To make button change content:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<div class="my-div">
  //MY DIV CONTENT
</div>

<label for="activate-div">
  //MY BUTTON STUFF
</label>
_x000D_
_x000D_
_x000D_

Hope it helps!!

Convert array of strings into a string in Java

With control over the delimiter (Java 8+):

String str = String.join(",", arr);

...or <8:

StringBuilder builder = new StringBuilder();
for(String s : arr) {
    builder.append(s);
}
String str = builder.toString();

Alternatively, if you just want a "debug-style" dump of an array:

String str = Arrays.toString(arr);

And if you're coming from the Android angle:

String str = TextUtils.join(",", arr);

You can modify the above depending on what characters, if any, you want in between strings.

You may see near identical code to the pre-Java 8 code but using StringBuffer - StringBuilder is a newer class that's not thread-safe, but therefore has better performance in a single thread because it does away with unneeded synchronization. In short, you're better using StringBuilder in 99% of cases - functionality wise, the two are identical.

DON'T use a string and just append to it with += like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.

Python dictionary replace values

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0t01 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}

How to get first element in a list of tuples?

Use the zip function to decouple elements:

>>> inpt = [(1, u'abc'), (2, u'def')]
>>> unzipped = zip(*inpt)
>>> print unzipped
[(1, 2), (u'abc', u'def')]
>>> print list(unzipped[0])
[1, 2]

Edit (@BradSolomon): The above works for Python 2.x, where zip returns a list.

In Python 3.x, zip returns an iterator and the following is equivalent to the above:

>>> print(list(list(zip(*inpt))[0]))
[1, 2]

creating a table in ionic

the issue of too long content @beenotung can be resolved by this css class :

.col{
  max-width :20% !important;
}

example fork from @jpoveda

What's the difference between Invoke() and BeginInvoke()

Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.

In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).

In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.

Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.

How to increase the distance between table columns in HTML?

If you need to give a distance between two rows use this tag

margin-top: 10px !important;

Java JTable getting the data of the selected row

You can use the following code to get the value of the first column of the selected row of your table.

int column = 0;
int row = table.getSelectedRow();
String value = table.getModel().getValueAt(row, column).toString();

Why does viewWillAppear not get called when an app comes back from the background?

Swift

Short answer

Use a NotificationCenter observer rather than viewWillAppear.

override func viewDidLoad() {
    super.viewDidLoad()

    // set observer for UIApplication.willEnterForegroundNotification
    NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

}

// my selector that was defined above
@objc func willEnterForeground() {
    // do stuff
}

Long answer

To find out when an app comes back from the background, use a NotificationCenter observer rather than viewWillAppear. Here is a sample project that shows which events happen when. (This is an adaptation of this Objective-C answer.)

import UIKit
class ViewController: UIViewController {

    // MARK: - Overrides

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view did load")

        // add notification observers
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

    }

    override func viewWillAppear(_ animated: Bool) {
        print("view will appear")
    }

    override func viewDidAppear(_ animated: Bool) {
        print("view did appear")
    }

    // MARK: - Notification oberserver methods

    @objc func didBecomeActive() {
        print("did become active")
    }

    @objc func willEnterForeground() {
        print("will enter foreground")
    }

}

On first starting the app, the output order is:

view did load
view will appear
did become active
view did appear

After pushing the home button and then bringing the app back to the foreground, the output order is:

will enter foreground
did become active 

So if you were originally trying to use viewWillAppear then UIApplication.willEnterForegroundNotification is probably what you want.

Note

As of iOS 9 and later, you don't need to remove the observer. The documentation states:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

How to call a Python function from Node.js

The python-shell module by extrabacon is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling.

Installation: npm install python-shell.

Running a simple Python script:

var PythonShell = require('python-shell');

PythonShell.run('my_script.py', function (err) {
  if (err) throw err;
  console.log('finished');
});

Running a Python script with arguments and options:

var PythonShell = require('python-shell');

var options = {
  mode: 'text',
  pythonPath: 'path/to/python',
  pythonOptions: ['-u'],
  scriptPath: 'path/to/my/scripts',
  args: ['value1', 'value2', 'value3']
};

PythonShell.run('my_script.py', options, function (err, results) {
  if (err) 
    throw err;
  // Results is an array consisting of messages collected during execution
  console.log('results: %j', results);
});

For the full documentation and source code, check out https://github.com/extrabacon/python-shell

How do I find a particular value in an array and return its index?

We here use simply linear search. At first initialize the index equal to -1 . Then search the array , if found the assign the index value in index variable and break. Otherwise, index = -1.

   int find(int arr[], int n, int key)
   {
     int index = -1;

       for(int i=0; i<n; i++)
       {
          if(arr[i]==key)
          {
            index=i;
            break;
          }
       }
      return index;
    }


 int main()
 {
    int arr[ 5 ] = { 4, 1, 3, 2, 6 };
    int n =  sizeof(arr)/sizeof(arr[0]);
    int x = find(arr ,n, 3);
    cout<<x<<endl;
    return 0;
 }

View/edit ID3 data for MP3 files

Thirding TagLib Sharp.

TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";
f.Save();

How do you push just a single Git branch (and no other branches)?

So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.

To push the contents of foo to origin/master, you first need to set its upstream:

git checkout foo
git branch -u origin/master

Then you can push to this branch using:

git push origin HEAD:master

In the last command you can add --force to replace the entire history of origin/master with that of foo.

ng-repeat :filter by single field

You can filter by an object with a property matching the objects you have to filter on it:

app.controller('FooCtrl', function($scope) {
   $scope.products = [
       { id: 1, name: 'test', color: 'red' },
       { id: 2, name: 'bob', color: 'blue' }
       /*... etc... */
   ];
});
<div ng-repeat="product in products | filter: { color: 'red' }"> 

This can of course be passed in by variable, as Mark Rajcok suggested.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I wrote this method to handle UTF8 arrays and JSON problems. It works fine with array (simple and multidimensional).

/**
 * Encode array from latin1 to utf8 recursively
 * @param $dat
 * @return array|string
 */
   public static function convert_from_latin1_to_utf8_recursively($dat)
   {
      if (is_string($dat)) {
         return utf8_encode($dat);
      } elseif (is_array($dat)) {
         $ret = [];
         foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);

         return $ret;
      } elseif (is_object($dat)) {
         foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);

         return $dat;
      } else {
         return $dat;
      }
   }
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);

What is cardinality in Databases?

It depends a bit on context. Cardinality means the number of something but it gets used in a variety of contexts.

  • When you're building a data model, cardinality often refers to the number of rows in table A that relate to table B. That is, are there 1 row in B for every row in A (1:1), are there N rows in B for every row in A (1:N), are there M rows in B for every N rows in A (N:M), etc.
  • When you are looking at things like whether it would be more efficient to use a b*-tree index or a bitmap index or how selective a predicate is, cardinality refers to the number of distinct values in a particular column. If you have a PERSON table, for example, GENDER is likely to be a very low cardinality column (there are probably only two values in GENDER) while PERSON_ID is likely to be a very high cardinality column (every row will have a different value).
  • When you are looking at query plans, cardinality refers to the number of rows that are expected to be returned from a particular operation.

There are probably other situations where people talk about cardinality using a different context and mean something else.

Simple way to transpose columns and rows in SQL?

Adding to @Paco Zarate's terrific answer above, if you want to transpose a table which has multiple types of columns, then add this to the end of line 39, so it only transposes int columns:

and C.system_type_id = 56   --56 = type int

Here is the full query that is being changed:

select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id(@tableToPivot) and
      C.name <> @columnToPivot and C.system_type_id = 56    --56 = type int
for xml path('')), 1, 1, '')

To find other system_type_id's, run this:

select name, system_type_id from sys.types order by name

md-table - How to update the column width

You can set the .mat-cell class to flex: 0 0 200px; instead of flex: 1 along with the nth-child.

.mat-cell:nth-child(2), .mat-header-cell:nth-child(2) {
    flex: 0 0 200px;
}

Run CRON job everyday at specific time

From cron manual http://man7.org/linux/man-pages/man5/crontab.5.html:

Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: "1,2,5,9", "0-4,8-12".

So in this case it would be:

30 10,14 * * *

swift How to remove optional String Character

Although we might have different contexts, the below worked for me.

I wrapped every part of my variable in brackets and then added an exclamation mark outside the right closing bracket.

For example, print(documentData["mileage"]) is changed to:

print((documentData["mileage"])!)

ERROR 1064 (42000): You have an error in your SQL syntax;

It is varchar and not var_char

CREATE DATABASE IF NOT EXISTS courses;

USE courses;

CREATE TABLE IF NOT EXISTS teachers(
    id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    addr VARCHAR(255) NOT NULL,
    phone INT NOT NULL
);

You should use a SQL tool to visualize possbile errors like MySQL Workbench.

android.content.res.Resources$NotFoundException: String resource ID #0x0

You can do it. this is a easy way.

txtTopicNo.setText(10+"");

Sum columns with null values in oracle

NVL(value, default) is the function you are looking for.

select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0) ) as total_hours
from hours_t
group by type, craft
order by type, craft

Oracle have 5 NULL-related functions:

  1. NVL
  2. NVL2
  3. COALESCE
  4. NULLIF
  5. LNNVL

NVL:

NVL(expr1, expr2)

NVL lets you replace null (returned as a blank) with a string in the results of a query. If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.

NVL2 :

NVL2(expr1, expr2, expr3)

NVL2 lets you determine the value returned by a query based on whether a specified expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1 is null, then NVL2 returns expr3.

COALESCE

COALESCE(expr1, expr2, ...)

COALESCE returns the first non-null expr in the expression list. At least one expr must not be the literal NULL. If all occurrences of expr evaluate to null, then the function returns null.

NULLIF

NULLIF(expr1, expr2)

NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.

LNNVL

LNNVL(condition)

LNNVL provides a concise way to evaluate a condition when one or both operands of the condition may be null.

More info on Oracle SQL Functions

Difference between git pull and git pull --rebase

For this is important to understand the difference between Merge and Rebase.

Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards.

For details refer - http://www.derekgourlay.com/archives/428

Setting a div's height in HTML with CSS

A 2 column layout is a little bit tough to get working in CSS (at least until CSS3 is practical.)

Floating left and right will work to a point, but it won't allow you to extend the background. To make backgrounds stay solid, you'll have to implement a technique known as "faux columns," which basically means your columns themselves won't have a background image. Your 2 columns will be contained inside of a parent tag. This parent tag is given a background image that contains the 2 column colors you want. Make this background only as big as you need it to (if it is a solid color, only make it 1 pixel high) and have it repeat-y. AListApart has a great walkthrough on what is needed to make it work.

http://www.alistapart.com/articles/fauxcolumns/

Effective way to find any file's Encoding

I'd try the following steps:

1) Check if there is a Byte Order Mark

2) Check if the file is valid UTF8

3) Use the local "ANSI" codepage (ANSI as Microsoft defines it)

Step 2 works because most non ASCII sequences in codepages other that UTF8 are not valid UTF8.

How to call loading function with React useEffect only once

leave the dependency array blank . hope this will help you understand better.

   useEffect(() => {
      doSomething()
    }, []) 

empty dependency array runs Only Once, on Mount

useEffect(() => {
  doSomething(value)
}, [value])  

pass value as a dependency. if dependencies has changed since the last time, the effect will run again.

useEffect(() => {
  doSomething(value)
})  

no dependency. This gets called after every render.

How to remove specific value from array using jQuery

First checks if element exists in the array

$.inArray(id, releaseArray) > -1

above line returns the index of that element if it exists in the array, otherwise it returns -1

 releaseArray.splice($.inArray(id, releaseArray), 1);

now above line will remove this element from the array if found. To sum up the logic below is the required code to check and remove the element from array.

  if ($.inArray(id, releaseArray) > -1) {
                releaseArray.splice($.inArray(id, releaseArray), 1);
            }
            else {
                releaseArray.push(id);
            }

String concatenation in Jinja

My bad, in trying to simplify it, I went too far, actually stuffs is a record of all kinds of info, I just want the id in it.

stuffs = [[123, first, last], [456, first, last]]

I want my_sting to be

my_sting = '123, 456'

My original code should have looked like this:

{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}

Thinking about it, stuffs is probably a dictionary, but you get the gist.

Yes I found the join filter, and was going to approach it like this:

 {% set my_string = [] %}
 {% for stuff in stuffs %}
 {% do my_string.append(stuff.id) %}
 {% endfor%}
 {%  my_string|join(', ') %}

But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.

How to log cron jobs?

Incase you're running some command with sudo, it won't allow it. Sudo needs a tty.

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Python dict how to create key or append an element to key?

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

Bootstrap: add margin/padding space between columns

Try this:

<div class="row">
      <div class="col-md-5">
         Set room heater temperature
     </div>
     <div class="col-md-2"></div>
     <div class="col-md-5">
         Set room heater temperature
     </div>
</div>

How to use XPath contains() here?

You are only looking at the first li child in the query you have instead of looking for any li child element that may contain the text, 'Model'. What you need is a query like the following:

//ul[@class='featureList' and ./li[contains(.,'Model')]]

This query will give you the elements that have a class of featureList with one or more li children that contain the text, 'Model'.

AppendChild() is not a function javascript

Try the following:

var div = document.createElement("div");
div.innerHTML = "topdiv";
div.appendChild(element);
document.body.appendChild(div);

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Hibernate show real SQL

If you can already see the SQL being printed, that means you have the code below in your hibernate.cfg.xml:

<property name="show_sql">true</property>

To print the bind parameters as well, add the following to your log4j.properties file:

log4j.logger.net.sf.hibernate.type=debug

download file using an ajax request

Your needs are covered by window.location('download.php');
But I think that you need to pass the file to be downloaded, not always download the same file, and that's why you are using a request, one option is to create a php file as simple as showfile.php and do a request like

var myfile = filetodownload.txt
var url = "shofile.php?file=" + myfile ;
ajaxRequest.open("GET", url, true);

showfile.php

<?php
$file = $_GET["file"] 
echo $file;

where file is the file name passed via Get or Post in the request and then catch the response in a function simply

if(ajaxRequest.readyState == 4){
                        var file = ajaxRequest.responseText;
                        window.location = 'downfile.php?file=' + file;  
                    }
                }

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A 

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

Regular expression for matching HH:MM time format

You can use following regex :

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

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

toggle show/hide div with button?

JavaScript - Toggle Element.styleMDN

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
_x000D_
#content{
  display:none;
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

About the ^ bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

JavaScript - Toggle .classList.toggle()

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.classList.toggle("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle

.toggle()Docs; .fadeToggle()Docs; .slideToggle()Docs

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggle();                 // .fadeToggle() // .slideToggle()
});
_x000D_
#content{
  display:none;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle .toggleClass()Docs

.toggle() toggles an element's display "block"/"none" values

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggleClass("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

HTML5 - Toggle using <summary> and <details>

(unsupported on IE and Opera Mini)

_x000D_
_x000D_
<details>
  <summary>TOGGLE</summary>
  <p>Some content...</p>
</details>
_x000D_
_x000D_
_x000D_

HTML - Toggle using checkbox

_x000D_
_x000D_
[id^=toggle],
[id^=toggle] + *{
  display:none;
}
[id^=toggle]:checked + *{
  display:block;
}
_x000D_
<label for="toggle-1">TOGGLE</label>

<input id="toggle-1" type="checkbox">
<div>Some content...</div>
_x000D_
_x000D_
_x000D_

HTML - Switch using radio

_x000D_
_x000D_
[id^=switch],
[id^=switch] + *{
  display:none;
}
[id^=switch]:checked + *{
  display:block;
}
_x000D_
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>

<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>

<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_

CSS - Switch using :target

(just to make sure you have it in your arsenal)

_x000D_
_x000D_
[id^=switch] + *{
  display:none;
}
[id^=switch]:target + *{
  display:block;
}
_x000D_
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>

<i id="switch1"></i>
<div>1 Merol Muspi ...</div>

<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_


Animating class transition

If you pick one of JS / jQuery way to actually toggle a className, you can always add animated transitions to your element, here's a basic example:

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function(){
  content.classList.toggle("appear");
}, false);
_x000D_
#content{
  /* DON'T USE DISPLAY NONE/BLOCK! Instead: */
  background: #cf5;
  padding: 10px;
  position: absolute;
  visibility: hidden;
  opacity: 0;
          transition: 0.6s;
  -webkit-transition: 0.6s;
          transform: translateX(-100%);
  -webkit-transform: translateX(-100%);
}
#content.appear{
  visibility: visible;
  opacity: 1;
          transform: translateX(0);
  -webkit-transform: translateX(0);
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some Togglable content...</div>
_x000D_
_x000D_
_x000D_

Creating a UICollectionView programmatically

Swift 3

class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let flowLayout = UICollectionViewFlowLayout()

        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.cyan

        self.view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor.green
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }

}

Does Index of Array Exist

You could check if the index is less than the length of the array. This doesn't check for nulls or other odd cases where the index can be assigned a value but hasn't been given one explicitly.

How to load a resource bundle from a file resource in Java?

This works for me:

File f = new File("some.properties");
Properties props = new Properties();
FileInputStream fis = null;
try {
    fis = new FileInputStream(f);
    props.load(fis);
} catch (FileNotFoundException e) {
    e.printStackTrace();                    
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
            fis = null;
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
}           

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

How do I upload a file with the JS fetch API?

Jumping off from Alex Montoya's approach for multiple file input elements

const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();

for (const file of inputFiles) {
    formData.append(file.name, file.files[0]);
}

fetch(url, {
    method: 'POST',
    body: formData })

CSS /JS to prevent dragging of ghost image?

You can assign an alternate ghost image if you really need to use drag events and can't set draggable=false. So just assign a blank png like so:

    $('#img').bind({
        dragstart: function(e) {
            var dragIcon = document.createElement('img');
            dragIcon.src = 'blank.png';
            dragIcon.width = 100;
            e.dataTransfer.setDragImage(dragIcon, -10, -10);
        }
    });

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

Where are include files stored - Ubuntu Linux, GCC

The \#include files of gcc are stored in /usr/include . The standard include files of g++ are stored in /usr/include/c++.

Merging two images with PHP

Merger two image png and jpg/png [Image Masking]

//URL or Local path
$src_url = '1.png';
$dest_url = '2.jpg';
$src = imagecreatefrompng($src_url);
$dest1 = imagecreatefromjpeg($dest_url);

//if you want to make same size
list($width, $height) = getimagesize($dest_url);
list($newWidth, $newHeight) = getimagesize($src_url);
$dest = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($dest, $dest1, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

list($src_w, $src_h) = getimagesize($src_url);

//merger with same size
$this->imagecopymerge_alpha($dest, $src, 0, 0, 0, 0, $src_w, $src_h, 100);

//show output on browser
header('Content-Type: image/png');
imagejpeg($dest);

imagecopymerge_alpha

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
    {
        $cut = imagecreatetruecolor($src_w, $src_h);
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

How to manually set an authenticated user in Spring Security / SpringMVC

The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .

To turn on that feature you need:

web.xml

<filter>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter>  
<filter-mapping>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <url-pattern>/<strike>*</strike></url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

RegistrationController

return "forward:/login?j_username=" + registrationModel.getUserEmail()
        + "&j_password=" + registrationModel.getPassword();

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

Which is more efficient, a for-each loop, or an iterator?

The foreach underhood is creating the iterator, calling hasNext() and calling next() to get the value; The issue with the performance comes only if you are using something that implements the RandomomAccess.

for (Iterator<CustomObj> iter = customList.iterator(); iter.hasNext()){
   CustomObj custObj = iter.next();
   ....
}

Performance issues with the iterator-based loop is because it is:

  1. allocating an object even if the list is empty (Iterator<CustomObj> iter = customList.iterator(););
  2. iter.hasNext() during every iteration of the loop there is an invokeInterface virtual call (go through all the classes, then do method table lookup before the jump).
  3. the implementation of the iterator has to do at least 2 fields lookup in order to make hasNext() call figure the value: #1 get current count and #2 get total count
  4. inside the body loop, there is another invokeInterface virtual call iter.next(so: go through all the classes and do method table lookup before the jump) and as well has to do fields lookup: #1 get the index and #2 get the reference to the array to do the offset into it (in every iteration).

A potential optimiziation is to switch to an index iteration with the cached size lookup:

for(int x = 0, size = customList.size(); x < size; x++){
  CustomObj custObj = customList.get(x);
  ...
}

Here we have:

  1. one invokeInterface virtual method call customList.size() on the initial creation of the for loop to get the size
  2. the get method call customList.get(x) during the body for loop, which is a field lookup to the array and then can do the offset into the array

We reduced a ton of method calls, field lookups. This you don't want to do with LinkedList or with something that is not a RandomAccess collection obj, otherwise the customList.get(x) is gonna turn into something that has to traverse the LinkedList on every iteration.

This is perfect when you know that is any RandomAccess based list collection.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);

How can I change IIS Express port for a site

Right click on your MVC Project. Go to Properties. Go to the Web tab.
Change the port number in the Project Url. Example. localhost:50645
Changing the bold number, 50645, to anything else will change the port the site runs under.
Press the Create Virtual Directory button to complete the process.

See also: http://msdn.microsoft.com/en-us/library/ms178109.ASPX

Image shows the web tab of an MVC Project enter image description here

Should MySQL have its timezone set to UTC?

PHP and MySQL have their own default timezone configurations. You should synchronize time between your data base and web application, otherwise you could run some issues.

Read this tutorial: How To Synchronize Your PHP and MySQL Timezones

Convert string to buffer Node

You can do:

var buf = Buffer.from(bufStr, 'utf8');

But this is a bit silly, so another suggestion would be to copy the minimal amount of code out of the called function to allow yourself access to the original buffer. This might be quite easy or fairly difficult depending on the details of that library.

How to decrypt a password from SQL server?

You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.

Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?

How to set a radio button in Android

If you want to do it in code, you can call the check member of RadioGroup:

radioGroup.check(R.id.radioButtonId);

This will check the button you specify and uncheck the others.

How to get the query string by javascript?

There is a new API called URLSearchParams in browsers which allow you to extract and change the values of the query string.

Currently, it seems to be supported in Firefox 44+, Chrome 49+ and Opera 36+.

Initialize/Input

To get started, create a new URLSearchParams object. For current implementations, you need to remove the "?" at the beginning of the query string, using slice(1) on the querystring, as Jake Archibald suggests:

var params = new URLSearchParams(window.location.search.slice(1)); // myParam=12

In later implementations, you should be able to use it without slice:

var params = new URLSearchParams(window.location.search); // myParam=12

Get

You can get params from it via the .get method:

params.get('myParam'); // 12

Set

Params can be changed using .set:

params.set('myParam', 'newValue');

Output

And if the current querystring is needed again, the .toString method provides it:

params.toString(); // myParam=newValue

There are a host of other methods in this API.

Polyfill

As browser support is still pretty thin, there is a small polyfill by Andrea Giammarchi (<3kB).

Java, reading a file from current directory?

Try

System.getProperty("user.dir")

It returns the current working directory.

How to view/delete local storage in Firefox?

To inspect your localStorage items you may type console.log(localStorage); in your javascript console (firebug for example or in new FF versions the shipped js console).

You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:

localStorage.clear();

C++ compiling on Windows and Linux: ifdef switch

It depends on the compiler. If you compile with, say, G++ on Linux and VC++ on Windows, this will do :

#ifdef linux
    ...
#elif _WIN32
    ...
#else
    ...
#endif

Synchronizing a local Git repository with a remote one

You can use git hooks for that. Just create a hook that pushes changed to the other repo after an update.

Of course you might get merge conflicts so you have to figure how to deal with them.

Telling Python to save a .txt file to a certain directory on Windows and Mac

Just use an absolute path when opening the filehandle for writing.

import os.path

save_path = 'C:/example/'

name_of_file = raw_input("What is the name of the file: ")

completeName = os.path.join(save_path, name_of_file+".txt")         

file1 = open(completeName, "w")

toFile = raw_input("Write what you want into the field")

file1.write(toFile)

file1.close()

You could optionally combine this with os.path.abspath() as described in Bryan's answer to automatically get the path of a user's Documents folder. Cheers!

change html input type by JS?

Yes, you can even change it by triggering an event

<input type='text' name='pass'  onclick="(this.type='password')" />


<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">

Creating a mock HttpServletRequest out of a url string?

You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.

In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.

I need an unordered list without any bullets

 <div class="custom-control custom-checkbox left">
    <ul class="list-unstyled">
        <li>
         <label class="btn btn-secondary text-left" style="width:100%;text-align:left;padding:2px;">
           <input type="checkbox" style="zoom:1.7;vertical-align:bottom;" asp-for="@Model[i].IsChecked" class="custom-control-input" /> @Model[i].Title
         </label>
        </li>
     </ul>
</div>

Accessing Object Memory Address

Just in response to Torsten, I wasn't able to call addressof() on a regular python object. Furthermore, id(a) != addressof(a). This is in CPython, don't know about anything else.

>>> from ctypes import c_int, addressof
>>> a = 69
>>> addressof(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid type
>>> b = c_int(69)
>>> addressof(b)
4300673472
>>> id(b)
4300673392

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

In my case I used sudo mkdir projectFolder to create folder. It was owned by root user and I was logged in using non root user.

So I changed the folder permission using command sudo chown mynonrootuser:mynonrootuser projectFolder and then it worked fine.

Comparing double values in C#

You need a combination of Math.Abs on X-Y and a value to compare with.

You can use following Extension method approach

public static class DoubleExtensions
    {
        const double _3 = 0.001;
        const double _4 = 0.0001;
        const double _5 = 0.00001;
        const double _6 = 0.000001;
        const double _7 = 0.0000001;

        public static bool Equals3DigitPrecision(this double left, double right)
        {
            return Math.Abs(left - right) < _3;
        }

        public static bool Equals4DigitPrecision(this double left, double right)
        {
            return Math.Abs(left - right) < _4;
        }

        ...

Since you rarely call methods on double except ToString I believe its pretty safe extension.

Then you can compare x and y like

if(x.Equals4DigitPrecision(y))

Pandas sort by group aggregate and column

Here's a more concise approach...

df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)

The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.

Result:

    A       B           C
5   baz     -2.301539   True
2   baz     -0.528172   False
1   bar     -0.611756   True
4   bar      0.865408   False
3   foo     -1.072969   True
0   foo      1.624345   False

NOTE: sort is deprecated, use sort_values instead

Setting multiple attributes for an element at once with JavaScript

You might be able to use Object.assign(...) to apply your properties to the created element. See comments for additional details.

Keep in mind that height and width attributes are defined in pixels, not percents. You'll have to use CSS to make it fluid.

_x000D_
_x000D_
var elem = document.createElement('img')_x000D_
Object.assign(elem, {_x000D_
  className: 'my-image-class',_x000D_
  src: 'https://dummyimage.com/320x240/ccc/fff.jpg',_x000D_
  height: 120, // pixels_x000D_
  width: 160, // pixels_x000D_
  onclick: function () {_x000D_
    alert('Clicked!')_x000D_
  }_x000D_
})_x000D_
document.body.appendChild(elem)_x000D_
_x000D_
// One-liner:_x000D_
// document.body.appendChild(Object.assign(document.createElement(...), {...}))
_x000D_
.my-image-class {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  border: solid 5px transparent;_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
.my-image-class:hover {_x000D_
  cursor: pointer;_x000D_
  border-color: red_x000D_
}_x000D_
_x000D_
body { margin:0 }
_x000D_
_x000D_
_x000D_

How to read data from java properties file using Spring Boot

You can use @PropertySource to externalize your configuration to a properties file. There is number of way to do get properties:

1. Assign the property values to fields by using @Value with PropertySourcesPlaceholderConfigurer to resolve ${} in @Value:

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Value("${gMapReportUrl}")
    private String gMapReportUrl;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

2. Get the property values by using Environment:

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Autowired
    private Environment env;

    public void foo() {
        env.getProperty("gMapReportUrl");
    }

}

Hope this can help

JQuery - Set Attribute value

You can add different classes to select, or select by type like this:

$('input[type="checkbox"]').removeAttr("disabled");

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Unfortunately it's out of our hands whether the package writer bothers with a declaration file. What I tend to do is have a file such index.d.ts that'll contain all the missing declaration files from various packages:

Index.ts:

declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';

Adding an item to an associative array

before for loop :

$data = array();

then in your loop:

$data[] = array($catagory => $question);

Fetch: reject promise and catch the error if status is not OK?

Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren't network errors, there's nothing to catch. You'll need to throw an error yourself to use Promise#catch.

A fetch Response conveniently supplies an ok , which tells you whether the request succeeded. Something like this should do the trick:

fetch(url).then((response) => {
  if (response.ok) {
    return response.json();
  } else {
    throw new Error('Something went wrong');
  }
})
.then((responseJson) => {
  // Do something with the response
})
.catch((error) => {
  console.log(error)
});

class << self idiom in Ruby

? singleton method is a method that is defined only for a single object.

Example:

class SomeClass
  class << self
    def test
    end
  end
end

test_obj = SomeClass.new

def test_obj.test_2
end

class << test_obj
  def test_3
  end
end

puts "Singleton's methods of SomeClass"
puts SomeClass.singleton_methods
puts '------------------------------------------'
puts "Singleton's methods of test_obj"
puts test_obj.singleton_methods

Singleton's methods of SomeClass

test


Singleton's methods of test_obj

test_2

test_3

IOError: [Errno 13] Permission denied

I had a similar problem. I was attempting to have a file written every time a user visits a website.

The problem ended up being twofold.

1: the permissions were not set correctly

2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)

After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)

Validating an XML against referenced XSD in C#

The following example validates an XML file and generates the appropriate error or warning.

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{

    public static void Main()
    {
        //Load the XmlSchemaSet.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add("urn:bookstore-schema", "books.xsd");

        //Validate the file using the schema stored in the schema set.
        //Any elements belonging to the namespace "urn:cd-schema" generate
        //a warning because there is no schema matching that namespace.
        Validate("store.xml", schemaSet);
        Console.ReadLine();
    }

    private static void Validate(String filename, XmlSchemaSet schemaSet)
    {
        Console.WriteLine();
        Console.WriteLine("\r\nValidating XML file {0}...", filename.ToString());

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            compiledSchema = schema;
        }

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add(compiledSchema);
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
        settings.ValidationType = ValidationType.Schema;

        //Create the schema validating reader.
        XmlReader vreader = XmlReader.Create(filename, settings);

        while (vreader.Read()) { }

        //Close the reader.
        vreader.Close();
    }

    //Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}

The preceding example uses the following input files.

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema" xmlns:cd="urn:cd-schema">
  <book genre="novel">
    <title>The Confidence Man</title>
    <price>11.99</price>
  </book>
  <cd:cd>
    <title>Americana</title>
    <cd:artist>Offspring</cd:artist>
    <price>16.95</price>
  </cd:cd>
</bookstore>

books.xsd

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

Create autoincrement key in Java DB using NetBeans IDE

If you look at this url: http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/

this part of the schema may be what you are looking for.

 ID          INTEGER NOT NULL 
                PRIMARY KEY GENERATED ALWAYS AS IDENTITY 
                (START WITH 1, INCREMENT BY 1),

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I have the same problem since yesterday. Yesterday, I fixed it by creating a new workspace and reimporting the projects. It seemed to work well, but today it started again.

So, today I created the folder and the file manually and gave the full permissions -rwxrwxrwx.

Seems to work again...

Howto? Parameters and LIKE statement SQL

Sometimes the symbol used as a placeholder % is not the same if you execute a query from VB as when you execute it from MS SQL / Access. Try changing your placeholder symbol from % to *. That might work.
However, if you debug and want to copy your SQL string directly in MS SQL or Access to test it, you may have to change the symbol back to % in MS SQL or Access in order to actually return values.

Hope this helps

How can I use mySQL replace() to replace strings in multiple records?

you can write a stored procedure like this:

CREATE PROCEDURE sanitize_TABLE()

BEGIN

#replace space with underscore

UPDATE Table SET FieldName = REPLACE(FieldName," ","_") WHERE FieldName is not NULL;

#delete dot

UPDATE Table SET FieldName = REPLACE(FieldName,".","") WHERE FieldName is not NULL;

#delete (

UPDATE Table SET FieldName = REPLACE(FieldName,"(","") WHERE FieldName is not NULL;

#delete )

UPDATE Table SET FieldName = REPLACE(FieldName,")","") WHERE FieldName is not NULL;

#raplace or delete any char you want

#..........................

END

In this way you have modularized control over table.

You can also generalize stored procedure making it, parametric with table to sanitoze input parameter

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode is a new feature of iOS 9

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.

Note: For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required

So you should disabled bitcode until all the frameworks of your app have bitcode enabled.

ADB Android Device Unauthorized

This solved my issue!

  1. run your android simulator
  2. go to setting and enable developer mode
  3. enable from the developer settings usb debugging

at this point you will get popup massage at you emulator to authorise the device and you are good to go :)

Get device token for push notification

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
        }
    let token = tokenParts.joined()

    print("Token\(token)")
}

Looping over a list in Python

Try this,

x in mylist is better and more readable than x in mylist[:] and your len(x) should be equal to 3.

>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
...      if len(x)==3:
...        print x
...
[1, 2, 3]
[8, 9, 10]

or if you need more pythonic use list-comprehensions

>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>

how to check which version of nltk, scikit learn installed?

You can find NLTK version simply by doing:

In [1]: import nltk

In [2]: nltk.__version__
Out[2]: '3.2.5'

And similarly for scikit-learn,

In [3]: import sklearn

In [4]: sklearn.__version__
Out[4]: '0.19.0'

I'm using python3 here.

System.Drawing.Image to stream C#

Try the following:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

Get top most UIViewController

The best solution for me is an extension with a function. Create a swift file with this extension

First is the UIWindow extension:

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

inside that file add function

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

And if you want to use it, you can call it anywhere. Example:

  override func viewDidLoad() {
    super.viewDidLoad()
      if let topVC = visibleViewController() {
             //show some label or text field 
    }
}

File code is like this:

import UIKit

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

Sorting object property by values

function sortObjByValue(list){
 var sortedObj = {}
 Object.keys(list)
  .map(key => [key, list[key]])
  .sort((a,b) => a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0)
  .forEach(data => sortedObj[data[0]] = data[1]);
 return sortedObj;
}
sortObjByValue(list);

Github Gist Link

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I am using the python package psycopg2 and I got this error while querying. I kept running just the query and then the execute function, but when I reran the connection (shown below), it resolved the issue. So rerun what is above your script i.e the connection, because as someone said above, I think it lost the connection or was out of sync or something.

connection = psycopg2.connect(user = "##",
        password = "##",
        host = "##",
        port = "##",
        database = "##")
cursor = connection.cursor()

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");

The mm is minutes you want MM

CODE

public class Test {

    public static void main(String[] args) throws ParseException {
        java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
                .parse("2012-07-10 14:58:00.000000");
        System.out.println(temp);
    }
}

Prints:

Tue Jul 10 14:58:00 EDT 2012

Find the most popular element in int[] array

  1. Take a map to map element - > count
  2. Iterate through array and process the map
  3. Iterate through map and find out the popular

Where are the python modules stored?

  1. You can iterate through directories listed in sys.path to find all modules (except builtin ones).
  2. It'll probably be somewhere around /usr/lib/pythonX.X/site-packages (again, see sys.path). And consider using native Python package management (via pip or easy_install, plus yolk) instead, packages in Linux distros-maintained repositories tend to be outdated.

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

Spring - download response as a file

You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

ASP.Net 2012 Unobtrusive Validation with jQuery

Other than the required "jquery" ScriptResourceDefinition in Global.asax (use your own paths):

    protected void Application_Start(object sender, EventArgs e)
    {            
        ScriptManager.ScriptResourceMapping.AddDefinition(
            "jquery",
            new ScriptResourceDefinition
            {
                Path = "/static/scripts/jquery-1.8.3.min.js",
                DebugPath = "/static/scripts/jquery-1.8.3.js",
                CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js",
                CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.js",
                CdnSupportsSecureConnection = true,
                LoadSuccessExpression = "jQuery"
            });
    }

You additionally only need to explicitly add "WebUIValidation.js" after "jquery" ScriptReference in ScriptManager (the most important part):

       <asp:ScriptManager runat="server" EnableScriptGlobalization="True" EnableCdn="True">
            <Scripts>
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" />
            </Scripts>
        </asp:ScriptManager>

If you add it before "jquery", or if you don't add any or both of them at all (ASP.Net will then automatically add it before "jquery") - the client validation will be completely broken:

http://connect.microsoft.com/VisualStudio/feedback/details/748064/unobtrusive-validation-breaks-with-a-script-manager-on-the-page

You don't need any of those NuGet packages at all, nor any additional ScriptReference (some of which are just duplicates, or even a completely unnecessary bloat - as they are added automatically by ASP.Net if needed) mentioned in your blog.

EDIT: you don't need to explicitly add "WebForms.js" as well (removed it from the example) - and if you do, its LoadSuccessExpression will be ignored for some reason

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

I ran across this question while troubleshooting my own code.

So this does NOT work...

$myLogText = ""
function AddLog ($Message)
{
    $myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText

This APPEARS to work, but only in the PowerShell ISE:

$myLogText = ""
function AddLog ($Message)
{
    $global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText

This is actually what works in both ISE and command line:

$global:myLogText = ""
function AddLog ($Message)
{
    $global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $global:myLogText

Rename multiple columns by names

Sidenote, if you want to concatenate one string to all of the column names, you can just use this simple code.

colnames(df) <- paste("renamed_",colnames(df),sep="")

How to find a Java Memory Leak

Checkout this screen cast about finding memory leaks with JProfiler. It's visual explanation of @Dima Malenko Answer.

Note: Though JProfiler is not freeware, But Trial version can deal with current situation.

How do I read and parse an XML file in C#?

LINQ to XML Example:

// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");


// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
            where (int)c.Attribute("id") < 4
            select c.Element("firstName").Value + " " +
                   c.Element("lastName").Value;


foreach (string name in query)
{
    Console.WriteLine("Contact's Full Name: {0}", name);
}

Reference: LINQ to XML at MSDN

Convert js Array() to JSon object for use with JQuery .ajax

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1

PHP - Check if the page run on Mobile or Desktop browser

I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:

function isMobileDevice(){
    $aMobileUA = array(
        '/iphone/i' => 'iPhone', 
        '/ipod/i' => 'iPod', 
        '/ipad/i' => 'iPad', 
        '/android/i' => 'Android', 
        '/blackberry/i' => 'BlackBerry', 
        '/webos/i' => 'Mobile'
    );

    //Return true if Mobile User Agent is detected
    foreach($aMobileUA as $sMobileKey => $sMobileOS){
        if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
            return true;
        }
    }
    //Otherwise return false..  
    return false;
}

How to justify a single flexbox item (override justify-content)

AFAIK there is no property for that in the specs, but here is a trick I’ve been using: set the container element ( the one with display:flex ) to justify-content:space-around Then add an extra element between the first and second item and set it to flex-grow:10 (or some other value that works with your setup)

Edit: if the items are tightly aligned it's a good idea to add flex-shrink: 10; to the extra element as well, so the layout will be properly responsive on smaller devices.

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

How do I iterate over the words of a string?

Thank you @Jairo Abdiel Toribio Cisneros. It works for me but your function return some empty element. So for return without empty I have edited with the following:

std::vector<std::string> split(std::string str, const char* delim) {
    std::vector<std::string> v;
    std::string tmp;

    for(std::string::const_iterator i = str.begin(); i <= str.end(); ++i) {
        if(*i != *delim && i != str.end()) {
            tmp += *i;
        } else {
            if (tmp.length() > 0) {
                v.push_back(tmp);
            }
            tmp = "";
        }
    }

    return v;
}

Using:

std::string s = "one:two::three";
std::string delim = ":";
std::vector<std::string> vv = split(s, delim.c_str());

how to pass list as parameter in function

You can pass it as a List<DateTime>

public void somefunction(List<DateTime> dates)
{
}

However, it's better to use the most generic (as in general, base) interface possible, so I would use

public void somefunction(IEnumerable<DateTime> dates)
{
}

or

public void somefunction(ICollection<DateTime> dates)
{
}

You might also want to call .AsReadOnly() before passing the list to the method if you don't want the method to modify the list - add or remove elements.

pass post data with window.location.href

it's as simple as this

$.post({url: "som_page.php", 
    data: { data1: value1, data2: value2 }
    ).done(function( data ) { 
        $( "body" ).html(data);
    });
});

I had to solve this to make a screen lock of my application where I had to pass sensitive data as user and the url where he was working. Then create a function that executes this code

How can I enable the Windows Server Task Scheduler History recording?

I think the confusion is that on my server I had to right click the Task Scheduler Library on left hand side and right click to get the option to enable or disable all tasks history.

Hope this helps

Set The Window Position of an application via command line

If you are happy to run a batch file along with a couple of tiny helper programs, a complete solution is posted here:
How can a batch file run a program and set the position and size of the window? - Stack Overflow (asked: May 1, 2012)

Cloud Firestore collection count

No, there is no built-in support for aggregation queries right now. However there are a few things you could do.

The first is documented here. You can use transactions or cloud functions to maintain aggregate information:

This example shows how to use a function to keep track of the number of ratings in a subcollection, as well as the average rating.

exports.aggregateRatings = firestore
  .document('restaurants/{restId}/ratings/{ratingId}')
  .onWrite(event => {
    // Get value of the newly added rating
    var ratingVal = event.data.get('rating');

    // Get a reference to the restaurant
    var restRef = db.collection('restaurants').document(event.params.restId);

    // Update aggregations in a transaction
    return db.transaction(transaction => {
      return transaction.get(restRef).then(restDoc => {
        // Compute new number of ratings
        var newNumRatings = restDoc.data('numRatings') + 1;

        // Compute new average rating
        var oldRatingTotal = restDoc.data('avgRating') * restDoc.data('numRatings');
        var newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;

        // Update restaurant info
        return transaction.update(restRef, {
          avgRating: newAvgRating,
          numRatings: newNumRatings
        });
      });
    });
});

The solution that jbb mentioned is also useful if you only want to count documents infrequently. Make sure to use the select() statement to avoid downloading all of each document (that's a lot of bandwidth when you only need a count). select() is only available in the server SDKs for now so that solution won't work in a mobile app.

How to swap two variables in JavaScript

In ES6 now there is destructuring assignment and you can do:

let a = 1;
let b = 2;
[b, a] = [a, b]  // a = 2, b = 1

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

An item with the same key has already been added

I had the problem not in my C# model, but in the javascript object I was posting using AJAX. I'm using Angular for binding and had a capitalized Notes field on the page while my C# object was expecting lower-case notes. A more descriptive error would sure be nice.

C#:

class Post {
    public string notes { get; set; }
}

Angular/Javascript:

<input ng-model="post.Notes" type="text">