Programs & Examples On #Cts

Android Comparability Test Suite, a suite of several thousand test cases to be run on an Android device from a host computer to test the OS and to ensure compatibility across Android implementations.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

This works for me

  1. Stop the ng server(ctrl+c)

  2. Run Again

    npm start / ng serve --open
    

SyntaxError: Cannot use import statement outside a module

This error also comes when you run the command

node filename.ts

and not

node filename.js

To simply put, with node command we will have to run the JavaScript file (filename.js) and not the TypeScript file unless we are using a package like ts-node

How to resolve the error on 'react-native start'

[Quick Answer]

There are a problem with Metro using some NPM and Node versions.

You can fix the problem changing some code in the file \node_modules\metro-config\src\defaults\blacklist.js .

Search this variable:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

and change to this:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Please note that if you run an npm install or a yarn install you need to change the code again.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I use this:

interface IObjectKeys {
  [key: string]: string | number;
}

interface IDevice extends IObjectKeys {
  id: number;
  room_id: number;
  name: string;
  type: string;
  description: string;
}

If you use the optional property in your object:

interface IDevice extends IObjectKeys {
  id: number;
  room_id?: number;
  name?: string;
  type?: string;
  description?: string;
}

... you should add 'undefined' value into the IObjectKeys interface:

interface IObjectKeys {
  [key: string]: string | number | undefined;
}

Why am I getting Unknown error in line 1 of pom.xml?

In my pom.xml file I had to downgrade the version from 2.1.6.RELEASE for spring-boot-starter-parent artifact to 2.1.4.RELEASE

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
</parent>

to be changed to

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
</parent>

And that weird Unknown error disappeared

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

Tensorflow has a fix in tf-nightly version.

!pip install tf-nightly

The current version is '2.0.0-dev20190511'.

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

It is useful for Linux people. My problem was trivial, I used chromium-browser. I installed chrome and all problems were resolved. It could work with chromium but with extra actions. I did not receive a success. I could set a need driver version to protractor configuration. It used the latest. I needed a downgrade.

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

If you have a seeder in your database, run php artisan migrate:fresh --seed

How to use callback with useState hook in react

With React16.x, if you want to invoke a callback function on state change using useState hook, you can use the useEffect hook attached to the state change.

import React, { useEffect } from 'react';

useEffect(() => {
  props.getChildChange(name); // using camelCase for variable name is recommended.
}, [name]); // this will call getChildChange when ever name changes.

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

This error could also be because you are not subscribing to the Observable.

Example, instead of:

this.products = this.productService.getProducts();

do this:

   this.productService.getProducts().subscribe({
    next: products=>this.products = products,
    error: err=>this.errorMessage = err
   });

Can I set state inside a useEffect hook

For future purposes, this may help too:

It's ok to use setState in useEffect you just need to have attention as described already to not create a loop.

But it's not the only problem that may occur. See below:

Imagine that you have a component Comp that receives props from parent and according to a props change you want to set Comp's state. For some reason, you need to change for each prop in a different useEffect:

DO NOT DO THIS

useEffect(() => {
  setState({ ...state, a: props.a });
}, [props.a]);

useEffect(() => {
  setState({ ...state, b: props.b });
}, [props.b]);

It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w

The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a and prop.b so the value of {...state} when you do setState are exactly the same in both useEffect because they are in the same context. When you run the second setState it will replace the first setState.

DO THIS INSTEAD

The solution for this problem is basically call setState like this:

useEffect(() => {
  setState(state => ({ ...state, a: props.a }));
}, [props.a]);

useEffect(() => {
  setState(state => ({ ...state, b: props.b }));
}, [props.b]);

Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx

Now, you always receive the most updated and correct value of the state when you proceed with the setState.

I hope this helps someone!

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I tried everything above nothing worked for me it was a space in a folder name

/swift files/project a/code.xcworkspace -> /swift_files/project_a/code.xcworkspace
did the trick If I looked deeper it was stopping at /swift

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Try to download HERE and use this latest chrome driver version.

https://sites.google.com/a/chromium.org/chromedriver/downloads

EDIT:

Try this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
d = webdriver.Chrome('/home/PycharmProjects/chromedriver',chrome_options=chrome_options)
d.get('https://www.google.nl/')

Flutter: RenderBox was not laid out

Placing your list view in a Flexible widget may also help,

Flexible( fit: FlexFit.tight, child: _buildYourListWidget(..),)

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I got the same error today but with a different scenario as compared to the scenario posted in this question. Hope the solution to below scenario helps someone.

The render function below is sufficient to understand my scenario and solution:

render() {
    let orderDetails = null;
    if(this.props.loading){
        orderDetails = <Spinner />;
    }
    if(this.props.orders.length == 0){
        orderDetails = null;
    }
    orderDetails = (
        <div>
            {
                this.props.orders.map(order => (
                <Order 
                    key={order.id}
                    ingredient={order.ingredients}
                    price={order.price} />
                ))
            }
        </div>
    );
    return orderDetails;
}

In above code snippet : If return orderDetails is sent as return {orderDetails} then the error posted in this question pops up despite the value of 'orderDetails' (value as <Spinner/> or null or JSX related to <Order /> component).

Error description : react-dom.development.js:57 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {orderDetails}). If you meant to render a collection of children, use an array instead.

We cannot return a JavaScript object from a return call inside the render() method. The reason being React expects a component or some JSX or null to render in the UI and not some JavaScript object that I am trying to render when I use return {orderDetails} and hence get the error as above.

Xcode 10: A valid provisioning profile for this executable was not found

I had the case where my app would deploy to my iPhone but not my watch. Deploying to the watch would give the "A valid provisioning profile for this executable was not found." error. This is with XCode Version 11.2.1 and using the free developer account.

Here is what I did to get it deployed to my watch:

1) I deleted my provisioning profile in XCode. I did this by going to Window -> Devices And Simulators. Then right Click on the iPhone name and choose "Show Provisioning Profiles". From there I could delete the file

2) In The Devices and Simulators screen I also deleted my app from the "Installed Apps" section.

3) Did a "clean build folder" (Product -> Clean Build Folder)

4) In the "Build Settings" -> "Signing section" I made sure each target (iPhone, Tests and Watch) had the same settings (development team, code signing style, provisioning profile was set to automatic etc).

build settings details

5) Ensured the ~/Library/MobileDevice/Provisioning Profiles directory was empty.

6) Unplugged phone from computer

7) Rebooted computer, phone and watch

8) Plugged phone back into computer, and went through the "trust this machine" prompts on phone and watch.

9) Ran app. It worked!

Problems after upgrading to Xcode 10: Build input file cannot be found

File>Project Settings>Change Build Systems to Legacy Build Systems

How to reload current page?

Without specifying the path you can do:

constructor(private route: ActivatedRoute, private router: Router) { }

reload() {
  this.router.routeReuseStrategy.shouldReuseRoute = () => false;
  this.router.onSameUrlNavigation = 'reload';
  this.router.navigate(['./'], { relativeTo: this.route });
}

And if you use query params you can do:

reload() {
  ...
  this.router.navigate(['./'], { relativeTo: this.route, queryParamsHandling: 'preserve' });
}

Getting all documents from one collection in Firestore

Two years late but I just began reading the Firestore documentation recently cover to cover for fun and found withConverter which I saw wasn't posted in any of the above answers. Thus:

If you want to include ids and also use withConverter (Firestore's version of ORMs, like ActiveRecord for Ruby on Rails, Entity Framework for .NET, etc), then this might be useful for you:

Somewhere in your project, you probably have your Event model properly defined. For example, something like:

Your model (in TypeScript): ./models/Event.js

export class Event {
  constructor (
    public id: string,
    public title: string,
    public datetime: Date
  )
}

export const eventConverter = {
  toFirestore: function (event: Event) {
    return {
      // id: event.id,  // Note! Not in ".data()" of the model!
      title: event.title,
      datetime: event.datetime
    }
  },
  fromFirestore: function (snapshot: any, options: any) {
    const data = snapshot.data(options)
    const id = snapshot.id
    return new Event(id, data.title, data.datetime)
  }
}

And then your client-side TypeScript code:

import { eventConverter } from './models/Event.js'

...

async function loadEvents () {
  const qs = await firebase.firestore().collection('events')
    .orderBy('datetime').limit(3)  // Remember to limit return sizes!
    .withConverter(eventConverter).get()

  const events = qs.docs.map((doc: any) => doc.data())

  ...
}

Two interesting quirks of Firestore to notice (or at least, I thought were interesting):

  1. Your event.id is actually stored "one-level-up" in snapshot.id and not snapshot.data().

  2. If you're using TypeScript, the TS linter (or whatever it's called) sadly isn't smart enough to understand:

const events = qs.docs.map((doc: Event) => doc.data())

even though right above it you explicitly stated: .withConverter(eventConverter)

Which is why it needs to be doc: any.

(But! You will actually get Array<Event> back! (Not Array<Map> back.) That's the entire point of withConverter... That way if you have any object methods (not shown here in this example), you can immediately use them.)

It makes sense to me but I guess I've gotten so greedy/spoiled that I just kinda expect my VS Code, ESLint, and the TS Watcher to literally do everything for me. Oh well.


Formal docs (about withConverter and more) here: https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects

Can I use library that used android support with Androidx projects.

You can enable Jetifier on your project, which will basically exchange the Android Support Library dependencies in your project dependencies with AndroidX-ones. (e.g. Your Lottie dependencies will be changed from Support to AnroidX)

From the Android Studio Documentation (https://developer.android.com/studio/preview/features/):

The Android Gradle plugin provides the following global flags that you can set in your gradle.properties file:

  • android.useAndroidX: When set to true, this flag indicates that you want to start using AndroidX from now on. If the flag is absent, Android Studio behaves as if the flag were set to false.
  • android.enableJetifier: When set to true, this flag indicates that you want to have tool support (from the Android Gradle plugin) to automatically convert existing third-party libraries as if they were written for AndroidX. If the flag is absent, Android Studio behaves as if the flag were set to false.

Precondition for Jetifier:

  • you have to use at least Android Studio 3.2

To enable jetifier, add those two lines to your gradle.properties file:

android.useAndroidX=true
android.enableJetifier=true

Finally, please check the release notes of AndroidX, because jetifier has still some problems with some libraries (e.g. Dagger Android): https://developer.android.com/topic/libraries/support-library/androidx-rn

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

Xcode couldn't find any provisioning profiles matching

I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem

What is AndroidX?

It is the same as AppCompat versions of support but it has less mess of v4 and v7 versions so it is much help from Using the different components of android XML elements.

Sort Array of object by object field in Angular 6

You can simply use Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

Working Example :

_x000D_
_x000D_
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
 _x000D_
 console.log(array);
_x000D_
_x000D_
_x000D_

How to uninstall Eclipse?

Look for an installation subdirectory, likely named eclipse. Under that subdirectory, if you see files like eclipse.ini, icon.xpm and subdirectories like plugins and dropins, remove the subdirectory parent (the one named eclipse).

That will remove your installation except for anything you've set up yourself (like workspaces, projects, etc.).

Hope this helps.

Using Environment Variables with Vue.js

If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.

The variables will automatically be accessible under process.env.variableName in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.

You have a few options, this is from the Environment Variables and Modes documentation:

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

Your .env file should look like this:

VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value

It is my understanding that all you need to do is create the .env file and add your variables then you're ready to go! :)

As noted in comment below: If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

Don't forget to restart serve if it is currently running.

Angular 6: How to set response type as text while making http call

By Default angular return responseType as Json, but we can configure below types according to your requirement.

responseType: 'arraybuffer'|'blob'|'json'|'text'

Ex:

this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'});

Xcode 10 Error: Multiple commands produce

1- Remove DerivedData For all Apps 2- Open Terminal 3- Update Pod Every thing Done

react button onClick redirect page

With React Router v5.1:

import {useHistory} from 'react-router-dom';
import React, {Component} from 'react';
import {Button} from 'reactstrap';
.....
.....
export class yourComponent extends Component {
    .....
    componentDidMount() { 
        let history = useHistory;
        .......
    }

    render() {
        return(
        .....
        .....
            <Button className="fooBarClass" onClick={() => history.back()}>Back</Button>

        )
    }
}

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

Try to install angular-devkit for building angular projects

npm install --save-dev @angular-devkit/build-angular

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

Install @angular-devkit/build-angular as dev dependency. This package is newly introduced in Angular 6.0

npm install --save-dev @angular-devkit/build-angular

or,

yarn add @angular-devkit/build-angular --dev

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

I have the same problem, in build.gradle (Module:app) add the following line of code inside dependencies:

dependencies 
{
   ...
   compile 'com.android.support:support-annotations:27.1.1'
}

It worked for me perfectly

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

This worked for me. Add sudo before python

curl https://bootstrap.pypa.io/get-pip.py |sudo python

Extract Google Drive zip from Google colab notebook

Colab research team has a notebook for helping you out.

Still, in short, if you are dealing with a zip file, like for me it is mostly thousands of images and I want to store them in a folder within drive then do this --

!unzip -u "/content/drive/My Drive/folder/example.zip" -d "/content/drive/My Drive/folder/NewFolder"

-u part controls extraction only if new/necessary. It is important if suddenly you lose connection or hardware switches off.

-d creates the directory and extracted files are stored there.

Of course before doing this you need to mount your drive

from google.colab import drive 
drive.mount('/content/drive')

I hope this helps! Cheers!!

How to create a new text file using Python

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!

VSCode single to double quote automatic replace

For JSX use:

{"jsxSingleQuote": false}

Entity Framework Core: A second operation started on this context before a previous operation completed

My situation is different: I was trying to seed the database with 30 users, belonging to specific roles, so I was running this code:

for (var i = 1; i <= 30; i++)
{
    CreateUserWithRole("Analyst", $"analyst{i}", UserManager);
}

This was a Sync function. Inside of it I had 3 calls to:

UserManager.FindByNameAsync(username).Result
UserManager.CreateAsync(user, pass).Result
UserManager.AddToRoleAsync(user, roleName).Result

When I replaced .Result with .GetAwaiter().GetResult(), this error went away.

Dart SDK is not configured

In my case Dart also installed separately for dart development with latest. So when IntelliJ suggest me to configure dart, I hit it and then it pointed to C:/tools/dart that was the case.

So, I had to go to File->Settings->Language & Framework->dart and add the SDK path to my Flutter sdk path with Dart SDK C:\flutter\bin\cache\dart-sdk.

Note that as others mentioned if you pointed out the Flutter SDK path, you may not be needed to setup Dart SDK path because of Flutter SDK comes with Dart SDK in it.

Failed linking file resources

This sometimes happens when you have a random XML file doing nothing. Removing the file resolves the issue.

Docker error: invalid reference format: repository name must be lowercase

In my case, the image name defined in docker-compose.yml contained uppercase letters. The fact that the error message mentioned repository instead of image did not help describe the problem and it took a while to figure out.

PackagesNotFoundError: The following packages are not available from current channels:

Have you tried:

pip install <package>

or

conda install -c conda-forge <package>

Google Colab: how to read data from my google drive?

What I have done is first:

from google.colab import drive
drive.mount('/content/drive/')

Then

%cd /content/drive/My Drive/Colab Notebooks/

After I can for example read csv files with

df = pd.read_csv("data_example.csv")

If you have different locations for the files just add the correct path after My Drive

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

I ran this in the command prompt(have windows 7 os): JAVA_HOME=C:\Program Files\Android\Android Studio\jre

where what its = to is the path to that jre folder, so anyone's can be different.

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Xampp localhost/dashboard

Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.

So, the simplest solution is to rename index.php or index.html to index2.php etc.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I had the same problem, and my solution was to eliminate the line

android:screenOrientation="portrait"

and then add this in the activity:

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Just solve the problem which come from java compiler instead of Build-Run task

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

I had the same problem and none of the above answers worked. If you go into the settings (CTRL + ALT + s) and search for project interpreter you will see all of the installed packages. Click the + button at the top right and search for xlrd, then click install package at the bottom left.

I had already done the "pip install xlrd" command from the file location of my python.exe before this, so you may need to do that as well. (you can find the file location by searching it in windows search bar and right click -> open file location, then type cmd into the file explorer address bar)

Exception : AAPT2 error: check logs for details

If you are getting this error only when you are generating signed Apk . Then the problem might be in one or more of the imported media file format. I have used an image directly from net to studio and was not able to generate sign apk, then found the error .

from Gradle >assembleRelease then got the error in console. see the error log in console image. This was my Error, See its clearly written that one of my image format is not valid or unknown

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

I tried all of the above and nothing worked for me.

Then I followed Gradle Settings > Build Execution, Deployment > Gradle > Android Studio and checked "Disable embedded Maven repository".

Did a build with this checked and the problem was solved.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

You could use moment.js with Postman to give you that timestamp format.

You can add this to the pre-request script:

const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));

Then reference {{today}} where ever you need it.

If you add this to the Collection Level Pre-request Script, it will be run for each request in the Collection. Rather than needing to add it to all the requests individually.

For more information about using moment in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/

Angular Material: mat-select not selecting default

Use a binding for the value in your template.

value="{{ option.id }}"

should be

[value]="option.id"

And in your selected value use ngModel instead of value.

<mat-select [(value)]="selected2">

should be

<mat-select [(ngModel)]="selected2">

Complete code:

<div>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</div>

On a side note as of version 2.0.0-beta.12 the material select now accepts a mat-form-field element as the parent element so it is consistent with the other material input controls. Replace the div element with mat-form-field element after you upgrade.

<mat-form-field>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</mat-form-field>

Save and load weights in keras

For loading weights, you need to have a model first. It must be:

existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')     

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model.save_model('filename')
model = load_model('filename')

No provider for HttpClient

You are getting error for HttpClient so, you are missing HttpClientModule for that.

You should import it in app.module.ts file like this -

import { HttpClientModule } from '@angular/common/http';

and mention it in the NgModule Decorator like this -

@NgModule({
...
imports:[ HttpClientModule ]
...
})

If this even doesn't work try clearing cookies of the browser and try restarting your server. Hopefully it may work, I was getting the same error.

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

If you've seen this error after trying to run individual Android implementation tests or test classes (by clicking on the run icon in the gutter) in a Kotlin project in Android Studio 3.0.1, you can get around the error by instead running the full test package (by right-clicking on the test package and choosing "Run tests in...").

There is a known bug in Android Studio 3.0.1 that causes the IDE to run Kotlin implementation tests as regular JUnit tests, which caused the OP's error message to get shown on my machine. The bug is tracked at https://issuetracker.google.com/issues/71056937. It appears to have been fixed in Android Studio 3.1 Canary 7.

Merge two array of objects based on a key

You can do this in one line

_x000D_
_x000D_
let arr1 = [_x000D_
    { id: "abdc4051", date: "2017-01-24" },_x000D_
    { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
    { id: "abdc4051", name: "ab" },_x000D_
    { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
const mergeById = (a1, a2) =>_x000D_
    a1.map(itm => ({_x000D_
        ...a2.find((item) => (item.id === itm.id) && item),_x000D_
        ...itm_x000D_
    }));_x000D_
_x000D_
console.log(mergeById(arr1, arr2));
_x000D_
_x000D_
_x000D_

  1. Map over array1
  2. Search through array2 for array1.id
  3. If you find it ...spread the result of array2 into array1

The final array will only contain id's that match from both arrays

How to change the project in GCP using CLI commands

Check the available projects by running: gcloud projects list. This will give you a list of projects which you can access. To switch between projects: gcloud config set project <project-id>.

Also, I recommend checking the active config before making any change to gcloud config. You can do so by running: gcloud config list

React-Redux: Actions must be plain objects. Use custom middleware for async actions

For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.

actions.js:

export function addNewComponent() {
  return {
    type: ADD_NEW_COMPONENT,
  };
}

myComponent.js:

import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';

  useEffect(() => {
    dispatch(refreshAllComponents); // <= Here was what I've missed.
  }, []);

I've forgotten to dispatch the action function with (). So doing this solved my issue.

  useEffect(() => {
    dispatch(refreshAllComponents());
  }, []);

Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.

How to update an "array of objects" with Firestore?

Other than the answers mentioned above. This will do it. Using Angular 5 and AngularFire2. or use firebase.firestore() instead of this.afs

  // say you have have the following object and 
  // database structure as you mentioned in your post
  data = { who: "[email protected]", when: new Date() };

  ...othercode


  addSharedWith(data) {

    const postDocRef = this.afs.collection('posts').doc('docID');

    postDocRef.subscribe( post => {

      // Grab the existing sharedWith Array
      // If post.sharedWith doesn`t exsit initiated with empty array
      const foo = { 'sharedWith' : post.sharedWith || []};

      // Grab the existing sharedWith Array
      foo['sharedWith'].push(data);

      // pass updated to fireStore
      postsDocRef.update(foo);
      // using .set() will overwrite everything
      // .update will only update existing values, 
      // so we initiated sharedWith with empty array
    });
 }  

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

You might be importing @Test from org.junit.Test, which is a JUnit 4 annotation. The Junit5 test runner will not discover it.

The Junit5 test runner will discover a test annotated with org.junit.jupiter.api.Test

Found the answer from Import org.junit.Test throws error as "No Test found with Test Runner "JUnit 5""

Angular - res.json() is not a function

You can remove the entire line below:

 .map((res: Response) => res.json());

No need to use the map method at all.

Unable to merge dex

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xyz.name"
        minSdkVersion 14
        targetSdkVersion 27
        versionCode 7
        versionName "1.6"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.wang.avi:library:2.1.3'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.android.support:support-v4:27.1.0'
    implementation 'de.hdodenhof:circleimageview:2.1.0'
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.0'
    implementation 'com.loopj.android:android-async-http:1.4.9'
    implementation 'com.google.firebase:firebase-messaging:11.8.0'
    implementation 'com.felipecsl.asymmetricgridview:library:2.0.1'
    implementation 'com.android.support:recyclerview-v7:27.1.0'
    implementation 'com.github.darsh2:MultipleImageSelect:3474549'
    implementation 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
    implementation 'com.android.support:multidex:1.0.1'
}

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

Note: update your all support library to 27.1.0 like above and remove duplicates

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

This happens when you push first time without net connection or poor net connection.But when you try again using good connection 2,3 times problem will be solved.

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

"The page has expired due to inactivity" - Laravel 5.5

In my case, the site was fine in server but not in local. Then I remember I was working on secure website.
So in file config.session.php, set the variable secure to false

'secure' => env('SESSION_SECURE_COOKIE', false),

No converter found capable of converting from type to type

Simple Solution::

use {nativeQuery=true} in your query.

for example

  @Query(value = "select d.id,d.name,d.breed,d.origin from Dog d",nativeQuery = true)
        
    List<Dog> findALL();

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

total edge case here: I had this issue installing an Arch AUR PKGBUILD file manually. In my case I needed to delete the 'pkg', 'src' and 'node_modules' folders, then it built fine without this npm error.

Angular 4 setting selected option in Dropdown

If you want to select a value based on true / false use

[selected]="opt.selected == true"

 <option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>

checkit out

Angular 2 - Setting selected value on dropdown list

How to get param from url in angular 4?

import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap
    .subscribe( params => {
    let id = +params.get('id');
    console.log('id' + id);
    console.log(params);


id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
        }
        )

      }

Is there way to use two PHP versions in XAMPP?

You can download and install two different xampps like I do: (first is php7 second is php5) enter image description here

and if you don't want to do that, I suggest you use wamp and change versions like shown here.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Add store name to template like {% url 'app_name:url_name' %}

App_name = store

In urls.py, path('search', views.searched, name="searched"),

<form action="{% url 'store:searched' %}" method="POST">

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.

Please check if you changed: compileSdkVersion --> implementationSdkVersion by mistake

how to refresh page in angular 2

Updated

How to implement page refresh in Angular 2+ note this is done within your component:

location.reload();

How to acces external json file objects in vue.js app

Just assign the import to a data property

<script>
      import json from './json/data.json'
      export default{
          data(){
              return{
                  myJson: json
              }
          }
      }
</script>

then loop through the myJson property in your template using v-for

<template>
    <div>
        <div v-for="data in myJson">{{data}}</div>
    </div>
</template>

NOTE

If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.

Vue converts all the properties in the data option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.

So you can create a custom option as follows:

<script>
          import MY_JSON from './json/data.json'
          export default{
              //custom option named myJson
                 myJson: MY_JSON
          }
    </script>

then loop through the custom option in your template using $options:

<template>
        <div>
            <div v-for="data in $options.myJson">{{data}}</div>
        </div>
    </template>

Error: fix the version conflict (google-services plugin)

All google services should be of same version, try matching every versions.

Correct one is :

  implementation 'com.google.firebase:firebase-auth:11.6.0'
  implementation 'com.google.firebase:firebase-database:11.6.0'

Incorrect Config is :

 implementation 'com.google.firebase:firebase-auth:11.6.0'
 implementation 'com.google.firebase:firebase-database:11.8.0'

Failed to resolve: com.android.support:appcompat-v7:26.0.0

File -> Project Structure -> Modules (app) -> Open Dependencies Tab -> Remove all then use + to add from the proposed list.

Constraint Layout Vertical Align Center

May be i did not fully understand the problem, but, centering all view inside a ConstraintLayout seems very simple. This is what I used:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">

enter image description here

Last two lines did the trick!

Class has no objects member

I was able to update the user settings.json

On my mac it was stored in:

~/Library/Application Support/Code/User/settings.json

Within it, I set the following:

{
    "python.linting.pycodestyleEnabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pylintPath": "pylint",
    "python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
}

That solved the issue for me.

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

According to this issue comment, editing cross-env path will fix the problem. Change cross-env to node node_modules/cross-env/dist/bin/cross-env.js in package.json like this:

    "dev": "npm run development",
    "development": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"

Cloning an array in Javascript/Typescript

try the following code:

this.cloneArray= [...this.OriginalArray]

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

Use defaultValue and onChange like this

const [myValue, setMyValue] = useState('');

<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
                    
       <option>Option 1</option>
       <option>Option 2</option>
       <option>Option 3</option>

</select>

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

RESTART YOUR IDE

I tried all of the different things but nothing seems to be working then I just restarted my IDE and it worked like charm.

Still, if it does not work then try restarting your system.

FYI, I am working on the following versions

opencv-contrib-python==4.4.0.46
opencv-python==4.1.2.30

Vue Js - Loop via v-for X times (in a range)

I have solved it with Dov Benjamin's help like that:

<ul>
  <li v-for="(n,index) in 2">{{ object.price }}</li>
</ul>

And another method, for both V1.x and 2.x of vue.js

Vue 1:

<p v-for="item in items | limitBy 10">{{ item }}</p>

Vue2:

// Via slice method in computed prop

<p v-for="item in filteredItems">{{ item }}</p>

computed: {
   filteredItems: function () {
     return this.items.slice(0, 10)
     }
  }

How to fix Cannot find module 'typescript' in Angular 4?

I had the same problem. If you have installed first nodejs by apt and then you use the tar.gz from nodejs.org, you have to delete the folder located in /usr/lib/node_modules.

Safe Area of Xcode 9

enter image description here

  • Earlier in iOS 7.0–11.0 <Deprecated> UIKit uses the topLayoutGuide & bottomLayoutGuide which is UIView property
  • iOS11+ uses safeAreaLayoutGuide which is also UIView property

  • Enable Safe Area Layout Guide check box from file inspector.

  • Safe areas help you place your views within the visible portion of the overall interface.

  • In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.

  • safeAreaLayoutGuide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor viewss.
  • Use safe areas as an aid to laying out your content like UIButton etc.

  • When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.

  • Make sure backgrounds extend to the edges of the display, and that vertically scrollable layouts, like tables and collections, continue all the way to the bottom.

  • The status bar is taller on iPhone X than on other iPhones. If your app assumes a fixed status bar height for positioning content below the status bar, you must update your app to dynamically position content based on the user's device. Note that the status bar on iPhone X doesn't change height when background tasks like voice recording and location tracking are active print(UIApplication.shared.statusBarFrame.height)//44 for iPhone X, 20 for other iPhones

  • Height of home indicator container is 34 points.

  • Once you enable Safe Area Layout Guide you can see safe area constraints property listed in the interface builder.

enter image description here

You can set constraints with respective of self.view.safeAreaLayoutGuide as-

ObjC:

  self.demoView.translatesAutoresizingMaskIntoConstraints = NO;
    UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
    [self.demoView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
    [self.demoView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
    [self.demoView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
    [self.demoView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;

Swift:

   demoView.translatesAutoresizingMaskIntoConstraints = false
        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            demoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
            demoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
            demoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
            demoView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
        } else {
            NSLayoutConstraint(item: demoView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
        }

enter image description here

enter image description here

enter image description here

Angular 2 'component' is not a known element

Route modules (did not saw this as an answer)

First check: if you have declared- and exported the component inside its module, imported the module where you want to use it and named the component correctly inside the HTML.

Otherwise, you might miss a module inside your routing module:
When you have a routing module with a route that routes to a component from another module, it is important that you import that module within that route module. Otherwise the Angular CLI will show the error: component is not a known element.

For example

1) Having the following project structure:

+---core
¦   +---sidebar
¦           sidebar.component.ts
¦           sidebar.module.ts
¦
+---todos
    ¦   todos-routing.module.ts
    ¦   todos.module.ts
    ¦
    +---pages
            edit-todo.component.ts
            edit-todo.module.ts

2) Inside the todos-routing.module.ts you have a route to the edit.todo.component.ts (without importing its module):

  {
    path: 'edit-todo/:todoId',
    component: EditTodoComponent,
  },

The route will just work fine! However when importing the sidebar.module.ts inside the edit-todo.module.ts you will get an error: app-sidebar is not a known element.

Fix: Since you have added a route to the edit-todo.component.ts in step 2, you will have to add the edit-todo.module.ts as an import, after that the imported sidebar component will work!

ssl.SSLError: tlsv1 alert protocol version

I got this problem too. In macos, here is the solution:

  • Step 1: brew restall python. now you got python3.7 instead of the old python

  • Step 2: build the new env base on python3.7. my path is /usr/local/Cellar/python/3.7.2/bin/python3.7

now, you'll not being disturbed by this problem.

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

My problem was that I forgot that I added a proxy in gradle.properties in C:\Users\(current user)\.gradle like:

systemProp.http.proxyHost=****
systemProp.http.proxyPort=8850

How does createOrReplaceTempView work in Spark?

CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.

first we read data in csv format and then convert to data frame and create a temp view

Reading data in csv format

val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")

printing the schema

data.printSchema

SchemaOfTable

data.createOrReplaceTempView("Data")

Now we can run sql queries on top the table view we just created

  %sql select Week as Date,Campaign Type,Engagements,Country from Data order     by Date asc

enter image description here

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

run gradle assembleDebug --scan in Android studio Terminal, in my case I removed an element in XML and forgotten to remove it from code, but the compiler couldn't compile and show Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details to me.

enter image description here

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Working on .Net Core 2.2 and 3.0 as of now.

To get the projects root directory within a Controller:

  • Create a property for the hosting environment

    private readonly IHostingEnvironment _hostingEnvironment;
    
  • Add Microsoft.AspNetCore.Hosting to your controller

    using Microsoft.AspNetCore.Hosting;
    
  • Register the service in the constructor

    public HomeController(IHostingEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }
    
  • Now, to get the projects root path

    string projectRootPath = _hostingEnvironment.ContentRootPath;
    

To get the "wwwroot" path, use

_hostingEnvironment.WebRootPath

How does the "position: sticky;" property work?

I know this seems to be already answered, but I ran into a specific case, and I feel most answers miss the point.

The overflow:hidden answers cover 90% of the cases. That's more or less the "sticky nav" scenario.

But the sticky behavior is best used within the height of a container. Think of a newsletter form in the right column of your website that scrolls down with the page. If your sticky element is the only child of the container, the container is the exact same size, and there's no room to scroll.

Your container needs to be the height you expect your element to scroll within. Which in my "right column" scenario is the height of the left column. The best way to achieve this is to use display:table-cell on the columns. If you can't, and are stuck with float:right and such like I was, you'll have to either guess the left column height of compute it with Javascript.

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

VS2017 supports ssis or ssrs projects if you install SSDT for VS2017 here.

Click on the newly downloaded file and check SSIS or SSRS components that you required, as show in diagram :-

enter image description here

Once you have installed this, try opening ssis / ssrs project. I managed to open ssis developed on vs2010.

You should see these component installed. (reboot if you don't see them).

enter image description here

Try open your project again. If you get 'incompatible project' - right click on your project, select "reload project" (not reopen the solution)

Sort an array of objects in React and render them

This might be what you're looking for:

// ... rest of code

// copy your state.data to a new array and sort it by itemM in ascending order
// and then map 
const myData = [].concat(this.state.data)
    .sort((a, b) => a.itemM > b.itemM ? 1 : -1)
    .map((item, i) => 
        <div key={i}> {item.matchID} {item.timeM}{item.description}</div>
    );

// render your data here...

The method sort will mutate the original array . Hence I create a new array using the concat method. The sorting on the field itemM should work on sortable entities like string and numbers.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:

Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");

You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.

Is Visual Studio Community a 30 day trial?

No, Community edition is free, so just sign-in and rid the warning. For more detail please check following link.
https://visualstudio.microsoft.com/vs/support/community-edition-expired-buy-license/

Export result set on Dbeaver to CSV

You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :

  1. Execute your query
  2. Right click any anywhere in the results
  3. click "Export resultset..." to open the export wizard
  4. Choose the format you want (CSV according to your question)
  5. Review the settings in the next panes when clicking "Next".
  6. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.


In newer versions of DBeaver you can just :

  1. right click the SQL of the query you want to export
  2. Execute > Export from query
  3. Choose the format you want (CSV according to your question)
  4. Review the settings in the next panes when clicking "Next".
  5. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.

Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.

How to use paths in tsconfig.json?

It looks like there has been an update to React that doesn't allow you to set the "paths" in the tsconfig.json anylonger.

Nicely React just outputs a warning:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

then updates your tsconfig.json and removes the entire "paths" section for you. There is a way to get around this run

npm run eject

This will eject all of the create-react-scripts settings by adding config and scripts directories and build/config files into your project. This also allows a lot more control over how everything is built, named etc. by updating the {project}/config/* files.

Then update your tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./src",
        {…}
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

Trying to use fetch and pass in mode: no-cors

So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

  1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
  2. Add the following code inside the handles function in Cors.php:

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

    ‘cors’ => \App\Http\Middleware\Cors::class
    

    (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

  4. Add this middleware on route registration for all the routes where you want to allow access, like this:

    Route::group(['middleware' => 'cors'], function () {
        Route::get('getData', 'v1\MyController@getData');
        Route::get('getData2', 'v1\MyController@getData2');
    });
    
  5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

Full credits to Pete Houston's blog article.

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

Laravel - htmlspecialchars() expects parameter 1 to be string, object given.

thank me latter.........................

when you send or get array from contrller or function but try to print as single value or single variable in laravel blade file so it throws an error

->use any think who convert array into string it work.

solution: 1)run the foreach loop and get single single value and print. 2)The implode() function returns a string from the elements of an array. {{ implode($your_variable,',') }}

implode is best way to do it and its 100% work.

Hibernate Error executing DDL via JDBC Statement

in your CFG file please change the hibernate dialect

<!-- SQL dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

TypeScript enum to object array

Simply this will return an array of enum values:

 Object.values(myEnum);

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

Open gradle-wrapper.properties

Change the version there on distributionUrl line

In Angular, What is 'pathmatch: full' and what effect does it have?

RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: '', redirectTo: 'welcome', pathMatch: 'full' },
      { path: '**', component: 'pageNotFoundComponent' }
    ])

Case 1 pathMatch:'full': In this case, when app is launched on localhost:4200 (or some server) the default page will be welcome screen, since the url will be https://localhost:4200/

If https://localhost:4200/gibberish this will redirect to pageNotFound screen because of path:'**' wildcard

Case 2 pathMatch:'prefix':

If the routes have { path: '', redirectTo: 'welcome', pathMatch: 'prefix' }, now this will never reach the wildcard route since every url would match path:'' defined.

React.createElement: type is invalid -- expected a string

In my case, the order in which you create the component and render, mattered. I was rendering the component before creating it. The best way is to create the child component and then the parent components and then render the parent component. Changing the order fixed the issue for me.

Visual Studio 2017 errors on standard headers

I got the errors to go away by installing the Windows Universal CRT SDK component, which adds support for legacy Windows SDKs. You can install this using the Visual Studio Installer:

enter image description here

If the problem still persists, you should change the Target SDK in the Visual Studio Project : check whether the Windows SDK version is 10.0.15063.0.

In : Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0.

Then errno.h and other standard files will be found and it will compile.

Visual Studio 2017 - Git failed with a fatal error

  1. Navigate to C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\
  2. Delete the Git folder
  3. Visual Studio

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

Taking a cue from @Mikel Yang, I found out that instead of deleting the ~/.gradle/wrapper/dists/ folder (which will means downloading the gradle files for different apps on my Android Studio), I decided to change the gradle.wrapper.properties file to any latest gradle --all.zip. So

Find 'gradle-wrapper.properties' in root project

distributionUrl=https\://services.gradle.org/distributions/gradle-{lastest}-all.zip

this way l get to save some data and time.

Flask - Calling python function on button OnClick event

index.html (index.html should be in templates folder)

<!doctype html>
<html>

<head>
    <title>The jQuery Example</title>

    <h2>jQuery-AJAX in FLASK. Execute function on button click</h2>  

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
    function(data) { }); return false; }); }); </script> 
</head>

<body>        
        <input type = "button" id = "mybutton" value = "Click Here" />
</body>    

</html>

test.py

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/SomeFunction')
def SomeFunction():
    print('In SomeFunction')
    return "Nothing"



if __name__ == '__main__':
   app.run()

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

I don't think that IDE is relevant here. After all you're running a Maven and Maven doesn't have a source that will allow to compile the diamond operators. So, I think you should configure maven-compiler-plugin itself.

You can read about this here. But in general try to add the following properties:

<properties>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
</properties>

and see whether it compiles now in Maven only.

Error:Cause: unable to find valid certification path to requested target

Run bellow command in Android studio terminal after opening the same project. It worked for me.

On Windows:

gradlew cleanBuildCache

On Mac or Linux:

./gradlew cleanBuildCache

How can I create an observable with a delay

In RxJS 5+ you can do it like this

import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { delay } from "rxjs/operators";

fakeObservable = of('dummy').pipe(delay(5000));

In RxJS 6+

import { of } from "rxjs";
import { delay } from "rxjs/operators";

fakeObservable = of('dummy').pipe(delay(5000));

If you want to delay each emitted value try

from([1, 2, 3]).pipe(concatMap(item => of(item).pipe(delay(1000))));

How can I serve static html from spring boot?

As it is written before, some folders (/META-INF/resources/, /resources/, /static/, /public/) serve static content by default, conroller misconfiguration can break this behaviour.

It is a common pitfall that people define the base url of a controller in the @RestController annotation, instead of the @RequestMapping annotation on the top of the controllers.

This is wrong:

@RestController("/api/base")
public class MyController {

    @PostMapping
    public String myPostMethod( ...) {

The above example will prevent you from opening the index.html. The Spring expects a POST method at the root, because the myPostMethod is mapped to the "/" path.

You have to use this instead:

@RestController
@RequestMapping("/api/base")
public class MyController {

    @PostMapping
    public String myPostMethod( ...) {

Job for mysqld.service failed See "systemctl status mysqld.service"

Had the same problem. Solved as given below. Use command :

sudo tail -f /var/log/messages|grep -i mysql

to check if SELinux policy is causing the issue. If so, first check if SELinux policy is enabled using command #sestatus. If it shows enabled, then disable it. To disable:

  1. # vi /etc/sysconfig/selinux
  2. change 'SELINUX=enforcing' to 'SELINUX=disabled'
  3. restart linux
  4. check with sestatus and it should show "disabled"

Uninstall and reinstall mysql. It should be working.

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

I am answering this for android studio 2.3.1. One of the easiest ways to set RelativeLayout as default layout is going to text mode and editing the XML file as follows:

Change this line:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

To

<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

And do check your ending tag changes to this:

</android.widget.RelativeLayout>

Also (optionally) go ahead and delete this line if it's being shown in grey:

xmlns:app="http://schemas.android.com/apk/res-auto"

Edit:

This is an optional change to make in project, I came across this tip while going through Udacity's Android Developer Course

If the constraint layout is not needed in the project remove the following dependency from build.gradle by deleting this line and then doing gradle sync:

    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

Vue.js - How to properly watch for nested data

Not seeing it mentioned here, but also possible to use the vue-property-decorator pattern if you are extending your Vue class.

import { Watch, Vue } from 'vue-property-decorator';

export default class SomeClass extends Vue {
   ...

   @Watch('item.someOtherProp')
   someOtherPropChange(newVal, oldVal) {
      // do something
   }

   ...
}

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

I don't exactly know what causes that, but I solve it this way.
Reinstall whole project but remember that webpack-dev-server must be globally installed.
I walk through some server errors like webpack cant be found, so I linked Webpack using link command.
In output Resolving some absolute path issues.

In devServer object: inline: false

webpack.config.js

module.exports = {
    entry: "./src/js/main.js",
    output: {
        path:__dirname+ '/dist/',
        filename: "bundle.js",
        publicPath: '/'
    },
    devServer: {
        inline: false,
        contentBase: "./dist",
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude:/(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }

};

package.json

{
  "name": "react-flux-architecture-es6",
  "version": "1.0.0",
  "description": "egghead",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cichy/react-flux-architecture-es6.git"
  },
  "keywords": [
    "React",
    "flux"
  ],
  "author": "Jaroslaw Cichon",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cichy/react-flux-architecture-es6/issues"
  },
  "homepage": "https://github.com/cichy/react-flux-architecture-es6#readme",
  "dependencies": {
    "flux": "^3.1.2",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-router": "^3.0.2"
  },
  "devDependencies": {
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0"
  }
}

How to listen to route changes in react router v4?

withRouter, history.listen, and useEffect (React Hooks) works quite nicely together:

import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'

const Component = ({ history }) => {
    useEffect(() => history.listen(() => {
        // do something on route change
        // for my example, close a drawer
    }), [])

    //...
}

export default withRouter(Component)

The listener callback will fire any time a route is changed, and the return for history.listen is a shutdown handler that plays nicely with useEffect.

How to get Django and ReactJS to work together?

The accepted answer lead me to believe that decoupling Django backend and React Frontend is the right way to go no matter what. In fact there are approaches in which React and Django are coupled, which may be better suited in particular situations.

This tutorial well explains this. In particular:

I see the following patterns (which are common to almost every web framework):

-React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium)

-Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication)

-Mix and match: mini React apps inside Django templates (difficulty: simple)

How to add fonts to create-react-app based projects?

  1. Go to Google Fonts https://fonts.google.com/
  2. Select your font as depicted in image below:

enter image description here

  1. Copy and then paste that url in new tab you will get the css code to add that font. In this case if you go to

https://fonts.googleapis.com/css?family=Spicy+Rice

It will open like this:

enter image description here

4, Copy and paste that code in your style.css and simply start using that font like this:

      <Typography
          variant="h1"
          gutterBottom
          style={{ fontFamily: "Spicy Rice", color: "pink" }}
        >
          React Rock
        </Typography>

Result:

enter image description here

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.

How to iterate object keys using *ngFor

You have to create custom pipe.

import { Injectable, Pipe } from '@angular/core';
@Pipe({
   name: 'keyobject'
})
@Injectable()
export class Keyobject {

transform(value, args:string[]):any {
    let keys = [];
    for (let key in value) {
        keys.push({key: key, value: value[key]});
    }
    return keys;
}}

And then use it in your *ngFor

*ngFor="let item of data | keyobject"

How to render an array of objects in React?

Try this:

_x000D_
_x000D_
class First extends React.Component {
  constructor (props){
    super(props);

  }

  render() {
     const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
    
    return (
      <div>
      {listItems}
      </div>
    );
  }
} 
_x000D_
_x000D_
_x000D_

Reactjs - Form input validation

Try this, example, the required property in below input tag will ensure that the name field should be submitted empty.

<input type="text" placeholder="Your Name" required />

tsconfig.json: Build:No inputs were found in config file

I had to add the files item to the tsconfig.json file, like so:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
    },
    "files": [
        "../MyFile.ts"
    ] 
}

More details here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

How to send custom headers with requests in Swagger UI?

I ended up here because I was trying to conditionally add header parameters in Swagger UI, based on my own [Authentication] attribute I added to my API method. Following the hint that @Corcus listed in a comment, I was able to derive my solution, and hopefully it will help others.

Using Reflection, it's checking if the method nested down in apiDescription has the desired attribute (MyApiKeyAuthenticationAttribute, in my case). If it does, I can append my desired header parameters.

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
    if (operation.parameters == null)
        operation.parameters = new List<Parameter>();


    var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)
        ((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo
        .GetCustomAttributes(false);
    if(attributes != null && attributes.Any()) {
        if(attributes.Where(x => x.GetType() 
            == typeof(MyApiKeyAuthenticationAttribute)).Any()) {

            operation.parameters.Add(new Parameter {
                name = "MyApiKey",
                @in = "header",
                type = "string",
                description = "My API Key",
                required = true
            });
            operation.parameters.Add(new Parameter {
                name = "EID",
                @in = "header",
                type = "string",
                description = "Employee ID",
                required = true
            });
        }
    }


}

Vue - Deep watching an array of objects and calculating the change?

I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.

Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.

new Vue({
  methods: {
    setValue: function() {
      this.$data.oldPeople = _.cloneDeep(this.$data.people);
    },
  },
  mounted() {
    this.setValue();
  },
  el: '#app',
  data: {
    people: [
      {id: 0, name: 'Bob', age: 27},
      {id: 1, name: 'Frank', age: 32},
      {id: 2, name: 'Joe', age: 38}
    ],
    oldPeople: []
  },
  watch: {
    people: {
      handler: function (after, before) {
        // Return the object that changed
        var vm = this;
        let changed = after.filter( function( p, idx ) {
          return Object.keys(p).some( function( prop ) {
            return p[prop] !== vm.$data.oldPeople[idx][prop];
          })
        })
        // Log it
        vm.setValue();
        console.log(changed)
      },
      deep: true,
    }
  }
})

See the updated codepen

Laravel Carbon subtract days from current date

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

How to map an array of objects in React

try the following snippet

const renObjData = this.props.data.map(function(data, idx) {
    return <ul key={idx}>{$.map(data,(val,ind) => {
        return (<li>{val}</li>);
    }
    }</ul>;
});

Checking version of angular-cli that's installed?

Go to your folder path in cmd where your angular is installed and type ng --version it will show your angular version. Thanks.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The most simple way is to use Record type Record<number, productDetails >

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

What is the recommended project structure for spring boot rest projects?

You do not need to do anything special to start. Start with a normal java project, either maven or gradle or IDE project layout with starter dependency.

You need just one main class, as per guide here and rest...

There is no constrained package structure. Actual structure will be driven by your requirement/whim and the directory structure is laid by build-tool / IDE

You can follow same structure that you might be following for a Spring MVC application.

You can follow either way

  • A project is divided into layers:

    for example: DDD style

    • Service layer : service package contains service classes
    • DAO/REPO layer : dao package containing dao classes
    • Entity layers


    or

    any layer structure suitable to your problem for which you are writing problem.

  • A project divided into modules or functionalities or features and A module is divided into layers like above

I prefer the second, because it follows Business context. Think in terms of concepts.

What you do is dependent upon how you see the project. It is your code organization skills.

Removing object from array in Swift 3

The Swift equivalent to NSMutableArray's removeObject is:

var array = ["alpha", "beta", "gamma"]

if let index = array.firstIndex(of: "beta") {
    array.remove(at: index)
}

if the objects are unique. There is no need at all to cast to NSArray and use indexOfObject:

The API index(of: also works but this causes an unnecessary implicit bridge cast to NSArray.

If there are multiple occurrences of the same object use filter. However in cases like data source arrays where an index is associated with a particular object firstIndex(of is preferable because it's faster than filter.

Update:

In Swift 4.2+ you can remove one or multiple occurrences of beta with removeAll(where:):

array.removeAll{$0 == "beta"}

I get conflicting provisioning settings error when I try to archive to submit an iOS app

The problem is in the Cordova settings.

Note this:

iPhone Distribution has been manually specified

This didn’t make any sense to me, since I had set the project to auto sign in xcode. Like you, the check and uncheck didn’t work. But then I read the last file path given and followed it. The file path is APP > Platforms > ios > Cordova > build-release.xconfig

And in the file, iPhone Distribution is explicitly set for CODE_SIGN_IDENTITY.

Change:

CODE_SIGN_IDENTITY = iPhone Distribution
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution

To:

CODE_SIGN_IDENTITY = iPhone Developer
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Developer

It a simple thing, and the error message does make it clear that iPhone Distribution has been manually specified, but it doesn’t really say where unless you follow the path. I looked and fiddled with xcode for about three hours trying to figure this out. Hopes this helps anyone in the future.

ReactJS map through Object

Use Object.entries() function.

Object.entries(object) return:

[
    [key, value],
    [key, value],
    ...
]

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

{Object.entries(subjects).map(([key, subject], i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subject.name}</span>
    </li>
))}

How to group an array of objects by key

_x000D_
_x000D_
var cars = [{
  make: 'audi',
  model: 'r8',
  year: '2012'
}, {
  make: 'audi',
  model: 'rs5',
  year: '2013'
}, {
  make: 'ford',
  model: 'mustang',
  year: '2012'
}, {
  make: 'ford',
  model: 'fusion',
  year: '2015'
}, {
  make: 'kia',
  model: 'optima',
  year: '2012'
}].reduce((r, car) => {

  const {
    model,
    year,
    make
  } = car;

  r[make] = [...r[make] || [], {
    model,
    year
  }];

  return r;
}, {});

console.log(cars);
_x000D_
_x000D_
_x000D_

How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

 ....
 methods:{
     getUnits: function() {...}
 },
 beforeMount(){
    this.getUnits()
 },
 ......

Working fiddle: https://jsfiddle.net/q83bnLrx/1/

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

Change language of Visual Studio 2017 RC

I solved this just created label on desktop with option/parameter --locale en-US

"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installer.exe" --locale en-US

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

selenium - chromedriver executable needs to be in PATH

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

How do you format a Date/Time in TypeScript?

function _formatDatetime(date: Date, format: string) {
   const _padStart = (value: number): string => value.toString().padStart(2, '0');
return format
    .replace(/yyyy/g, _padStart(date.getFullYear()))
    .replace(/dd/g, _padStart(date.getDate()))
    .replace(/mm/g, _padStart(date.getMonth() + 1))
    .replace(/hh/g, _padStart(date.getHours()))
    .replace(/ii/g, _padStart(date.getMinutes()))
    .replace(/ss/g, _padStart(date.getSeconds()));
}
function isValidDate(d: Date): boolean {
    return !isNaN(d.getTime());
}
export function formatDate(date: any): string {
    var datetime = new Date(date);
    return isValidDate(datetime) ? _formatDatetime(datetime, 'yyyy-mm-dd hh:ii:ss') : '';
}

docker cannot start on windows

For Installation in Windows 10 machine: Before installing search Windows Features in search and check the windows hypervisor platform and Subsystem for Linux windows features

Installation for WSL 1 or 2 installation is compulsory so install it while docker prompt you to install it.

https://docs.microsoft.com/en-us/windows/wsl/install-win10

You need to install ubantu(version 16,18 or 20) from windows store:

ubantu version 20

After installation you can run command like docker -version or docker run hello-world in Linux terminal.

This video will help: https://www.youtube.com/watch?v=5RQbdMn04Oc&t=471s

Angular2: custom pipe could not be found

see this is working for me.

ActStatus.pipe.ts First this is my pipe

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

@Pipe({
  name:'actStatusPipe'
})
export class ActStatusPipe implements PipeTransform{
  transform(status:any):any{
    switch (status) {
      case 1:
        return "UN_PUBLISH";
      case 2:
        return "PUBLISH";
      default:
        return status
    }
  }
}

main-pipe.module.ts in pipe module, i need to declare my pipe/s and export it.

import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";

import {ActStatusPipe} from "./ActStatusPipe.pipe"; // <---

@NgModule({
  declarations:[ActStatusPipe], // <---
  imports:[CommonModule],
  exports:[ActStatusPipe] // <---
})

export class MainPipe{}

app.module.ts user this pipe module in any module.

@NgModule({
  declarations: [...],
  imports: [..., MainPipe], // <---
  providers: [...],
  bootstrap: [AppComponent]
})

you can directly user pipe in this module. but if you feel that your pipe is used with in more than one component i suggest you to follow my approach.

  1. create pipe .
  2. create separate module and declare and export one or more pipe.
  3. user that pipe module.

How to use pipe totally depends on your project complexity and requirement. you might have just one pipe which used only once in the whole project. in that case you can directly use it without creating a pipe/s module (module approach).

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Removing object properties with Lodash

You can approach it from either an "allow list" or a "block list" way:

// Block list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);

// Allow list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);

If it's reusable business logic, you can partial it out as well:

// Partial out a "block list" version
var clean = _.partial(_.omit, _, ['age']);

// and later
var result = clean(credentials);

Note that Lodash 5 will drop support for omit

A similar approach can be achieved without Lodash:

const transform = (obj, predicate) => {
  return Object.keys(obj).reduce((memo, key) => {
    if(predicate(obj[key], key)) {
      memo[key] = obj[key]
    }
    return memo
  }, {})
}

const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))

const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))

// Partials
// Lazy clean
const cleanL = (obj) => omit(obj, ['age'])

// Guarded clean
const cleanG = (obj) => pick(obj, ['fname', 'lname'])


// "App"
const credentials = {
    fname:"xyz",
    lname:"abc",
    age:23
}

const omitted = omit(credentials, ['age'])
const picked = pick(credentials, ['age'])
const cleanedL = cleanL(credentials)
const cleanedG = cleanG(credentials)

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

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

push object into array

Create an array of object like this:

var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;

First you create the object inside of the push method and then return the newly created array.

Returning Promises from Vuex actions

actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.

Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously

actions: {
    myAction(context, data) {
        return new Promise((resolve, reject) => {
            // Do something here... lets say, a http call using vue-resource
            this.$http("/api/something").then(response => {
                // http success, call the mutator and change something in state
                resolve(response);  // Let the calling function know that http is done. You may send some data back
            }, error => {
                // http failed, let the calling function know that action did not work out
                reject(error);
            })
        })
    }
}

Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:

export default {
    mounted: function() {
        // This component just got created. Lets fetch some data here using an action
        this.$store.dispatch("myAction").then(response => {
            console.log("Got some data, now lets show something in this component")
        }, error => {
            console.error("Got nothing from server. Prompt user to check internet connection and try again")
        })
    }
}

As you can see above, it is highly beneficial for actions to return a Promise. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.

And a last note regarding mutators - as you rightly pointed out, they are synchronous. They change stuff in the state, and are usually called from actions. There is no need to mix Promises with mutators, as the actions handle that part.

Edit: My views on the Vuex cycle of uni-directional data flow:

If you access data like this.$store.state["your data key"] in your components, then the data flow is uni-directional.

The promise from action is only to let the component know that action is complete.

The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"] which is unidirectional and follows the vuex data lifecycle.

The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data), once the http call is completed in your action.

How to loop an object in React?

The problem is the way you're using forEach(), as it will always return undefined. You're probably looking for the map() method, which returns a new array:

var tifOptions = Object.keys(tifs).map(function(key) {
    return <option value={key}>{tifs[key]}</option>
});

If you still want to use forEach(), you'd have to do something like this:

var tifOptions = [];

Object.keys(tifs).forEach(function(key) {
    tifOptions.push(<option value={key}>{tifs[key]}</option>);
});

Update:

If you're writing ES6, you can accomplish the same thing a bit neater using an arrow function:

const tifOptions = Object.keys(tifs).map(key => 
    <option value={key}>{tifs[key]}</option>
)

Here's a fiddle showing all options mentioned above: https://jsfiddle.net/fs7sagep/

Add key value pair to all objects in array

You may also try this:

arrOfObj.forEach(function(item){item.isActive = true;});

console.log(arrOfObj);

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

When your app and the libraries it references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture

To avoid this limitation you have to configure your app for multidex

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 21 
        multiDexEnabled true
    }
    ...   
}

Else, if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:

1.Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        multiDexEnabled true
    }
    ...
 }

dependencies {
        implementation 'com.android.support:multidex:1.0.3'
}

2.Depending on whether you override the Application class, perform one of the following:

  • If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:

    <application
        android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
  • Else If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:

   public class MyApplication extends MultiDexApplication { ... }
  • Else you do override the Application class but it's not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:

   public class MyApplication extends SomeOtherApplication {
     @Override
     protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
     }
   }

React - Preventing Form Submission

No JS needed really ... Just add a type attribute to the button with a value of button

<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>&nbsp;

By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any). Changing the type to "button" prevents that.

Angular2: Cannot read property 'name' of undefined

This line

<h2>{{hero.name}} details!</h2>

is outside *ngFor and there is no hero therefore hero.name fails.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

angular2: how to copy object into another object

Solution

Angular2 developed on the ground of modern technologies like TypeScript and ES6.

So you can just do let copy = Object.assign({}, myObject).

Object assign - nice examples.

For nested objects : let copy = JSON.parse(JSON.stringify(myObject))

Python/Json:Expecting property name enclosed in double quotes

As the other answers explain well the error occurs because of invalid quote characters passed to the json module.

In my case I continued to get the ValueError even after replacing ' with " in my string. What I finally realized was that some quote-like unicode symbols had found their way into my string:

 “  ”  '  ’  ‘  `  ´  "  ' 

To clean all of these you can just pass your string through a regular expression:

import re

raw_string = '{“key”:“value”}'

parsed_string = re.sub(r"[“|”|'|’|‘|`|´|"|'|']", '"', my_string)

json_object = json.loads(parsed_string)

How do I mock a REST template exchange?

This is an example with the non deprecated ArgumentMatchers class

when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                ArgumentMatchers.any(HttpMethod.class),
                ArgumentMatchers.any(),
                ArgumentMatchers.<Class<String>>any()))
             .thenReturn(responseEntity);

How can I change the user on Git Bash?

If you want to change the user at git Bash .You just need to configure particular user and email(globally) at the git bash.

$ git config --global user.name "abhi"
$ git config --global user.email "[email protected]"

Note: No need to delete the user from Keychain .

Angular 2 declaring an array of objects

Datatype: array_name:datatype[]=[]; Example string: users:string[]=[];

For array of objects:

Objecttype: object_name:objecttype[]=[{}]; Example user: Users:user[]=[{}];

And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit().

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.

The trick is to use --trustedhost to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.

So in a nutshell, you should do:

pip install python-certifi-win32 -trustedhost pypi.org

and after that you should be good to go

npm ERR! Error: EPERM: operation not permitted, rename

This might be due to your Antivirus software. If you can not disable AV then you can try modifying your NPM global install location as node installs into APPDATA directory which is actively monitored by AV Engines. Try running following commands-

npm config set prefix "YOUR CUSTOM LOCATION" npm config set cache "YOUR CUSTOM LOCATION"

Delete node_modules directory and install your package again.

Error: Unexpected value 'undefined' imported by the module

This can be caused by multiple scenarios like

  1. Missing commas
imports: [
    BrowserModule
   ,routing <= Missing Comma
   ,FeatureComponentsModule
  ],
  1. Double Commas
imports: [
    BrowserModule, 
   ,routing <=Double Comma
   ,FeatureComponentsModule
  ],
  1. Exporting Nothing from the Module
  2. Syntax errors
  3. Typo Errors
  4. Semicolons inside Objects, Arrays
  5. Incorrect import Statements

How do I access Configuration in any class in ASP.NET Core?

In ASP.NET Core, there are configuration providers for reading configurations from almost anywhere such as files e.g. JSON, INI or XML, environment variables, Azure key vault, command-line arguments, etc. and many more sources. I have written a step by step guide to show you how can you configure your application settings in various files such as JSON, INI or XML and how can you read those settings from your application code. I will also demonstrate how can you read application settings as custom .NET types (classes) and how can you use the built-in ASP.NET Core dependency injection to read your configuration settings in multiple classes, services or even projects available in your solution.

Read A Step by Step Guide for ASP.NET Core Configuration

How to register multiple implementations of the same interface in Asp.Net Core?

I know this post is a couple years old, but I keep running into this and I'm not happy with the service locator pattern.

Also, I know the OP is looking for an implementation which allows you to choose a concrete implementation based on a string. I also realize that the OP is specifically asking for an implementation of an identical interface. The solution I'm about to describe relies on adding a generic type parameter to your interface. The problem is that you don't have any real use for the type parameter other than service collection binding. I'll try to describe a situation which might require something like this.

Imagine configuration for such a scenario in appsettings.json which might look something like this (this is just for demonstration, your configuration can come from wherever you want as long as you have the correction configuration provider):

{
  "sqlDataSource": {
    "connectionString": "Data Source=localhost; Initial catalog=Foo; Connection Timeout=5; Encrypt=True;",
    "username": "foo",
    "password": "this normally comes from a secure source, but putting here for demonstration purposes"
  },
  "mongoDataSource": {
    "hostName": "uw1-mngo01-cl08.company.net",
    "port": 27026,
    "collection": "foo"
  }
}

You really need a type that represents each of your configuration options:

public class SqlDataSource
{
  public string ConnectionString { get;set; }
  public string Username { get;set; }
  public string Password { get;set; }
}

public class MongoDataSource
{
  public string HostName { get;set; }
  public string Port { get;set; }
  public string Collection { get;set; }
}

Now, I know that it might seem a little contrived to have two implementations of the same interface, but it I've definitely seen it in more than one case. The ones I usually come across are:

  1. When migrating from one data store to another, it's useful to be able to implement the same logical operations using the same interfaces so that you don't need to change the calling code. This also allows you to add configuration which swaps between different implementations at runtime (which can be useful for rollback).
  2. When using the decorator pattern. The reason you might use that pattern is that you want to add functionality without changing the interface and fall back to the existing functionality in certain cases (I've used it when adding caching to repository classes because I want circuit breaker-like logic around connections to the cache that fall back to the base repository -- this gives me optimal behavior when the cache is available, but behavior that still functions when it's not).

Anyway, you can reference them by adding a type parameter to your service interface so that you can implement the different implementations:

public interface IService<T> {
  void DoServiceOperation();
}

public class MongoService : IService<MongoDataSource> {
  private readonly MongoDataSource _options;

  public FooService(IOptionsMonitor<MongoDataSource> serviceOptions){
    _options = serviceOptions.CurrentValue
  }

  void DoServiceOperation(){
    //do something with your mongo data source options (connect to database)
    throw new NotImplementedException();
  }
}

public class SqlService : IService<SqlDataSource> {
  private readonly SqlDataSource_options;

  public SqlService (IOptionsMonitor<SqlDataSource> serviceOptions){
    _options = serviceOptions.CurrentValue
  }

  void DoServiceOperation(){
    //do something with your sql data source options (connect to database)
    throw new NotImplementedException();
  }
}

In startup, you'd register these with the following code:

services.Configure<SqlDataSource>(configurationSection.GetSection("sqlDataSource"));
services.Configure<MongoDataSource>(configurationSection.GetSection("mongoDataSource"));

services.AddTransient<IService<SqlDataSource>, SqlService>();
services.AddTransient<IService<MongoDataSource>, MongoService>();

Finally in the class which relies on the Service with a different connection, you just take a dependency on the service you need and the DI framework will take care of the rest:

[Route("api/v1)]
[ApiController]
public class ControllerWhichNeedsMongoService {  
  private readonly IService<MongoDataSource> _mongoService;
  private readonly IService<SqlDataSource> _sqlService ;

  public class ControllerWhichNeedsMongoService(
    IService<MongoDataSource> mongoService, 
    IService<SqlDataSource> sqlService
  )
  {
    _mongoService = mongoService;
    _sqlService = sqlService;
  }

  [HttpGet]
  [Route("demo")]
  public async Task GetStuff()
  {
    if(useMongo)
    {
       await _mongoService.DoServiceOperation();
    }
    await _sqlService.DoServiceOperation();
  }
}

These implementations can even take a dependency on each other. The other big benefit is that you get compile-time binding so any refactoring tools will work correctly.

Hope this helps someone in the future.

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Angular get object from array by Id

CASE - 1

Using array.filter() We can get an array of objects which will match with our condition.
see the working example.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function filter(){
  console.clear();
  var filter_id = document.getElementById("filter").value;
  var filter_array = questions.filter(x => x.id == filter_id);
  console.log(filter_array);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
}
_x000D_
<div>
  <label for="filter"></label>
  <input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
  <button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_

CASE - 2

Using array.find() we can get first matched item and break the iteration.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function find(){
  console.clear();
  var find_id = document.getElementById("find").value;
  var find_object = questions.find(x => x.id == find_id);
  console.log(find_object);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
  width: 200px;
}
_x000D_
<div>
  <label for="find"></label>
  <input id="find" type="number" name="find" placeholder="Enter id which you want to find">
  <button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_

Swift 3 - Comparing Date objects

To compare date only with year - month - day and without time for me worked like this:

     let order = Calendar.current.compare(self.startDate, to: compareDate!, toGranularity: .day)  

                      switch order {
                        case .orderedAscending:
                            print("\(gpsDate) is after \(self.startDate)")
                        case .orderedDescending:
                            print("\(gpsDate) is before \(self.startDate)")
                        default:
                            print("\(gpsDate) is the same as \(self.startDate)")
                        }

Add property to an array of objects

  Object.defineProperty(Results, "Active", {value : 'true',
                       writable : true,
                       enumerable : true,
                       configurable : true});

Create a global variable in TypeScript

As an addon to Dima V's answer this is what I did to make this work for me.

// First declare the window global outside the class

declare let window: any;

// Inside the required class method

let globVarName = window.globVarName;

Can't push to the heroku

You need to follow the instructions displayed here, on your case follow scala configuration:

https://devcenter.heroku.com/articles/getting-started-with-scala#introduction

After setting up the getting started pack, tweak around the default config and apply to your local repository. It should work, just like mine using NodeJS.

HTH! :)

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

How to discard local changes and pull latest from GitHub repository

If you already committed the changes than you would have to revert changes.

If you didn't commit yet, just do a clean checkout git checkout .

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

Ran into a similar issues, for me the problem was that I had different AWS keys set in my bash_profile.

I answered a similar question here: https://stackoverflow.com/a/57317494/11871462

If you have conflicting AWS keys in your bash_profile, AWS CLI defaults to these instead.

How do I filter date range in DataTables?

Follow the link below and configure it to what you need. Daterangepicker does it for you, very easily. :)

http://www.daterangepicker.com/#ex1

How to search for an element in a golang slice

You can use sort.Slice() plus sort.Search()

type Person struct {
    Name string
}

func main() {
    crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}

    sort.Slice(crowd, func(i, j int) bool {
        return crowd[i].Name <= crowd[j].Name
    })

    needle := "Benni"
    idx := sort.Search(len(crowd), func(i int) bool {
        return string(crowd[i].Name) >= needle
    })

    if crowd[idx].Name == needle {
        fmt.Println("Found:", idx, crowd[idx])
    } else {
        fmt.Println("Found noting: ", idx)
    }
}

See: https://play.golang.org/p/47OPrjKb0g_c

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

  • nchar is fixed-length and can hold unicode characters. it uses two bytes storage per character.

  • varchar is of variable length and cannot hold unicode characters. it uses one byte storage per character.

"Logging out" of phpMyAdmin?

Simple seven step to solve issue in case of WampServer:

  1. Start WampServer
  2. Click on Folder icon Mysql -> Mysql Console
  3. Press Key Enter without password
  4. Execute Statement

    SET PASSWORD FOR root@localhost=PASSWORD('root');
    
  5. open D:\wamp\apps\phpmyadmin4.1.14\config.inc.php file set value

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = '';
    
  6. Restart All services

  7. Open phpMyAdmin in browser enter user root and pass root

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

For Windows 10 / Windows Server 2016 use the following command:

dism /online /enable-feature /featurename:IIS-ASPNET45 /all

The suggested answers with aspnet_regiis doesn't work on Windows 10 (Creators Update and later) or Windows Server 2016:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.0).
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
Finished installing ASP.NET (4.0.30319.0).

Interestingly, the "Turn Windows Features On/Off" dialog didn't allow me to untick .NET nor ASP.NET 4.6, and only the above DISM command worked. Not sure whether the featurename is correct, but it worked for me.

What is a constant reference? (not a reference to a constant)

The clearest answer. Does “X& const x” make any sense?

No, it is nonsense

To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.

In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.

Hive External Table Skip First Row

I also struggled with this and found no way to tell hive to skip first row, like there is e.g. in Greenplum. So finally I had to remove it from the files. e.g. "cat File.csv | grep -v RecordId > File_no_header.csv"

.trim() in JavaScript not working in IE

jQuery:

$.trim( $("#mycomment").val() );

Someone uses $("#mycomment").val().trim(); but this will not work on IE.

How to check if a character is upper-case in Python?

You can use this code:

def is_valid(string):
    words = string.split('_')
    for word in words:
        if not word.istitle():
            return False, word
    return True, words
x="Alpha_beta_Gamma"
assert is_valid(x)==(False,'beta')
x="Alpha_Beta_Gamma"
assert is_valid(x)==(True,['Alpha', 'Beta', 'Gamma'])

This way you know if is valid and what word is wrong

How to set a Header field on POST a form?

In fact a better way to do it to save a cookie on the client side. Then the cookie is automatically sent with every page header for that particular domain.

In node-js, you can set up and use cookies with cookie-parser.

an example:

res.cookie('token', "xyz....", { httpOnly: true });

Now you can access this :

app.get('/',function(req, res){
 var token = req.cookies.token
});

Note that httpOnly:true ensures that the cookie is usually not accessible manually or through javascript and only browser can access it. If you want to send some headers or security tokens with a form post, and not through ajax, in most situation this can be considered a secure way. Although make sure that the data is sent over secure protocol /ssl if you are storing some sensitive user related info which is usually the case.

Random number from a range in a Bash Script

shuf -i 2000-65000 -n 1

Enjoy!

Edit: The range is inclusive.

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

How to print the array?

It looks like you have a typo on your array, it should read:

int my_array[3][3] = {...

You don't have the _ or the {.

Also my_array[3][3] is an invalid location. Since computers begin counting at 0, you are accessing position 4. (Arrays are weird like that).

If you want just the last element:

printf("%d\n", my_array[2][2]);

If you want the entire array:

for(int i = 0; i < my_array.length; i++) {
  for(int j = 0; j < my_array[i].length; j++)
    printf("%d ", my_array[i][j]);
  printf("\n");
}

How to use Java property files?

There are many ways to create and read properties files:

  1. Store the file in the same package.
  2. Recommend .properties extension however you can choose your own.
  3. Use theses classes located at java.util package => Properties, ListResourceBundle, ResourceBundle classes.
  4. To read properties, use iterator or enumerator or direct methods of Properties or java.lang.System class.

ResourceBundle class:

 ResourceBundle rb = ResourceBundle.getBundle("prop"); // prop.properties
 System.out.println(rb.getString("key"));

Properties class:

Properties ps = new Properties();
ps.Load(new java.io.FileInputStream("my.properties"));

Creating a Custom Event

Declare the class containing the event:

class MyClass {
    public event EventHandler MyEvent;

    public void Method() {
        OnEvent();
    }

    private void OnEvent() {
        if (MyEvent != null) {
            MyEvent(this, EventArgs.Empty);
        }
    }
}

Use it like this:

MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();

How to import RecyclerView for Android L-preview

Other answers did not work for me. I had to add this line:

compile 'com.android.support:recyclerview-v7:21.0.0'

What's the best way to limit text length of EditText in Android

This is a custom EditText Class that allow Length filter to live along with other filters. Thanks to Tim Gallagher's Answer (below)

import android.content.Context;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.widget.EditText;


public class EditTextMultiFiltering extends EditText{

    public EditTextMultiFiltering(Context context) {
        super(context);
    }

    public EditTextMultiFiltering(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditTextMultiFiltering(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setMaxLength(int length) {
        InputFilter curFilters[];
        InputFilter.LengthFilter lengthFilter;
        int idx;

        lengthFilter = new InputFilter.LengthFilter(length);

        curFilters = this.getFilters();
        if (curFilters != null) {
            for (idx = 0; idx < curFilters.length; idx++) {
                if (curFilters[idx] instanceof InputFilter.LengthFilter) {
                    curFilters[idx] = lengthFilter;
                    return;
                }
            }

            // since the length filter was not part of the list, but
            // there are filters, then add the length filter
            InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
            System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
            newFilters[curFilters.length] = lengthFilter;
            this.setFilters(newFilters);
        } else {
            this.setFilters(new InputFilter[] { lengthFilter });
        }
    }
}

Hibernate openSession() vs getCurrentSession()

As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context - you don't need to close this.

If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.

You should never use one session per web app - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

1) Server.MapPath(".") -- Returns the "Current Physical Directory" of the file (e.g. aspx) being executed.

Ex. Suppose D:\WebApplications\Collage\Departments

2) Server.MapPath("..") -- Returns the "Parent Directory"

Ex. D:\WebApplications\Collage

3) Server.MapPath("~") -- Returns the "Physical Path to the Root of the Application"

Ex. D:\WebApplications\Collage

4) Server.MapPath("/") -- Returns the physical path to the root of the Domain Name

Ex. C:\Inetpub\wwwroot

sys.argv[1], IndexError: list index out of range

I've done some research and it seems that the sys.argv might require an argument at the command line when running the script

Not might, but definitely requires. That's the whole point of sys.argv, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError.

Although the code uses try/except to trap some errors, the offending statement occurs in the first line.

So the script needs a directory name, and you can test if there is one by looking at len(sys.argv) and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.

To print an error and exit when the argument is missing, add this line before the first use of sys.argv:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

sys.argv[0] always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...

see also:

What is path of JDK on Mac ?

Have a look and see if the the JDK is at:

Library/Java/JavaVirtualMachines/ Or /System/Library/Java/JavaVirtualMachines/

Check this earlier SO post: JDK on OSX 10.7 Lion

Printing PDFs from Windows Command Line

I had two problems with using Acrobat Reader for this task.

  1. The command line API is not officially supported, so it could change or be removed without warning.
  2. Send a print command to Reader loads up the GUI, with seemingly no way to prevent it. I needed the process to be transparent to the user.

I stumbled across this blog, that suggests using Foxit Reader. Foxit Reader is free, the API is almost identical to Acrobat Reader, but crucially is documented and does not load the GUI for print jobs.

A word of warning, don't just click through the install process without paying attention, it tries to install unrelated software as well. Why are software vendors still doing this???

How to prevent Browser cache on Angular 2 site?

angular-cli resolves this by providing an --output-hashing flag for the build command (versions 6/7, for later versions see here). Example usage:

ng build --output-hashing=all

Bundling & Tree-Shaking provides some details and context. Running ng help build, documents the flag:

--output-hashing=none|all|media|bundles (String)

Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>

Although this is only applicable to users of angular-cli, it works brilliantly and doesn't require any code changes or additional tooling.

Update

A number of comments have helpfully and correctly pointed out that this answer adds a hash to the .js files but does nothing for index.html. It is therefore entirely possible that index.html remains cached after ng build cache busts the .js files.

At this point I'll defer to How do we control web page caching, across all browsers?

How to make a text box have rounded corners?

This can be done with CSS3:

<input type="text" />

input
{
  -moz-border-radius: 15px;
 border-radius: 15px;
    border:solid 1px black;
    padding:5px;
}

http://jsfiddle.net/UbSkn/1/


However, an alternative would be to put the input inside a div with a rounded background, and no border on the input

Getting the current Fragment instance in the viewpager

by selecting an option, I need to update the fragment that is currently visible.

To get a reference to currently visible fragment, assume you have a reference to ViewPager as mPager. Then following steps will get a reference to currentFragment:

  1. PageAdapter adapter = mPager.getAdapter();
  2. int fragmentIndex = mPager.getCurrentItem();
  3. FragmentStatePagerAdapter fspa = (FragmentStatePagerAdapter)adapter;
  4. Fragment currentFragment = fspa.getItem(fragmentIndex);

The only cast used line 3 is valid usually. FragmentStatePagerAdapter is an useful adapter for a ViewPager.

Check if number is decimal

The function you posted is just not PHP.

Have a look at is_float [docs].

Edit: I missed the "user entered value" part. In this case you can actually use a regular expression:

^\d+\.\d+$

Android Studio build fails with "Task '' not found in root project 'MyProject'."

This is what I did

  1. Remove .idea folder

    $ mv .idea .idea.bak

  2. Import the project again

ASP.NET Identity reset password

In case of password reset, it is recommended to reset it through sending password reset token to registered user email and ask user to provide new password. If have created a easily usable .NET library over Identity framework with default configuration settins. You can find details at blog link and source code at github.

Arrays.asList() of an array

This works from Java 5 to 7:

public int getTheNumber(Integer... factors) {
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));
    Collections.sort(f);
    return f.get(0)*f.get(f.size()-1);
}

In Java 4 there is no vararg... :-)

Javascript extends class

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript

Loading/Downloading image from URL on Swift

Swift 4.1 I have crated a function just pass image url, cache key after image is generated set it to completion block.

   class NetworkManager: NSObject {

  private var imageQueue = OperationQueue()
  private var imageCache = NSCache<AnyObject, AnyObject>()

  func downloadImageWithUrl(imageUrl: String, cacheKey: String, completionBlock: @escaping (_ image: UIImage?)-> Void) {

    let downloadedImage = imageCache.object(forKey: cacheKey as AnyObject)
    if let  _ = downloadedImage as? UIImage {
      completionBlock(downloadedImage as? UIImage)
    } else {
      let blockOperation = BlockOperation()
      blockOperation.addExecutionBlock({
        let url = URL(string: imageUrl)
        do {
          let data = try Data(contentsOf: url!)
          let newImage = UIImage(data: data)
          if newImage != nil {
            self.imageCache.setObject(newImage!, forKey: cacheKey as AnyObject)
            self.runOnMainThread {
              completionBlock(newImage)
            }
          } else {
            completionBlock(nil)
          }
        } catch {
          completionBlock(nil)
        }
      })
      self.imageQueue.addOperation(blockOperation)
      blockOperation.completionBlock = {
        print("Image downloaded \(cacheKey)")
      }
    }
  }
}
extension NetworkManager {
  fileprivate func runOnMainThread(block:@escaping ()->Void) {
    if Thread.isMainThread {
      block()
    } else {
      let mainQueue = OperationQueue.main
      mainQueue.addOperation({
        block()
      })
    }
  }
}

"Thinking in AngularJS" if I have a jQuery background?

To describe the "paradigm shift", I think a short answer can suffice.

AngularJS changes the way you find elements

In jQuery, you typically use selectors to find elements, and then wire them up:
$('#id .class').click(doStuff);

In AngularJS, you use directives to mark the elements directly, to wire them up:
<a ng-click="doStuff()">

AngularJS doesn't need (or want) you to find elements using selectors - the primary difference between AngularJS's jqLite versus full-blown jQuery is that jqLite does not support selectors.

So when people say "don't include jQuery at all", it's mainly because they don't want you to use selectors; they want you to learn to use directives instead. Direct, not select!

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

What I did was run the following commands from nodejs command prompt while in the project folder directory:

  1. npm init
  2. npm install -g webpack
  3. npm install --save react react-dom @types/react @types/react-dom
  4. npm install --save-dev typescript awesome-typescript-loader source-map-loader
  5. npm install ajv@^6.0.0
  6. npm i react-html-id
  7. import the package(in node modules) in App.js file by adding the code: import UniqueId from 'react-html-id';

I did the above(although I already had npm installed) and it worked!

The 'json' native gem requires installed build tools

Followed the steps.

  1. Extract DevKit to path C:\Ruby193\DevKit
  2. cd C:\Ruby192\DevKit
  3. ruby dk.rb init
  4. ruby dk.rb review
  5. ruby dk.rb install

Then I wrote the command

gem install rails -r -y

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

Regular Expression for matching parentheses

Two options:

Firstly, you can escape it using a backslash -- \(

Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]

How to use npm with node.exe?

Use a Windows Package manager like chocolatey. First install chocolatey as indicated on it's homepage. That should be a breeze

Then, to install Node JS (Install), run the following command from the command line or from PowerShell:

C:> cinst nodejs.install

How to access remote server with local phpMyAdmin client?

I would have added this as a comment, but my reputation is not yet high enough.

Under version 4.5.4.1deb2ubuntu2, and I am guessing any other versions 4.5.x or newer. There is no need to modify the config.inc.php file at all. Instead go one more directory down conf.d.

Create a new file with the '.php' extension and add the lines. This is a better modularized approach and isolates each remote database server access information.

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

Handling polymorphism is either model-bound or requires lots of code with various custom deserializers. I'm a co-author of a JSON Dynamic Deserialization Library that allows for model-independent json deserialization library. The solution to OP's problem can be found below. Note that the rules are declared in a very brief manner.

public class SOAnswer {
    @ToString @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static abstract class Animal {
        private String name;    
    }

    @ToString(callSuper = true) @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static class Dog extends Animal {
        private String breed;
    }

    @ToString(callSuper = true) @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static class Cat extends Animal {
        private String favoriteToy;
    }
    
    
    public static void main(String[] args) {
        String json = "[{"
                + "    \"name\": \"pluto\","
                + "    \"breed\": \"dalmatian\""
                + "},{"
                + "    \"name\": \"whiskers\","
                + "    \"favoriteToy\": \"mouse\""
                + "}]";
        
        // create a deserializer instance
        DynamicObjectDeserializer deserializer = new DynamicObjectDeserializer();
        
        // runtime-configure deserialization rules; 
        // condition is bound to the existence of a field, but it could be any Predicate
        deserializer.addRule(DeserializationRuleFactory.newRule(1, 
                (e) -> e.getJsonNode().has("breed"),
                DeserializationActionFactory.objectToType(Dog.class)));
        
        deserializer.addRule(DeserializationRuleFactory.newRule(1, 
                (e) -> e.getJsonNode().has("favoriteToy"),
                DeserializationActionFactory.objectToType(Cat.class)));
        
        List<Animal> deserializedAnimals = deserializer.deserializeArray(json, Animal.class);
        
        for (Animal animal : deserializedAnimals) {
            System.out.println("Deserialized Animal Class: " + animal.getClass().getSimpleName()+";\t value: "+animal.toString());
        }
    }
}

Maven depenendency for pretius-jddl (check newest version at maven.org/jddl:

<dependency>
  <groupId>com.pretius</groupId>
  <artifactId>jddl</artifactId>
  <version>1.0.0</version>
</dependency>

How to determine if string contains specific substring within the first X characters

shorter version:

found = Value1.StartsWith("abc");

sorry, but I am a stickler for 'less' code.


Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith

public static class StackOverflowExtensions
{
    public static bool StartsWith(this String val, string findString, int count)
    {
        return val.Substring(0, count).Contains(findString);
    }
}

Java character array initializer

you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.

or even simpler just use String.charAt() in the loop to populate array like below:

String ini="Hi there";
  char[] array=new  char[ini.length()];

  for(int count=0;count<array.length;count++){
         array[count] = ini.charAt(count);
  System.out.print(" "+array[count]);
  }

or one liner would be

  String ini="Hi there";
  char[] array=ini.toCharArray();

What does a just-in-time (JIT) compiler do?

A just in time compiler (JIT) is a piece of software which takes receives an non executable input and returns the appropriate machine code to be executed. For example:

Intermediate representation    JIT    Native machine code for the current CPU architecture

     Java bytecode            --->        machine code
     Javascript (run with V8) --->        machine code

The consequence of this is that for a certain CPU architecture the appropriate JIT compiler must be installed.

Difference compiler, interpreter, and JIT

Although there can be exceptions in general when we want to transform source code into machine code we can use:

  1. Compiler: Takes source code and returns a executable
  2. Interpreter: Executes the program instruction by instruction. It takes an executable segment of the source code and turns that segment into machine instructions. This process is repeated until all source code is transformed into machine instructions and executed.
  3. JIT: Many different implementations of a JIT are possible, however a JIT is usually a combination of a compliler and an interpreter. The JIT first turn intermediary data (e.g. Java bytecode) which it receives into machine language via interpretation. A JIT can often sense when a certain part of the code is executed often and the will compile this part for faster execution.

How to give a user only select permission on a database

You can use Create USer to create a user

CREATE LOGIN sam
    WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO 

and to Grant (Read-only access) you can use the following

GRANT SELECT TO sam

Hope that helps.

Remove a fixed prefix/suffix from a string in Bash

$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor

This is documented in the Shell Parameter Expansion section of the manual:

${parameter#word}
${parameter##word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. […]

${parameter%word}
${parameter%%word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. […]

In LaTeX, how can one add a header/footer in the document class Letter?

After I removed

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

it seems to have worked "correctly".

It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.

FYI: MikTeX 2.7 under Vista

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

Windows batch file file download from a URL

Instead of wget you can also use aria2 to download the file from a particular URL.

See the following link which will explain more about aria2:

https://aria2.github.io/

Using Mysql in the command line in osx - command not found?

You have to create a symlink to your mysql installation if it is not the most recent version of mysql.

$ brew link --force [email protected]

see this post by Alex Todd

Embed an External Page Without an Iframe?

You could load the external page with jquery:

<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script>
<div id="testLoad"></div>
//would this help

How do I use a custom Serializer with Jackson?

You can put @JsonSerialize(using = CustomDateSerializer.class) over any date field of object to be serialized.

public class CustomDateSerializer extends SerializerBase<Date> {

    public CustomDateSerializer() {
        super(Date.class, true);
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)");
        String format = formatter.format(value);
        jgen.writeString(format);
    }

}

How to change line width in ggplot?

Whilst @Didzis has the correct answer, I will expand on a few points

Aesthetics can be set or mapped within a ggplot call.

  • An aesthetic defined within aes(...) is mapped from the data, and a legend created.

  • An aesthetic may also be set to a single value, by defining it outside aes().

As far as I can tell, what you want is to set size to a single value, not map within the call to aes()

When you call aes(size = 2) it creates a variable called `2` and uses that to create the size, mapping it from a constant value as it is within a call to aes (thus it appears in your legend).

Using size = 1 (and without reg_labeller which is perhaps defined somewhere in your script)

Figure29 +
    geom_line(aes(group=factor(tradlib)),size=1) +
    facet_grid(regionsFull~., scales="free_y") +
    scale_colour_brewer(type = "div") +
    theme(axis.text.x = element_text(
          colour = 'black', angle = 90, size = 13,
          hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
    ylab("FSI (%Change)") +
    theme(axis.text.y = element_text(colour = 'black', size = 12), 
          axis.title.y = element_text(size = 12, 
          hjust = 0.5, vjust = 0.2)) + 
    theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust =    0.5, face = 'bold'))

enter image description here

and with size = 2

 Figure29 + 
     geom_line(aes(group=factor(tradlib)),size=2) +
     facet_grid(regionsFull~., scales="free_y") + 
     scale_colour_brewer(type = "div") +
     theme(axis.text.x = element_text(colour = 'black', angle = 90,
          size = 13, hjust = 0.5, vjust = 
          0.5),axis.title.x=element_blank()) + 
     ylab("FSI (%Change)") +
     theme(axis.text.y = element_text(colour = 'black', size = 12),
          axis.title.y = element_text(size = 12,
          hjust = 0.5, vjust = 0.2)) + 
      theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust = 0.5, face = 'bold'))

enter image description here

You can now define the size to work appropriately with the final image size and device type.

CSS3 Transform Skew One Side

Maybe you want to use CSS "clip-path" (Works with transparency and background)

"clip-path" reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path

Generator: http://bennettfeely.com/clippy/

Example:

_x000D_
_x000D_
/* With percent */_x000D_
.element-percent {_x000D_
  background: red;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
  background: blue;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With background */_x000D_
.element-background {_x000D_
  background: url(https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260) no-repeat center/cover;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}
_x000D_
<div class="element-percent"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-pixel"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-background"></div>
_x000D_
_x000D_
_x000D_

Shortest way to print current year in a website

TJ's answer is excellent but I ran into one scenario where my HTML was already rendered and the document.write script would overwrite all of the page contents with just the date year.

For this scenario, you can append a text node to the existing element using the following code:

<div>
    &copy;
    <span id="copyright">
        <script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
    </span>
    Company Name
</div>

Unable to open a file with fopen()

Your executable's working directory is probably set to something other than the directory where it is saved. Check your IDE settings.

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

Using os.walk() to recursively traverse directories in Python

Recursive walk through a directory where you get ALL files from all dirs in the current directory and you get ALL dirs from the current directory - because codes above don't have a simplicity (imho):

for root, dirs, files in os.walk(rootFolderPath):
    for filename in files:
        doSomethingWithFile(os.path.join(root, filename))
    for dirname in dirs:
        doSomewthingWithDir(os.path.join(root, dirname))

Automatically deleting related rows in Laravel (Eloquent ORM)

Relation in User model:

public function photos()
{
    return $this->hasMany('Photo');
}

Delete record and related:

$user = User::find($id);

// delete related   
$user->photos()->delete();

$user->delete();

How do I interpret precision and scale of a number in a database?

Precision, Scale, and Length in the SQL Server 2000 documentation reads:

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

error running apache after xampp install

After changing main port from 80 to 8080 you have to change the config in XAMPP control panel as I show in the images:

1) enter image description here

2) enter image description here

3) enter image description here

Then restart the service and that's it !

ClassCastException, casting Integer to Double

Changing an integer to a double

int abc=12; //setting up integer "abc"

System.out.println((double)abc); 

The code will output integer "abc" as a double, which means that it will display as "12.0". Notice how there is a decimal place, indicating that this precision digit has been stored.

Same with double if you want to change it back,

double number=13.94;

System.out.println((int)number); 

This code will print on one line, "number" as an integer. The output will be "13". Notice that the value has not been rounded up, the data has actually been omitted.

What is the easiest way to remove all packages installed by pip?

I wanted to elevate this answer out of a comment section because it's one of the most elegant solutions in the thread. Full credit for this answer goes to @joeb.

pip uninstall -y -r <(pip freeze)

This worked great for me for the use case of clearing my user packages folder outside the context of a virtualenv which many of the above answers don't handle.

Edit: Anyone know how to make this command work in a Makefile?

Bonus: A bash alias

I add this to my bash profile for convenience:

alias pipuninstallall="pip uninstall -y -r <(pip freeze)"

Then run:

pipuninstallall

Alternative for pipenv

If you happen to be using pipenv you can just run:

pipenv uninstall --all

How to POST the data from a modal form of Bootstrap?

I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
                    method="post"
                    action="abc.php">
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
                                    name="planform">

                </form>

You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {
        document.getElementById("paymentitrform").submit();
   }  

How to take complete backup of mysql database using mysqldump command line utility

It depends a bit on your version. Before 5.0.13 this is not possible with mysqldump.

From the mysqldump man page (v 5.1.30)

 --routines, -R

      Dump stored routines (functions and procedures) from the dumped
      databases. Use of this option requires the SELECT privilege for the
      mysql.proc table. The output generated by using --routines contains
      CREATE PROCEDURE and CREATE FUNCTION statements to re-create the
      routines. However, these statements do not include attributes such
      as the routine creation and modification timestamps. This means that
      when the routines are reloaded, they will be created with the
      timestamps equal to the reload time.
      ...

      This option was added in MySQL 5.0.13. Before that, stored routines
      are not dumped. Routine DEFINER values are not dumped until MySQL
      5.0.20. This means that before 5.0.20, when routines are reloaded,
      they will be created with the definer set to the reloading user. If
      you require routines to be re-created with their original definer,
      dump and load the contents of the mysql.proc table directly as
      described earlier.

Removing MySQL 5.7 Completely

Run these commands in the terminal:

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo apt-get autoremove

sudo apt-get autoclean

Run these commands separately as each command requires confirmation & if run as a block, the command below the one currently running will cancel the confirmation (leading to the command not being run).

Please refer to How do I uninstall Mysql?

How to add a progress bar to a shell script?

I prefer to use dialog with the --gauge param. Is used very often in .deb package installations and other basic configuration stuff of many distros. So you don't need to reinvent the wheel... again

Just put an int value from 1 to 100 @stdin. One basic and silly example:

for a in {1..100}; do sleep .1s; echo $a| dialog --gauge "waiting" 7 30; done

I have this /bin/Wait file (with chmod u+x perms) for cooking purposes :P

#!/bin/bash
INIT=`/bin/date +%s`
NOW=$INIT
FUTURE=`/bin/date -d "$1" +%s`
[ $FUTURE -a $FUTURE -eq $FUTURE ] || exit
DIFF=`echo "$FUTURE - $INIT"|bc -l`

while [ $INIT -le $FUTURE -a $NOW -lt $FUTURE ]; do
    NOW=`/bin/date +%s`
    STEP=`echo "$NOW - $INIT"|bc -l`
    SLEFT=`echo "$FUTURE - $NOW"|bc -l`
    MLEFT=`echo "scale=2;$SLEFT/60"|bc -l`
    TEXT="$SLEFT seconds left ($MLEFT minutes)";
    TITLE="Waiting $1: $2"
    sleep 1s
    PTG=`echo "scale=0;$STEP * 100 / $DIFF"|bc -l`
    echo $PTG| dialog --title "$TITLE" --gauge "$TEXT" 7 72
done

if [ "$2" == "" ]; then msg="Espera terminada: $1";audio="Listo";
else msg=$2;audio=$2;fi 

/usr/bin/notify-send --icon=stock_appointment-reminder-excl "$msg"
espeak -v spanish "$audio"

So I can put:

Wait "34 min" "warm up the oven"

or

Wait "dec 31" "happy new year"

Conversion between UTF-8 ArrayBuffer and String

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                                   ((char2 & 0x3F) << 6) |
                                   ((char3 & 0x3F) << 0));
        break;
    }
  }    
  return out;
}

It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.

Check out the JSFiddle demo.

Also see the related questions: here, here

Execute and get the output of a shell command in node.js

If you're using node later than 7.6 and you don't like the callback style, you can also use node-util's promisify function with async / await to get shell commands which read cleanly. Here's an example of the accepted answer, using this technique:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)

module.exports.getGitUser = async function getGitUser () {
  const name = await exec('git config --global user.name')
  const email = await exec('git config --global user.email')
  return { name, email }
};

This also has the added benefit of returning a rejected promise on failed commands, which can be handled with try / catch inside the async code.

How to change the font size on a matplotlib plot

Here is what I generally use in Jupyter Notebook:

# Jupyter Notebook settings

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
%autosave 0
%matplotlib inline
%load_ext autoreload
%autoreload 2

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"


# Imports for data analysis
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 2500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_colwidth', 2000)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)

#size=25
size=15
params = {'legend.fontsize': 'large',
          'figure.figsize': (20,8),
          'axes.labelsize': size,
          'axes.titlesize': size,
          'xtick.labelsize': size*0.75,
          'ytick.labelsize': size*0.75,
          'axes.titlepad': 25}
plt.rcParams.update(params)

How to serve up a JSON response using Go?

You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

How do I run Google Chrome as root?

It no longer suffices to start Chrome with --user-data-dir=/root/.config/google-chrome. It simply prints Aborted and ends (Chrome 48 on Ubuntu 12.04).

You need actually to run it as a non-root user. This you can do with

gksu -wu chrome-user google-chrome

where chrome-user is some user you've decided should be the one to run Chrome. Your Chrome user profile will be found at ~chrome-user/.config/google-chrome.

BTW, the old hack of changing all occurrences of geteuid to getppid in the chrome binary no longer works.

git: How to ignore all present untracked files?

-u no doesn't show unstaged files either. -uno works as desired and shows unstaged, but hides untracked.

Socket accept - "Too many open files"

Just another information about CentOS. In this case, when using "systemctl" to launch process. You have to modify the system file ==> /usr/lib/systemd/system/processName.service .Had this line in the file :

LimitNOFILE=50000

And just reload your system conf :

systemctl daemon-reload

Splitting comma separated string in a PL/SQL stored proc

create or replace procedure pro_ss(v_str varchar2) as
v_str1 varchar2(100); 
v_comma_pos number := 0;    
v_start_pos number := 1;
begin             
    loop        
    v_comma_pos := instr(v_str,',',v_start_pos);   
    if  v_comma_pos = 0 then     
      v_str1 := substr(v_str,v_start_pos);  
      dbms_output.put_line(v_str1);    
      exit;
      end if;    
    v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos)); 
    dbms_output.put_line(v_str1);       
    v_start_pos := v_comma_pos + 1;    
    end loop; 
end;
/

call pro_ss('aa,bb,cc,dd,ee,ff,gg,hh,ii,jj');

outout: aa bb cc dd ee ff gg hh ii jj

Tomcat starts but home page cannot open with url http://localhost:8080

If you have your tomcat started (in linux check with ps -ef | grep java) and you see it opened the port 8080 or the one you configured in server.xml (check with netstat --tcp -na | grep <port number>) but you still cannot access it in your browser check the following:

  1. It may start but with a delay of 3-5 minutes. Check the logs/catalina.out. You should see something like this when the server started completely.
    INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 38442 ms
    If you don't have this INFO line your server startup is not complete yet. The problem may occur due to the SecureRandom class responsible to provide random Session IDs and which can cause big delays during startup. Check more details and the solution here.
  2. Check your firewall (on linux iptables -L -n): You can try to reset your firewall completely iptables -F if you are not into an exposed environment. However, pay attention, that leaves you without protection therefore it can be dangerous.
  3. Check your selinux (if you are on linux).

These are some of the most forgotten and not obvious issues in having your Apache Tomcat up and running.

How to tell if browser/tab is active

I would try to set a flag on the window.onfocus and window.onblur events.

The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:

var isTabActive;

window.onfocus = function () { 
  isTabActive = true; 
}; 

window.onblur = function () { 
  isTabActive = false; 
}; 

// test
setInterval(function () { 
  console.log(window.isTabActive ? 'active' : 'inactive'); 
}, 1000);

Try it out here.

How to remove the underline for anchors(links)?

Don't forget to either include stylesheets using the link tag

http://www.w3schools.com/TAGS/tag_link.asp

Or enclose CSS within a style tag on your webpage.

<style>
  a { text-decoration:none; }
  p { text-decoration:underline; }
</style>

I wouldn't recommend using the underline on anything apart from links, underline is generally accepted as something that is clickable. If it isn't clickable don't underline it.

CSS basics can be picked up at w3schools

Specifying a custom DateTime format when serializing with Json.Net

public static JsonSerializerSettings JsonSerializer { get; set; } = new JsonSerializerSettings()
        {
            DateFormatString= "yyyy-MM-dd HH:mm:ss",
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new LowercaseContractResolver()
        };

Hello,

I'm using this property when I need set JsonSerializerSettings

How do I know which version of Javascript I'm using?

Click on this link to see which version your BROWSER is using: http://jsfiddle.net/Ac6CT/

You should be able filter by using script tags to each JS version.

<script type="text/javascript">
  var jsver = 1.0;
</script>
<script language="Javascript1.1">
  jsver = 1.1;
</script>
<script language="Javascript1.2">
  jsver = 1.2;
</script>
<script language="Javascript1.3">
  jsver = 1.3;
</script>
<script language="Javascript1.4">
  jsver = 1.4;
</script>
<script language="Javascript1.5">
  jsver = 1.5;
</script>
<script language="Javascript1.6">
  jsver = 1.6;
</script>
<script language="Javascript1.7">
  jsver = 1.7;
</script>
<script language="Javascript1.8">
  jsver = 1.8;
</script>
<script language="Javascript1.9">
  jsver = 1.9;
</script>

<script type="text/javascript">
  alert(jsver);
</script>

My Chrome reports 1.7

Blatantly stolen from: http://javascript.about.com/library/bljver.htm

How to run binary file in Linux

Or, the file is of a filetype and/or architecture that you just cannot run with your hardware and/or there is also no fallback binfmt_misc entry to handle the particular format in some other way. Use file(1) to determine.

Android read text raw resource file

This is another method which will definitely work, but I cant get it to read multiple text files to view in multiple textviews in a single activity, anyone can help?

TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
    helloTxt.setText(readTxt());
}

private String readTxt(){

 InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
try {
i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
  }
  inputStream.close();
} catch (IOException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}

 return byteArrayOutputStream.toString();
}

.gitignore exclude folder but include specific subfolder

@Chris Johnsen's answer is great, but with a newer versions of Git (1.8.2 or later), there is a double asterisk pattern you can leverage for a bit more shorthand solution:

# assuming the root folder you want to ignore is 'application'
application/**/*

# the subfolder(s) you want to track:
!application/language/gr/

This way you don't have to "unignore" parent directory of the subfolder you want to track.


With Git 2.17.0 (Not sure how early before this version. Possibly back to 1.8.2), using the ** pattern combined with excludes for each subdirectory leading up to your file(s) works. For example:

# assuming the root folder you want to ignore is 'application'
application/**

# Explicitly track certain content nested in the 'application' folder:
!application/language/
!application/language/gr/
!application/language/gr/** # Example adding all files & folder in the 'gr' folder
!application/language/gr/SomeFile.txt # Example adding specific file in the 'gr' folder

How to hide columns in HTML table?

_x000D_
_x000D_
<style>_x000D_
.hideFullColumn tr > .hidecol_x000D_
{_x000D_
    display:none;_x000D_
}_x000D_
</style>
_x000D_
_x000D_
_x000D_

use .hideFullColumn in table and .hidecol in th.You don't need to add class in td individually as it will be problem because index may not be in mind of each td.

How to configure PHP to send e-mail?

This will not work on a local host, but uploaded on a server, this code should do the trick. Just make sure to enter your own email address for the $to line.

<?php
if (isset($_POST['name']) && isset($_POST['email'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $to = '[email protected]';
    $subject = "New Message on YourWebsite.com";
    $body = '<html>
                <body>
                    <h2>Title</h2>
                    <br>
                    <p>Name:<br>'.$name.'</p>
                    <p>Email:<br>'.$email.'</p>

                </body>
            </html>';

//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers = "Reply-To: ".$email."\r\n";
$headers = "MIME-Version: 1.0\r\n";
$headers = "Content-type: text/html; charset=utf-8";

//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
    echo '<br>';
    echo "Success. Thanks for Your Message.";
} else {
    echo 'Error.';
}
}
?>

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="name" placeholder="Your Name"><br>
            <input type="text" name="email" placeholder="Your Email"><br>
            <button type="submit">Subscribe</button>
        </form>
    </body>
</html>

Python slice first and last element in list

first, last = some_list[0], some_list[-1]

Addition for BigDecimal

It looks like from the Java docs here that add returns a new BigDecimal:

BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);

Test method is inconclusive: Test wasn't run. Error?

I faced this problem in vs 2017 update 3 with Resharper Ultimate 2017.2

Restart vs or restart machine can't help.

I resolved the problem by clearing the Cache as follows:

    Resharper ->options-> Environment ->click the button 'Clear caches'

Update:

There is a button "error" (I find in Resharper 2018) in the upper right corner of the test window.

If you click the error button, it shows an error message that may help in resolving the problem.

To track the root of the problem, run Visual Studio in log mode. In vs 2017, Run the command:

      devenv /ReSharper.LogFile C:\temp\log\test_log.txt /ReSharper.LogLevel Verbose

Run the test.

Review the log file test_log.txt and search for 'error' in the file.

The log file is a great help to find the error that you can resolve or you can send the issue with the log file to the technical support team of Resharper.

Web API optional parameters

you need only set default value to parameters(you do not need the Route attribute):

public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

Converting newline formatting from Mac to Windows

You probably want unix2dos:

$ man unix2dos

NAME
       dos2unix - DOS/MAC to UNIX and vice versa text file format converter

SYNOPSIS
           dos2unix [options] [-c CONVMODE] [-o FILE ...] [-n INFILE OUTFILE ...]
           unix2dos [options] [-c CONVMODE] [-o FILE ...] [-n INFILE OUTFILE ...]

DESCRIPTION
       The Dos2unix package includes utilities "dos2unix" and "unix2dos" to convert plain text files in DOS or MAC format to UNIX format and vice versa.  Binary files and non-
       regular files, such as soft links, are automatically skipped, unless conversion is forced.

       Dos2unix has a few conversion modes similar to dos2unix under SunOS/Solaris.

       In DOS/Windows text files line endings exist out of a combination of two characters: a Carriage Return (CR) followed by a Line Feed (LF).  In Unix text files line
       endings exists out of a single Newline character which is equal to a DOS Line Feed (LF) character.  In Mac text files, prior to Mac OS X, line endings exist out of a
       single Carriage Return character. Mac OS X is Unix based and has the same line endings as Unix.

You can either run unix2dos on your DOS/Windows machine using cygwin or on your Mac using MacPorts.

How do you change the character encoding of a postgres database?

First off, Daniel's answer is the correct, safe option.

For the specific case of changing from SQL_ASCII to something else, you can cheat and simply poke the pg_database catalogue to reassign the database encoding. This assumes you've already stored any non-ASCII characters in the expected encoding (or that you simply haven't used any non-ASCII characters).

Then you can do:

update pg_database set encoding = pg_char_to_encoding('UTF8') where datname = 'thedb'

This will not change the collation of the database, just how the encoded bytes are converted into characters (so now length('£123') will return 4 instead of 5). If the database uses 'C' collation, there should be no change to ordering for ASCII strings. You'll likely need to rebuild any indices containing non-ASCII characters though.

Caveat emptor. Dumping and reloading provides a way to check your database content is actually in the encoding you expect, and this doesn't. And if it turns out you did have some wrongly-encoded data in the database, rescuing is going to be difficult. So if you possibly can, dump and reinitialise.

SQL to add column and comment in table in single command

Query to add column with comment are :

alter table table_name 
add( "NISFLAG"    NUMBER(1,0) )

comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'

commit;

Cannot stop or restart a docker container

Check if there is any zombie process using "top" command.

docker ps | grep <<container name>> 

Get the container id.

ps -ef | grep <<container id>>

ps -ef|grep defunct | grep java

And kill the container by Parent PID .

Java: How can I compile an entire directory structure of code ?

You'd have to use something like Ant to do this hierarchically:

http://ant.apache.org/manual/Tasks/javac.html

You'll need to create a build script with a target called compile containing the following:

<javac sourcepath="" srcdir="${src}"
         destdir="${build}" >
    <include name="**/*.java"/>
</javac>

Then you''ll be able to compile all files by running:

 ant compile

Alternatively, import your project into Eclipse and it will automatically compile all the source files for that project.

Can jQuery check whether input content has changed?

There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details:

Example (except IE < 9: see links above for workaround):

$("#your_id").on("input", function() {
    alert("Change to " + this.value);
});

Finding an element in an array in Java

You might want to consider using a Collection implementation instead of a flat array.

The Collection interface defines a contains(Object o) method, which returns true/false.

ArrayList implementation defines an indexOf(Object o), which gives an index, but that method is not on all collection implementations.

Both these methods require proper implementations of the equals() method, and you probably want a properly implemented hashCode() method just in case you are using a hash based Collection (e.g. HashSet).

What is the syntax for an inner join in LINQ to SQL?

One Best example

Table Names : TBL_Emp and TBL_Dep

var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
select new
{
 emp.Name;
 emp.Address
 dep.Department_Name
}


foreach(char item in result)
 { // to do}

psql: FATAL: Ident authentication failed for user "postgres"

Simply adding the -h localhost bit was all mine required to work

Error importing Seaborn module in Python

  1. delete package whl file in 'C:\Users\hp\Anaconda3\Lib\site-packages'
  2. pip uninstlal scipy and seaborn
  3. pip install scipy nd seaborn agaian

it worked for 4, win10, anaconda

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

You would need to enable https binding on server side. IISExpress in this case. Select Properties on website project in solution explorer (not double click). In the properties pane then you need to enable SSL.

How to set headers in http get request?

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

None of the above fixed my problem.

I added "C:/Windows/System32" to the 'Path' or 'PATH' environment variable. I could use the reg /? command. I also ran the 'vcvarsall.bat' file with no error message.

My error is that I was running VS2012 Cross Tools Command Prompt instead of VS2013 Cross Tools Command Prompt.

The reason being the file structure in the start menu. 2010 and 2012 are under 'Microsoft Visual Studio YEAR' and 2013 is under 'Visual Studio YEAR'. I just didn't realize this. :/

I hope this helps someone.

How to save S3 object to a file using boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_download(s3path, destination) directly or the copy-pasted code:

def s3_download(source, destination,
                exists_strategy='raise',
                profile_name=None):
    """
    Copy a file from an S3 source to a local destination.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    destination : str
    exists_strategy : {'raise', 'replace', 'abort'}
        What is done when the destination already exists?
    profile_name : str, optional
        AWS profile

    Raises
    ------
    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    exists_strategies = ['raise', 'replace', 'abort']
    if exists_strategy not in exists_strategies:
        raise ValueError('exists_strategy \'{}\' is not in {}'
                         .format(exists_strategy, exists_strategies))
    session = boto3.Session(profile_name=profile_name)
    s3 = session.resource('s3')
    bucket_name, key = _s3_path_split(source)
    if os.path.isfile(destination):
        if exists_strategy is 'raise':
            raise RuntimeError('File \'{}\' already exists.'
                               .format(destination))
        elif exists_strategy is 'abort':
            return
    s3.Bucket(bucket_name).download_file(key, destination)

from collections import namedtuple

S3Path = namedtuple("S3Path", ["bucket_name", "key"])


def _s3_path_split(s3_path):
    """
    Split an S3 path into bucket and key.

    Parameters
    ----------
    s3_path : str

    Returns
    -------
    splitted : (str, str)
        (bucket, key)

    Examples
    --------
    >>> _s3_path_split('s3://my-bucket/foo/bar.jpg')
    S3Path(bucket_name='my-bucket', key='foo/bar.jpg')
    """
    if not s3_path.startswith("s3://"):
        raise ValueError(
            "s3_path is expected to start with 's3://', " "but was {}"
            .format(s3_path)
        )
    bucket_key = s3_path[len("s3://"):]
    bucket_name, key = bucket_key.split("/", 1)
    return S3Path(bucket_name, key)

Counting Number of Letters in a string variable

myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));

Converting a number with comma as decimal point to float

Using str_replace() to remove the dots is not overkill.

$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));

// At this point, $number is a "natural" float.
print $number;

This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.

Include CSS,javascript file in Yii Framework

Using bootstrap extension

my css file: themes/bootstrap/css/style.css

my js file: root/js/script.js

at theme/bootstrap/views/layouts/main.php

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/styles.css" />

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/script.js"></script>

Postgres and Indexes on Foreign Keys and Primary Keys

PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships.

When Pg creates an implicit index it will emit a NOTICE-level message that you can see in psql and/or the system logs, so you can see when it happens. Automatically created indexes are visible in \d output for a table, too.

The documentation on unique indexes says:

PostgreSQL automatically creates an index for each unique constraint and primary key constraint to enforce uniqueness. Thus, it is not necessary to create an index explicitly for primary key columns.

and the documentation on constraints says:

Since a DELETE of a row from the referenced table or an UPDATE of a referenced column will require a scan of the referencing table for rows matching the old value, it is often a good idea to index the referencing columns. Because this is not always needed, and there are many choices available on how to index, declaration of a foreign key constraint does not automatically create an index on the referencing columns.

Therefore you have to create indexes on foreign-keys yourself if you want them.

Note that if you use primary-foreign-keys, like 2 FK's as a PK in a M-to-N table, you will have an index on the PK and probably don't need to create any extra indexes.

While it's usually a good idea to create an index on (or including) your referencing-side foreign key columns, it isn't required. Each index you add slows DML operations down slightly, so you pay a performance cost on every INSERT, UPDATE or DELETE. If the index is rarely used it may not be worth having.

Get the filename of a fileupload in a document through JavaScript

Try the value property, like this:

var fu1 = document.getElementById("FileUpload1");
alert("You selected " + fu1.value);

NOTE: It looks like FileUpload1 is an ASP.Net server-side FileUpload control.
If so, you should get its ID using the ClientID property, like this:

var fu1 = document.getElementById("<%= FileUpload1.ClientID %>");

Check empty string in Swift?

if myString?.startIndex != myString?.endIndex {}

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

Querying Datatable with where condition

Something like this...

var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;

See also LINQ query on a DataTable

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

Well, it'd still be convenient (syntactically) if we could declare usual values inside the if's condition. So, here's a trick: you can make the compiler think there is an assignment of Optional.some(T) to a value like so:

    if let i = "abc".firstIndex(of: "a"),
        let i_int = .some(i.utf16Offset(in: "abc")),
        i_int < 1 {
        // Code
    }

Using getline() with file input in C++

getline, as it name states, read a whole line, or at least till a delimiter that can be specified.

So the answer is "no", getlinedoes not match your need.

But you can do something like:

inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;

Asynchronously load images with jQuery

No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });

Each GROUP BY expression must contain at least one column that is not an outer reference

When you're using GROUP BY, you need to also use aggregate functions for the columns not inside your group by clause.

I don't know exactly what you're trying to do, but I guess this would work:

select 
    LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000),
    PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
    qvalues.name,
    qvalues.compound,
    MAX(qvalues.rid)
from
    batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
where
    LEN(datapath)>4
group by
    LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000),
    PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
    qvalues.name,
    qvalues.compound
having
    rid!=MAX(rid)

Edit: What I'm trying to do here is a group by with all fields but rid. If that's not what you want, what you need to do in order to have a valid SQL statement is adding an aggregate function call for each removed group by field...

Python BeautifulSoup extract text between element

soup = BeautifulSoup(html)
for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
  hit = hit.text.strip()
  print hit

This will print: THIS IS MY TEXT Try this..

How can I undo a `git commit` locally and on a remote after `git push`

Try using

git reset --hard <commit id> 

Please Note : Here commit id will the id of the commit you want to go to but not the id you want to reset. this was the only point where i also got stucked.

then push

git push -f <remote> <branch>

Convert a object into JSON in REST service by Spring MVC

You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.

Please note, it might not be a good idea to directly return model classes. Just a suggestion.

HTH.

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

How to include PHP files that require an absolute path?

require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/path/to/file.php");

I use this line of code. It goes back to the "top" of the site tree, then goes to the file desired.

For example, let's say i have this file tree:

domain.com/aaa/index.php
domain.com/bbb/ccc/ddd/index.php
domain.com/_resources/functions.php

I can include the functions.php file from wherever i am, just by copy pasting

require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/_resources/functions.php");

If you need to use this code many times, you may create a function that returns the str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1)) part. Then just insert this function in the first file you include. I have an "initialize.php" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named path_back):

require(path_back()."/_resources/another_php_file.php");

How create table only using <div> tag and Css

A bit OFF-TOPIC, but may help someone for a cleaner HTML... CSS

.common_table{
    display:table;
    border-collapse:collapse;
    border:1px solid grey;
    }
.common_table DIV{
    display:table-row;
    border:1px solid grey;
    }
.common_table DIV DIV{
    display:table-cell;
    }

HTML

<DIV class="common_table">
   <DIV><DIV>this is a cell</DIV></DIV>
   <DIV><DIV>this is a cell</DIV></DIV>
</DIV>

Works on Chrome and Firefox

Declare variable MySQL trigger

Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.

For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.

INSERT ... SELECT Syntax.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

The error message proved to be true as Apache Ant isn't in the path of Mac OS X Mavericks anymore.

Bulletproof solution:

  1. Download and install Homebrew by executing following command in terminal:

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  2. Install Apache Ant via Homebrew by executing

    brew install ant

Run the PhoneGap build again and it should successfully compile and install your Android app.

Eclipse: How to build an executable jar with external jar?

Try the fat-jar extension. It will include all external jars inside the jar.

Converting xml to string using C#

As Chris suggests, you can do it like this:

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Or like this:

public string GetXMLAsString(XmlDocument myxml)
    {

        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        myxml.WriteTo(tx);

        string str = sw.ToString();// 
        return str;
    }

and if you really want to create a new XmlDocument then do this

XmlDocument newxmlDoc= myxml

How long will my session last?

You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.

Your session will last 1440 seconds which is 24 minutes (default).

React.js inline style best practices

2020 Update: The best practice is to use a library that has already done the hard work for you and doesn't kill your team when you make the switch as pointed out by the originally accepted answer in this video (it's still relevant). Also just to get a sense on trends this is a very helpful chart. After doing my own research on this I chose to use Emotion for my new projects and it has proven to be very flexible and scaleable.

Given that the most upvoted answer from 2015 recommended Radium which is now relegated to maintenance mode. So it seems reasonable to add a list of alternatives. The post discontinuing Radium suggests a few libraries. Each of the sites linked has examples readily available so I will refrain from copy and pasting the code here.

  • Emotion which is "inspired by" styled-components among others, uses styles in js and can be framework agnostic, but definitely promotes its React library. Emotion has been kept up to date as of this post.
  • styled-components is comparable and offers many of the same features as Emotion. Also actively being maintained. Both Emotion and styled-components have similar syntax. It is built specifically to work with React components.
  • JSS Yet another option for styles in js which is framework agnostic though it does have a number of framework packages, React-JSS among them.

git cherry-pick says "...38c74d is a merge but no -m option was given"

@Borealid's answer is correct, but suppose that you don't care about preserving the exact merging history of a branch and just want to cherry-pick a linearized version of it. Here's an easy and safe way to do that:

Starting state: you are on branch X, and you want to cherry-pick the commits Y..Z.

  1. git checkout -b tempZ Z
  2. git rebase Y
  3. git checkout -b newX X
  4. git cherry-pick Y..tempZ
  5. (optional) git branch -D tempZ

What this does is to create a branch tempZ based on Z, but with the history from Y onward linearized, and then cherry-pick that onto a copy of X called newX. (It's safer to do this on a new branch rather than to mutate X.) Of course there might be conflicts in step 4, which you'll have to resolve in the usual way (cherry-pick works very much like rebase in that respect). Finally it deletes the temporary tempZ branch.

If step 2 gives the message "Current branch tempZ is up to date", then Y..Z was already linear, so just ignore that message and proceed with steps 3 onward.

Then review newX and see whether that did what you wanted.

(Note: this is not the same as a simple git rebase X when on branch Z, because it doesn't depend in any way on the relationship between X and Y; there may be commits between the common ancestor and Y that you didn't want.)

How to convert a String to Bytearray

UTF-16 Byte Array

JavaScript encodes strings as UTF-16, just like C#'s UnicodeEncoding, so the byte arrays should match exactly using charCodeAt(), and splitting each returned byte pair into 2 separate bytes, as in:

function strToUtf16Bytes(str) {
  const bytes = [];
  for (ii = 0; ii < str.length; ii++) {
    const code = str.charCodeAt(ii); // x00-xFFFF
    bytes.push(code & 255, code >> 8); // low, high
  }
  return bytes;
}

For example:

strToUtf16Bytes(''); 
// [ 60, 216, 53, 223 ]

However, If you want to get a UTF-8 byte array, you must transcode the bytes.

UTF-8 Byte Array

The solution feels somewhat non-trivial, but I used the code below in a high-traffic production environment with great success (original source).

Also, for the interested reader, I published my unicode helpers that help me work with string lengths reported by other languages such as PHP.

/**
 * Convert a string to a unicode byte array
 * @param {string} str
 * @return {Array} of bytes
 */
export function strToUtf8Bytes(str) {
  const utf8 = [];
  for (let ii = 0; ii < str.length; ii++) {
    let charCode = str.charCodeAt(ii);
    if (charCode < 0x80) utf8.push(charCode);
    else if (charCode < 0x800) {
      utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
    } else if (charCode < 0xd800 || charCode >= 0xe000) {
      utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
    } else {
      ii++;
      // Surrogate pair:
      // UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
      // splitting the 20 bits of 0x0-0xFFFFF into two halves
      charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
      utf8.push(
        0xf0 | (charCode >> 18),
        0x80 | ((charCode >> 12) & 0x3f),
        0x80 | ((charCode >> 6) & 0x3f),
        0x80 | (charCode & 0x3f),
      );
    }
  }
  return utf8;
}

Docker-compose: node_modules not present in a volume after npm install succeeds

UPDATE: Use the solution provided by @FrederikNS.

I encountered the same problem. When the folder /worker is mounted to the container - all of it's content will be syncronized (so the node_modules folder will disappear if you don't have it locally.)

Due to incompatible npm packages based on OS, I could not just install the modules locally - then launch the container, so..

My solution to this, was to wrap the source in a src folder, then link node_modules into that folder, using this index.js file. So, the index.js file is now the starting point of my application.

When I run the container, I mounted the /app/src folder to my local src folder.

So the container folder looks something like this:

/app
  /node_modules
  /src
    /node_modules -> ../node_modules
    /app.js
  /index.js

It is ugly, but it works..

What SOAP client libraries exist for Python, and where is the documentation for them?

I believe soaplib has deprecated its SOAP client ('sender') in favor of suds. At this point soaplib is focused on being a web framework agnostic SOAP server ('receiver'). Currently soaplib is under active development and is usually discussed in the Python SOAP mailing list:

http://mail.python.org/mailman/listinfo/soap

Hide text using css

The answer is to create a span with the property

{display:none;}

You can find an example at this site

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Return multiple values to a method caller

You cannot do this in C#. What you can do is have a out parameter or return your own class (or struct if you want it to be immutable).

Using out parameter
public int GetDay(DateTime date, out string name)
{
  // ...
}
Using custom class (or struct)
public DayOfWeek GetDay(DateTime date)
{
  // ...
}

public class DayOfWeek
{
  public int Day { get; set; }
  public string Name { get; set; }
}

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

Benchmark time!

_x000D_
_x000D_
function log(data) {_x000D_
  document.getElementById("log").textContent += data + "\n";_x000D_
}_x000D_
_x000D_
benchmark = (() => {_x000D_
  time_function = function(ms, f, num) {_x000D_
    var z = 0;_x000D_
    var t = new Date().getTime();_x000D_
    for (z = 0;_x000D_
      ((new Date().getTime() - t) < ms); z++)_x000D_
      f(num);_x000D_
    return (z)_x000D_
  }_x000D_
_x000D_
  function clone1(arr) {_x000D_
    return arr.slice(0);_x000D_
  }_x000D_
_x000D_
  function clone2(arr) {_x000D_
    return [...arr]_x000D_
  }_x000D_
_x000D_
  function clone3(arr) {_x000D_
    return [].concat(arr);_x000D_
  }_x000D_
_x000D_
  Array.prototype.clone = function() {_x000D_
    return this.map(e => Array.isArray(e) ? e.clone() : e);_x000D_
  };_x000D_
_x000D_
  function clone4(arr) {_x000D_
    return arr.clone();_x000D_
  }_x000D_
_x000D_
_x000D_
  function benchmark() {_x000D_
    function compare(a, b) {_x000D_
      if (a[1] > b[1]) {_x000D_
        return -1;_x000D_
      }_x000D_
      if (a[1] < b[1]) {_x000D_
        return 1;_x000D_
      }_x000D_
      return 0;_x000D_
    }_x000D_
_x000D_
    funcs = [clone1, clone2, clone3, clone4];_x000D_
    results = [];_x000D_
    funcs.forEach((ff) => {_x000D_
      console.log("Benchmarking: " + ff.name);_x000D_
      var s = time_function(2500, ff, Array(1024));_x000D_
      results.push([ff, s]);_x000D_
      console.log("Score: " + s);_x000D_
_x000D_
    })_x000D_
    return results.sort(compare);_x000D_
  }_x000D_
  return benchmark;_x000D_
})()_x000D_
log("Starting benchmark...\n");_x000D_
res = benchmark();_x000D_
_x000D_
console.log("Winner: " + res[0][0].name + " !!!");_x000D_
count = 1;_x000D_
res.forEach((r) => {_x000D_
  log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");_x000D_
});_x000D_
log("\nWinner code:\n");_x000D_
log(res[0][0].toString());
_x000D_
<textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>
_x000D_
_x000D_
_x000D_

The benchmark will run for 10s since you click the button.

My results:

Chrome (V8 engine):

1. clone1 score: 100% *winner* (4110764)
2. clone3 score: 74.32% speed of winner. (3055225)
3. clone2 score: 30.75% speed of winner. (1264182)
4. clone4 score: 21.96% speed of winner. (902929)

Firefox (SpiderMonkey Engine):

1. clone1 score: 100% *winner* (8448353)
2. clone3 score: 16.44% speed of winner. (1389241)
3. clone4 score: 5.69% speed of winner. (481162)
4. clone2 score: 2.27% speed of winner. (192433)

Winner code:

function clone1(arr) {
    return arr.slice(0);
}

Winner engine:

SpiderMonkey (Mozilla/Firefox)

Python [Errno 98] Address already in use

First of all find the python process ID using this command

ps -fA | grep python

You will get a pid number by naming of your python process on second column

Then kill the process using this command

kill -9 pid

Disable Proximity Sensor during call

I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.

What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.

What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.

Wavy shape with css

My pure CSS implementation based on above with 100% width. Hope it helps!

_x000D_
_x000D_
#wave-container {_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#wave {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 40px;_x000D_
  background: black;_x000D_
}_x000D_
_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  right: -25%;_x000D_
  top: 20px_x000D_
}_x000D_
_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: black;_x000D_
  left: -25%;_x000D_
  top: -240px;_x000D_
}
_x000D_
<div id="wave-container">_x000D_
  <div id="wave">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Testing if a list of integer is odd or even

There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:

if (x % 2 == 0)
               //even number
        else
               //odd number

Here are a few other methods (from the website) :

//bitwise operation
if ((x & 1) == 0)
       //even number
else
      //odd number

//bit shifting
if (((x >> 1) << 1) == x)
       //even number
else
       //odd number

//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
       //even number
else
       //odd number

What are the differences between Visual Studio Code and Visual Studio?

Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:

    1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2     train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.

I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

I think the best way to find out how your restore or backup progress is by the following query:

USE[master]
GO
SELECT session_id AS SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time 
    FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a 
        WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')
GO

The query above, identify the session by itself and perform a percentage progress every time you press F5 or Execute button on SSMS!

The query was performed by the guy who write this post

Parsing JSON object in PHP using json_decode

You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

MySQL: Convert INT to DATETIME

SELECT  FROM_UNIXTIME(mycolumn)
FROM    mytable

Finding partial text in range, return an index

This formula will do the job:

=INDEX(G:G,MATCH(FALSE,ISERROR(SEARCH(H1,G:G)),0)+3)

you need to enter it as an array formula, i.e. press Ctrl-Shift-Enter. It assumes that the substring you're searching for is in cell H1.

How to generate gcc debug symbol outside the build target?

You need to use objcopy to separate the debug information:

objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"

I use the bash script below to separate the debug information into files with a .debug extension in a .debug directory. This way I can tar the libraries and executables in one tar file and the .debug directories in another. If I want to add the debug info later on I simply extract the debug tar file and voila I have symbolic debug information.

This is the bash script:

#!/bin/bash

scriptdir=`dirname ${0}`
scriptdir=`(cd ${scriptdir}; pwd)`
scriptname=`basename ${0}`

set -e

function errorexit()
{
  errorcode=${1}
  shift
  echo $@
  exit ${errorcode}
}

function usage()
{
  echo "USAGE ${scriptname} <tostrip>"
}

tostripdir=`dirname "$1"`
tostripfile=`basename "$1"`


if [ -z ${tostripfile} ] ; then
  usage
  errorexit 0 "tostrip must be specified"
fi

cd "${tostripdir}"

debugdir=.debug
debugfile="${tostripfile}.debug"

if [ ! -d "${debugdir}" ] ; then
  echo "creating dir ${tostripdir}/${debugdir}"
  mkdir -p "${debugdir}"
fi
echo "stripping ${tostripfile}, putting debug info into ${debugfile}"
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
chmod -x "${debugdir}/${debugfile}"

What does java.lang.Thread.interrupt() do?

If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.

It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.

It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.

Service Reference Error: Failed to generate code for the service reference

I have encountered this problem when upgrading a VS2010 WCF+Silverlight solution in VS2015 Professional. Besides automatically upgrading from Silverlight 4 to Silverlight 5, the service reference reuse checkbox value was changed and generation failed.

Function passed as template argument

Came here with the additional requirement, that also parameter/return types should vary. Following Ben Supnik this would be for some type T

typedef T(*binary_T_op)(T, T);

instead of

typedef int(*binary_int_op)(int, int);

The solution here is to put the function type definition and the function template into a surrounding struct template.

template <typename T> struct BinOp
{
    typedef T(*binary_T_op )(T, T); // signature for all valid template params
    template<binary_T_op op>
    T do_op(T a, T b)
    {
       return op(a,b);
    }
};


double mulDouble(double a, double b)
{
    return a * b;
}


BinOp<double> doubleBinOp;

double res = doubleBinOp.do_op<&mulDouble>(4, 5);

Alternatively BinOp could be a class with static method template do_op(...), then called as

double res = BinOp<double>::do_op<&mulDouble>(4, 5);

Timer for Python game

I use this function in my python programs. The input for the function is as example:
value = time.time()

def stopWatch(value):
    '''From seconds to Days;Hours:Minutes;Seconds'''

    valueD = (((value/365)/24)/60)
    Days = int (valueD)

    valueH = (valueD-Days)*365
    Hours = int(valueH)

    valueM = (valueH - Hours)*24
    Minutes = int(valueM)

    valueS = (valueM - Minutes)*60
    Seconds = int(valueS)


    print Days,";",Hours,":",Minutes,";",Seconds




start = time.time() # What in other posts is described is

***your code HERE***

end = time.time()         
stopWatch(end-start) #Use then my code

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

JavaScript: Parsing a string Boolean value?

Wood-eye be careful. After looking at all this code, I feel obligated to post:

Let's start with the shortest, but very strict way:

var str = "true";
var mybool = JSON.parse(str);

And end with a proper, more tolerant way:

var parseBool = function(str) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)

    if(str == null)
        return false;

    if (typeof str === 'boolean')
    {
        if(str === true)
            return true;

        return false;
    } 

    if(typeof str === 'string')
    {
        if(str == "")
            return false;

        str = str.replace(/^\s+|\s+$/g, '');
        if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
            return true;

        str = str.replace(/,/g, '.');
        str = str.replace(/^\s*\-\s*/g, '-');
    }

    // var isNum = string.match(/^[0-9]+$/) != null;
    // var isNum = /^\d+$/.test(str);
    if(!isNaN(str))
        return (parseFloat(str) != 0);

    return false;
}

Testing:

var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", "  true  ", "  TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");

var array_2 = new Array(null, "", false, "false", "   false   ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");


for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}

for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}

for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}

Cross-Origin Read Blocking (CORB)

Try to install "Moesif CORS" extension if you are facing issue in google chrome. As it is cross origin request, so chrome is not accepting a response even when the response status code is 200

Exception from HRESULT: 0x800A03EC Error

Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". This problem occurs if you are using an older version of excel file (.xls) instead of .xlsx. The older version does not allow more than 65k rows in the excel sheet.

Once you have saved as .xslx, try executing your code again.

edit ----

Looking more into your problem, it seems that the problem might be locale specific. Does the code work on another machine? What value does the cell have? Is it datetime format? Have a look here:

http://support.microsoft.com/kb/320369

http://blogs.msdn.com/b/eric_carter/archive/2005/06/15/429515.aspx

Can a java lambda have more than 1 parameter?

Another alternative, not sure if this applies to your particular problem but to some it may be applicable is to use UnaryOperator in java.util.function library. where it returns same type you specify, so you put all your variables in one class and is it as a parameter:

public class FunctionsLibraryUse {

    public static void main(String[] args){
        UnaryOperator<People> personsBirthday = (p) ->{
            System.out.println("it's " + p.getName() + " birthday!");
            p.setAge(p.getAge() + 1);
            return p;
        };
        People mel = new People();
        mel.setName("mel");
        mel.setAge(27);
        mel = personsBirthday.apply(mel);
        System.out.println("he is now : " + mel.getAge());

    }
}
class People{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

So the class you have, in this case Person, can have numerous instance variables and won't have to change the parameter of your lambda expression.

For those interested, I've written notes on how to use java.util.function library: http://sysdotoutdotprint.com/index.php/2017/04/28/java-util-function-library/

How to convert buffered image to image and vice-versa?

Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:

Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);     

BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);

CMake is not able to find BOOST libraries

Try to complete cmake process with following libs:

sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev

Is there a command to undo git init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

ImportError: No module named 'encodings'

I got this error when try to launch MySql Workbench 8.0 on my macOS Catalina 10.15.3.

I solved this issue by installing Python 3.7 on my system.

I guess in future, when Workbench will have version greater than 8, it will require newer version of Python. Just look at the library path in the error and you will find required version.

Javascript set img src

document["pic1"].src = searchPic.src

should work

Access localhost from the internet

Try with your IP Address , I think you can access it by internet.

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Try doing this, using firefox as fake user agent (moreover, it's a good startup script for web scraping with the use of cookies):

#!/usr/bin/env python2
# -*- coding: utf8 -*-
# vim:ts=4:sw=4


import cookielib, urllib2, sys

def doIt(uri):
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    page = opener.open(uri)
    page.addheaders = [('User-agent', 'Mozilla/5.0')]
    print page.read()

for i in sys.argv[1:]:
    doIt(i)

USAGE:

python script.py "http://www.ichangtou.com/#company:data_000008.html"

How to return a file using Web API?

Another way to download file is to write the stream content to the response's body directly:

[HttpGet("pdfstream/{id}")]
public async Task  GetFile(long id)
{        
    var stream = GetStream(id);
    Response.StatusCode = (int)HttpStatusCode.OK;
    Response.Headers.Add( HeaderNames.ContentDisposition, $"attachment; filename=\"{Guid.NewGuid()}.pdf\"" );
    Response.Headers.Add( HeaderNames.ContentType, "application/pdf"  );            
    await stream.CopyToAsync(Response.Body);
    await Response.Body.FlushAsync();           
}

How to select only date from a DATETIME field in MySQL?

Simply You can do

SELECT DATE(date_field) AS date_field FROM table_name

Rails 3.1 and Image Assets

http://railscasts.com/episodes/279-understanding-the-asset-pipeline

This railscast (Rails Tutorial video on asset pipeline) helps a lot to explain the paths in assets pipeline as well. I found it pretty useful, and actually watched it a few times.

The solution I chose is @Lee McAlilly's above, but this railscast helped me to understand why it works. Hope it helps!

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

Ruby: Merging variables in to a string

You can use sprintf-like formatting to inject values into the string. For that the string must include placeholders. Put your arguments into an array and use on of these ways: (For more info look at the documentation for Kernel::sprintf.)

fmt = 'The %s %s the %s'
res = fmt % [animal, action, other_animal]  # using %-operator
res = sprintf(fmt, animal, action, other_animal)  # call Kernel.sprintf

You can even explicitly specify the argument number and shuffle them around:

'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']

Or specify the argument using hash keys:

'The %{animal} %{action} the %{second_animal}' %
  { :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}

Note that you must provide a value for all arguments to the % operator. For instance, you cannot avoid defining animal.

How to search by key=>value in a multidimensional array in PHP

I think the easiest way is using php array functions if you know your key.

function search_array ( $array, $key, $value )
{
   return array_search($value,array_column($array,$key));
}

this return an index that you could find your desired data by this like below:

$arr = array(0 => array('id' => 1, 'name' => "cat 1"),
  1 => array('id' => 2, 'name' => "cat 2"),
  2 => array('id' => 3, 'name' => "cat 1")
);

echo json_encode($arr[search_array($arr,'name','cat 2')]);

this output will:

{"id":2,"name":"cat 2"}

Prompt for user input in PowerShell

Read-Host is a simple option for getting string input from a user.

$name = Read-Host 'What is your username?'

To hide passwords you can use:

$pass = Read-Host 'What is your password?' -AsSecureString

To convert the password to plain text:

[Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))

As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].

To access information without invoking a method, leave the parentheses off:

PS> $Host.UI.Prompt

MemberType          : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
                    ompt(string caption, string message, System.Collections.Ob
                    jectModel.Collection[System.Management.Automation.Host.Fie
                    ldDescription] descriptions)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Collections.Generic.Dictionary[string,psobject] Pro
                    mpt(string caption, string message, System.Collections.Obj
                    ectModel.Collection[System.Management.Automation.Host.Fiel
                    dDescription] descriptions)
Name                : Prompt
IsInstance          : True

$Host.UI.Prompt.OverloadDefinitions will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>).

Currently running queries in SQL Server

I use the below query

SELECT   SPID       = er.session_id
    ,STATUS         = ses.STATUS
    ,[Login]        = ses.login_name
    ,Host           = ses.host_name
    ,BlkBy          = er.blocking_session_id
    ,DBName         = DB_Name(er.database_id)
    ,CommandType    = er.command
    ,ObjectName     = OBJECT_NAME(st.objectid)
    ,CPUTime        = er.cpu_time
    ,StartTime      = er.start_time
    ,TimeElapsed    = CAST(GETDATE() - er.start_time AS TIME)
    ,SQLStatement   = st.text
FROM    sys.dm_exec_requests er
    OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
    LEFT JOIN sys.dm_exec_sessions ses
    ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
    ON con.session_id = ses.session_id
WHERE   st.text IS NOT NULL

IIS Request Timeout on long ASP.NET operation

I'm posting this here, because I've spent like 3 and 4 hours on it, and I've only found answers like those one above, that say do add the executionTime, but it doesn't solve the problem in the case that you're using ASP .NET Core. For it, this would work:

At web.config file, add the requestTimeout attribute at aspNetCore node.

<system.webServer>
  <aspNetCore requestTimeout="00:10:00" ... (other configs goes here) />
</system.webServer>

In this example, I'm setting the value for 10 minutes.

Reference: https://docs.microsoft.com/en-us/aspnet/core/hosting/aspnet-core-module#configuring-the-asp-net-core-module

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

How to read an external local JSON file in JavaScript?

One simple workaround is to put your JSON file inside a locally running server. for that from the terminal go to your project folder and start the local server on some port number e.g 8181

python -m SimpleHTTPServer 8181

Then browsing to http://localhost:8181/ should display all of your files including the JSON. Remember to install python if you don't already have.

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

How to close a Tkinter window by pressing a Button?

You can use lambda to pass a reference to the window object as argument to close_window function:

button = Button (frame, text="Good-bye.", command = lambda: close_window(window))

This works because the command attribute is expecting a callable, or callable like object. A lambda is a callable, but in this case it is essentially the result of calling a given function with set parameters.

In essence, you're calling the lambda wrapper of the function which has no args, not the function itself.

C# Break out of foreach loop after X number of items

This should work.

int i = 1;
foreach (ListViewItem lvi in listView.Items) {
    ...
    if(++i == 50) break;
}

What is the difference between _tmain() and main() in C++?

Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello" that would probably end up as "H\0e\0l\0l\0o\0\0\0" and your program would only print the 'H' before it sees what it thinks is a null terminator.

So now you may wonder why it even compiles and links.

Well it compiles because you are allowed to define an overload to a function.

Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.

Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[]) version.

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

Laravel Advanced Wheres how to pass variable into function?

@kajetons' answer is fully functional.

You can also pass multiple variables by passing them like: use($var1, $var2)

DB::table('users')->where(function ($query) use ($activated,$var2) {
    $query->where('activated', '=', $activated);
    $query->where('var2', '>', $var2);
})->get();

How do I include a file over 2 directories back?

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

         

Xcode 10: A valid provisioning profile for this executable was not found

Make sure you:

1) Have a registered provisioning profile for your device.

2) Device must be added to the Development profile and updated.

If you still run into issues check your target's build settings.

Make sure you:

1) CODE_SIGNING_REQUIRED in User-Defined is set to YES.

enter image description here

2) Check Signing options are correct. If the problem persists switch to Manual settings instead of automatically.

Maven Could not resolve dependencies, artifacts could not be resolved

Turns out that it happened because of the firewall on my computer. Turning it off worked for me.

How to call function on child component on parent events

Calling child component in parent

<component :is="my_component" ref="my_comp"></component>
<v-btn @click="$refs.my_comp.alertme"></v-btn>

in Child component

mycomp.vue

    methods:{     
    alertme(){
            alert("alert")
            }
    }

Android Studio: Plugin with id 'android-library' not found

Use

apply plugin: 'com.android.library'

to convert an app module to a library module. More info here: https://developer.android.com/studio/projects/android-library.html

How can I render repeating React elements?

Since Array(3) will create an un-iterable array, it must be populated to allow the usage of the map Array method. A way to "convert" is to destruct it inside Array-brackets, which "forces" the Array to be filled with undefined values, same as Array(N).fill(undefined)

<table>
    { [...Array(3)].map((_, index) => <tr key={index}/>) }
</table>

Another way would be via Array fill():

<table>
    { Array(3).fill(<tr/>) }
</table>

?? Problem with above example is the lack of key prop, which is a must.
(Using an iterator's index as key is not recommended)


Nested Nodes:

_x000D_
_x000D_
const tableSize = [3,4]
const Table = (
    <table>
        <tbody>
        { [...Array(tableSize[0])].map((tr, trIdx) => 
            <tr key={trIdx}> 
              { [...Array(tableSize[1])].map((a, tdIdx, arr) => 
                  <td key={trIdx + tdIdx}>
                  {arr.length * trIdx + tdIdx + 1}
                  </td>
               )}
            </tr>
        )}
        </tbody>
    </table>
);

ReactDOM.render(Table, document.querySelector('main'))
_x000D_
td{ border:1px solid silver; padding:1em; }
_x000D_
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<main></main>
_x000D_
_x000D_
_x000D_

List of enum values in java

This is a more generic solution, that can be use for any Enum object, so be free of used.

static public List<Object> constFromEnumToList(Class enumType) {
    List<Object> nueva = new ArrayList<Object>();
    if (enumType.isEnum()) {
        try {
            Class<?> cls = Class.forName(enumType.getCanonicalName());
            Object[] consts = cls.getEnumConstants();
            nueva.addAll(Arrays.asList(consts));
        } catch (ClassNotFoundException e) {
            System.out.println("No se localizo la clase");
        }
    }
    return nueva;
}

Now you must call this way:

constFromEnumToList(MiEnum.class);

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

Split data frame string column into multiple columns

here is a one liner along the same lines as aniko's solution, but using hadley's stringr package:

do.call(rbind, str_split(before$type, '_and_'))

How to auto resize and adjust Form controls with change in resolution

Use Dock and Anchor properties. Here is a good article. Note that these will handle changes when maximizing/minimizing. That is a little different that if the screen resolution changes, but it will be along the same idea.

How to make overlay control above all other controls?

If you are using a Canvas or Grid in your layout, give the control to be put on top a higher ZIndex.

From MSDN:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="ZIndex Sample">
  <Canvas>
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" Fill="blue"/>
    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="150" Canvas.Left="150" Fill="yellow"/>
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" Fill="green"/>

    <!-- Reverse the order to illustrate z-index property -->

    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="300" Canvas.Left="200" Fill="green"/>
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="350" Canvas.Left="150" Fill="yellow"/>
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="400" Canvas.Left="100" Fill="blue"/>
  </Canvas>
</Page>

If you don't specify ZIndex, the children of a panel are rendered in the order they are specified (i.e. last one on top).

If you are looking to do something more complicated, you can look at how ChildWindow is implemented in Silverlight. It overlays a semitransparent background and popup over your entire RootVisual.

C++ calling base class constructors

Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.

Xcode 10 Error: Multiple commands produce

In my case, the problem comes from the podfile. I must add my test project to the podfile:

target 'MyApp' do
    pod 'Firebase'
    target 'MyAppTests' do
        inherit! :search_paths
        pod 'Firebase'
    end
end

After that, I need to execute:

pod update