Programs & Examples On #Pc

Anything about personal computers.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

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

I also encountered similar problem which is asked here. The issue was that some applications come with their own JRE and sometimes the installed JDK appears at lower priority level in environment path. Now there are two options:

  1. Uninstall the other application which has their own JDK/JRE.
  2. Sometimes it is not possible to remove the other application, which was my case. So I moved JDk installed by me to higher priority level in environment path.

enter image description here

I also removed the path as suggested by @CrazyCoder

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

All mentioned comments above are great, sharing the path that worked with me for this Blacklist file that need to be edited:

"Your project name\node_modules\metro-bundler\src" File name "blacklist.js"

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

For .NET CORE 3.1

I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them

What i mean is:

change this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseHttpsRedirection();  

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

      ...

     }

to this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseHttpsRedirection(); 

      ...

     }

By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

React Native Error: ENOSPC: System limit for number of file watchers reached

I had the same problem by using library wifi but when i changed my network it worked perfectly.

Change your network connection

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

I had the same problem and I solved as follows define an interface like mine

export class Notification {
    id: number;
    heading: string;
    link: string;
}

and in nofificationService write

allNotifications: Notification[]; 
  //NotificationDetail: Notification;  
  private notificationsUrl = 'assets/data/notification.json';  // URL to web api 
  private downloadsUrl = 'assets/data/download.json';  // URL to web api 

  constructor(private httpClient: HttpClient ) { }

  getNotifications(): Observable<Notification[]> {    
       //return this.allNotifications = this.NotificationDetail.slice(0);  
     return this.httpClient.get<Notification[]>

(this.notificationsUrl).pipe(map(res => this.allNotifications = res))
      } 

and in component write

 constructor(private notificationService: NotificationService) {
   }

  ngOnInit() {
      /* get Notifications */
      this.notificationService.getNotifications().subscribe(data => this.notifications = data);
}

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I tried many solutions but didn't work for me. The below solution works for me.

locate the sdkmanager file in android SDK.

In my case : ~/Android/Sdk/tools/bin

go to that path : cd ~/Android/Sdk/tools/bin

Accept licenses manually : ./sdkmanager --licenses Enter Yes or y

useState set method not reflecting change immediately

// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;

Now you should see, that your code actually does work. What does not work is the console.log(movies). This is because movies points to the old state. If you move your console.log(movies) outside of useEffect, right above the return, you will see the updated movies object.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

Remove a space in fileName

ex)

  • AS-IS: /Users/user/Desktop/My Projects/TestProject/
  • TO-BE: /Users/user/Desktop/MyProjects/TestProject/

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Here a temporary workaround, If you are using room just upgrade to 1.1.0 or higher

implementation "android.arch.persistence.room:runtime:1.1.0"

it removes this warning for me.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

I had the same issue but solved it by using Ubuntu.

  1. python -m pip install pyaudio
  2. Install sudo, apt-get and then install homebrew &/ linuxbrew on your linux subsystem using Ubuntu.
  3. The latest version supports ubuntu.
  4. brew install portaudio
  5. Make sure you have python/python3 installed on the terminal
  6. Make sure the current location is added as path in your virtual computer's path in environment Variable.
  7. brew link portaudio

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

Add the lines in the gradle.properties file

android.useAndroidX=true
android.enableJetifier=true

enter image description here enter image description here Refer also https://developer.android.com/jetpack/androidx

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

When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink], then it should be assigned a name of the property the value of which will be the route it should navigate the user to.

So to fix your issue, replace this routerLink="['/about']" with routerLink="/about" in your HTML.

There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:

<nav class="main-nav>
  <ul 
    class="main-nav__list" 
    ng-sticky 
    addClass="main-sticky-link" 
    [ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
    <li class="main-nav__item" routerLinkActive="active">
      <a class="main-nav__link" routerLink="/">Home</a>
    </li>
    <li class="main-nav__item" routerLinkActive="active"> 
      <a class="main-nav__link" routerLink="/about">About us</a>
    </li>
  </ul>
</nav>

It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>, either in your template provided above or in a parent component.

There's another issue with your AppRoutingModule. You need to export the RouterModule from there so that it is available to your AppModule when it imports it. To fix that, export it from your AppRoutingModule by adding it to the exports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'what', component: WhatwedoComponent },
  { path: 'contacts', component: FooterComponent },
  { path: 'projects', component: ProjectsComponent},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I solved this by reopening cmd in administration mode, activating virtual env, and installing again.

This was with Tensorflow 2.3.0 in a virtual environment.

Android Material and appcompat Manifest merger failed

in my case i am add in manifest file `

tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"

application tag of course, It will work

Angular: How to download a file from HttpClient?

Try something like this:

type: application/ms-excel

/**
 *  used to get file from server
 */

this.http.get(`${environment.apiUrl}`,{
          responseType: 'arraybuffer',headers:headers} 
         ).subscribe(response => this.downLoadFile(response, "application/ms-excel"));


    /**
     * Method is use to download file.
     * @param data - Array Buffer data
     * @param type - type of the document.
     */
    downLoadFile(data: any, type: string) {
        let blob = new Blob([data], { type: type});
        let url = window.URL.createObjectURL(blob);
        let pwa = window.open(url);
        if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
            alert( 'Please disable your Pop-up blocker and try again.');
        }
    }

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

in build.gradle , the version of bellow line should be same

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0'

git clone: Authentication failed for <URL>

The culprit was russian account password.

Accidentally set up it (wrong keyboard layout). Everything was working, so didnt bother changing it.

Out of despair changed it now and it worked.

If someone looked up this thread and its not a solution for you - check out comments under the question and steps i described in question, they might be useful to you.

Xcode couldn't find any provisioning profiles matching

What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.

  1. Connect your iPhone to your Mac
  2. Xcode>Window>Devices & Simulators
  3. Add new under Devices and make sure "show are run destination" is ticked
  4. Build project and run it on your iPhone

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

It simply means you have downloaded a spring starter code with database dependency without configuring your database, So it doesn't know how to connect. For Spring boot version 2.18 do the following steps to fix it.

  1. Create a database for the driver you have downloaded ie mysql/mongo etc.

  2. In your applications.properties file add the db connection info. Sample is given for mysql if your db is mongo change it for mongo.

spring.datasource.url=jdbc:mysql://localhost:3306/db_name_that_you_created
spring.datasource.username=your_db_username_here
spring.datasource.password=your_db_pass_here
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
  1. Reboot the server it will be running.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I think the problems comes from the following: The internet connection with u was unavailable so Android Studio asked you to enable the "offline work" and you just enabled it

To fix this:

  • File
  • Settings
  • Build, Execution, Deployment
  • Gradle
  • Uncheck offline work

why might unchecking the offline work solves the problem, because in the Gradle sometimes some dependencies need to update (the ones containing '+'), so internet connection is needed.

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'   
                                         ^^^^^

The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

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

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

Android design support library for API 28 (P) not working

1.Added these codes to your app/build.gradle:

configurations.all {
   resolutionStrategy.force 'com.android.support:support-v4:26.1.0' // the lib is old dependencies version;       
}

2.Modified sdk and tools version to 28:

compileSdkVersion 28
buildToolsVersion '28.0.3'
targetSdkVersion  28

2.In your AndroidManifest.xml file, you should add two line:

<application
    android:name=".YourApplication"
    android:appComponentFactory="anystrings be placeholder"
    tools:replace="android:appComponentFactory"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">

Thanks for the answer @Carlos Santiago : Android design support library for API 28 (P) not working

Failed to resolve: com.google.firebase:firebase-core:16.0.1

if you are using

compileSdkVersion 23

in app-level gradle, and

classpath 'com.android.tools.build:gradle:2.1.0'

in project-level gradle and you have added the google-services.json file to your project.

you need to add just below code

maven {
   url "https://maven.google.com"
}

at below of jcenter() in repositories blocks in project-level gradle file here are my gradle files:

project-level gradle file:

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and app-level gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.moslem.amazonlikeapp"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.google.firebase:firebase-core:16.0.1'
}
apply plugin: 'com.google.gms.google-services'

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two possible reasons 1. If you are using HttpClient in your service you need to import HttpClientModule in your module file and mention it in the imports array.

import { HttpClientModule } from '@angular/common/http';
  1. If you are using normal Http in your services you need to import HttpModule in your module file and mention it in the imports array.

    import { HttpModule } from '@angular/http'

By default, this is not available in the angular then you need to install @angular/http

If you wish you can use both HttpClientModule and HttpModule in your project.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

It also might be that you haven't declared you Dependency Injected service, as a provider in the component that you injected it to. That was my case :)

Flutter.io Android License Status Unknown

here is my solution:

  1. install SDKMan

    $ curl -s "https://get.sdkman.io" | bash

  2. setting your bash_profile

    $ source "$HOME/.sdkman/bin/sdkman-init.sh

    $ source ~/.bash_profile

  3. find java sdk, and select want to install version

    $ sdk ls java

    $ sdk install java 8.0.192-zulu

  4. copy your flutter doctor warning message to update sdkmanager

    $ /Users/YourUserName/Library/Android/sdk/tools/bin/sdkmanager --update

  5. after 1~4, redo it

    $ flutter doctor --android-licenses

error: resource android:attr/fontVariationSettings not found

For native Android apps (not Cordova) solution for me is:

Was:

implementation 'com.android.support:support-v13:+'

Now:

implementation 'com.android.support:support-v13:27.1.1'

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Go to the directory where you put additional libraries and delete duplicated libraries.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

Failed linking file resources

You maybe having this error on your java files because there is one or more XML file with error.

Go through all your XML files and resolve errors, then clean or rebuild project from build menu

Start with your most recent edited XML file

Assets file project.assets.json not found. Run a NuGet package restore

For me when i did - dotnet restore still error was occurring.

I went to

1 Tool -> NuGet Package Maneger -> Package Manager settings -> click on "Clear on Nuget Catche(s)"

2 dotnet restore

resolved issues.

How to check python anaconda version installed on Windows 10 PC?

On the anaconda prompt, do a

  • conda -V or conda --version to get the conda version.
  • python -V or python --version to get the python version.
  • conda list anaconda$ to get the Anaconda version.
  • conda list to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).
  • conda info to get all the current environment details.
  • conda info --envs To see a list of all your environments

Detailed description here, download cheat sheet from here

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

I fixed my problem with the solution below:

In Gradle build file, add dependency:

implementation 'com.android.support:multidex:1.0.3'

And then in the "defaultConfig" section, add:

multiDexEnabled true

How to iterate using ngFor loop Map containing key as string and values as map iteration

If you are using Angular 6.1 or later, the most convenient way is to use KeyValuePipe

   @Component({
      selector: 'keyvalue-pipe',
      template: `<span>
        <p>Object</p>
        <div *ngFor="let item of object | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
        <p>Map</p>
        <div *ngFor="let item of map | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
      </span>`
    })
    export class KeyValuePipeComponent {
      object: Record<number, string> = {2: 'foo', 1: 'bar'};
      map = new Map([[2, 'foo'], [1, 'bar']]);
    }

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

Check the namespace from where we are importing

import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**

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

I have resolved this issue after selecting the "Target Compatibility" to 1.8 Java version. File -> Project Structure -> Modules.

How to start up spring-boot application via command line?

To run the spring-boot application, need to follow some step.

  1. Maven setup (ignore if already setup):

    a. Install maven from https://maven.apache.org/download.cgi

    b. Unzip maven and keep in C drive (you can keep any location. Path location will be changed accordingly).

    c. Set MAVEN_HOME in system variable. enter image description here

    d. Set path for maven

enter image description here

  1. Add Maven Plugin to POM.XML

    <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

  2. Build Spring Boot Project with Maven

       maven package
    

    or

         mvn install / mvn clean install
    
  3. Run Spring Boot app using Maven:

        mvn spring-boot:run
    
  4. [optional] Run Spring Boot app with java -jar command

         java -jar target/mywebserviceapp-0.0.1-SNAPSHOT.jar
    

Android Studio AVD - Emulator: Process finished with exit code 1

Check android studio event log as it could be low storage issue.

emulator: ERROR: Not enough disk space to run AVD 'Nexus_5_API_21'. Exiting...

How to get query parameters from URL in Angular 5?

Found in: Parent components gets empty Params from ActivatedRoute

Worked for me:

import {Component, OnDestroy, OnInit} from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

@Component({
  selector: 'app-navigation-bar',
  templateUrl: './navigation-bar.component.html',
  styleUrls: ['./navigation-bar.component.scss']
})
export class NavigationBarComponent implements OnInit, OnDestroy {
  private sub: any;
  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.sub = this.router.events.subscribe(val => {
      if (val instanceof RoutesRecognized) {
        console.log(val.state.root.firstChild.params);
      }
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

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

well got this answer from another site and don't want to take any credit for this but this solution works like butter.

Go to File\Settings\Gradle. Deselect the "Offline work" box. Now you can connect and download any necessary or missing dependencies.

NullInjectorError: No provider for AngularFirestore

import angularFirebaseStore 

in app.module.ts and set it as a provider like service

How to add CORS request in header in Angular 5

You can also try the fetch function and the no-cors mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Your initial statement in the marked solution isn't entirely true. While your new solution may accomplish your original goal, it is still possible to circumvent the original error while preserving your AuthorizationHandler logic--provided you have basic authentication scheme handlers in place, even if they are functionally skeletons.

Speaking broadly, Authentication Handlers and schemes are meant to establish + validate identity, which makes them required for Authorization Handlers/policies to function--as they run on the supposition that an identity has already been established.

ASP.NET Dev Haok summarizes this best best here: "Authentication today isn't aware of authorization at all, it only cares about producing a ClaimsPrincipal per scheme. Authorization has to be aware of authentication somewhat, so AuthenticationSchemes in the policy is a mechanism for you to associate the policy with schemes used to build the effective claims principal for authorization (or it just uses the default httpContext.User for the request, which does rely on DefaultAuthenticateScheme)." https://github.com/aspnet/Security/issues/1469

In my case, the solution I'm working on provided its own implicit concept of identity, so we had no need for authentication schemes/handlers--just header tokens for authorization. So until our identity concepts changes, our header token authorization handlers that enforce the policies can be tied to 1-to-1 scheme skeletons.

Tags on endpoints:

[Authorize(AuthenticationSchemes = "AuthenticatedUserSchemeName", Policy = "AuthorizedUserPolicyName")]

Startup.cs:

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = "AuthenticatedUserSchemeName";
        }).AddScheme<ValidTokenAuthenticationSchemeOptions, ValidTokenAuthenticationHandler>("AuthenticatedUserSchemeName", _ => { });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("AuthorizedUserPolicyName", policy =>
            {
                //policy.RequireClaim(ClaimTypes.Sid,"authToken");
                policy.AddAuthenticationSchemes("AuthenticatedUserSchemeName");
                policy.AddRequirements(new ValidTokenAuthorizationRequirement());
            });
            services.AddSingleton<IAuthorizationHandler, ValidTokenAuthorizationHandler>();

Both the empty authentication handler and authorization handler are called (similar in setup to OP's respective posts) but the authorization handler still enforces our authorization policies.

CSS class for pointer cursor

I usually just add the following custom CSS, the W3School example prepended with cursor-

_x000D_
_x000D_
.cursor-alias {cursor: alias;}_x000D_
.cursor-all-scroll {cursor: all-scroll;}_x000D_
.cursor-auto {cursor: auto;}_x000D_
.cursor-cell {cursor: cell;}_x000D_
.cursor-context-menu {cursor: context-menu;}_x000D_
.cursor-col-resize {cursor: col-resize;}_x000D_
.cursor-copy {cursor: copy;}_x000D_
.cursor-crosshair {cursor: crosshair;}_x000D_
.cursor-default {cursor: default;}_x000D_
.cursor-e-resize {cursor: e-resize;}_x000D_
.cursor-ew-resize {cursor: ew-resize;}_x000D_
.cursor-grab {cursor: -webkit-grab; cursor: grab;}_x000D_
.cursor-grabbing {cursor: -webkit-grabbing; cursor: grabbing;}_x000D_
.cursor-help {cursor: help;}_x000D_
.cursor-move {cursor: move;}_x000D_
.cursor-n-resize {cursor: n-resize;}_x000D_
.cursor-ne-resize {cursor: ne-resize;}_x000D_
.cursor-nesw-resize {cursor: nesw-resize;}_x000D_
.cursor-ns-resize {cursor: ns-resize;}_x000D_
.cursor-nw-resize {cursor: nw-resize;}_x000D_
.cursor-nwse-resize {cursor: nwse-resize;}_x000D_
.cursor-no-drop {cursor: no-drop;}_x000D_
.cursor-none {cursor: none;}_x000D_
.cursor-not-allowed {cursor: not-allowed;}_x000D_
.cursor-pointer {cursor: pointer;}_x000D_
.cursor-progress {cursor: progress;}_x000D_
.cursor-row-resize {cursor: row-resize;}_x000D_
.cursor-s-resize {cursor: s-resize;}_x000D_
.cursor-se-resize {cursor: se-resize;}_x000D_
.cursor-sw-resize {cursor: sw-resize;}_x000D_
.cursor-text {cursor: text;}_x000D_
.cursor-w-resize {cursor: w-resize;}_x000D_
.cursor-wait {cursor: wait;}_x000D_
.cursor-zoom-in {cursor: zoom-in;}_x000D_
.cursor-zoom-out {cursor: zoom-out;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<button type="button" class="btn btn-success cursor-pointer">Sample Button</button>
_x000D_
_x000D_
_x000D_

No provider for HttpClient

Just Add HttpClientModule in 'imports' array of app.module.ts file.

...
import {HttpClientModule} from '@angular/common/http'; // add this line
@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule, //add this line
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

and then you can use HttpClient in your project through constructor injection

  import {HttpClient} from '@angular/common/http';
  
  export class Services{
  constructor(private http: HttpClient) {}

Angular 5 Service to read local .json file

I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".

Just call require:

const content = require('../../path_of_your.json');

The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl property by template and the value by a require call to the actual HTML resource.

If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json:

"compilerOptions": {
  "types": ["node"],
  ...
},
...

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

For me it was caused by a server side JsonSerializerException.

An unhandled exception has occurred while executing the request Newtonsoft.Json.JsonSerializationException: Self referencing loop detected with type ...

The client said:

POST http://localhost:61495/api/Action net::ERR_INCOMPLETE_CHUNKED_ENCODING
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

Making the response type simpler by eliminating the loops solved the problem.

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Note- position really matters add google() before jcenter()

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

Failed to run sdkmanager --list with Java 9

With the help of this answer, I successfully solved the problem.

We are going to apply a fix in sdkmanager. It is a shell script. It is located at $android_sdk/tools/bin, where $android_sdk is where you unzipped the Android SDK.

  1. Open sdkmanager in your favorite editor.
  2. Locate the line which sets the DEFAULT_JVM_OPTSvariable. In my copy, it is at line 31:

    DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME"'
    
  3. Append the following options to the variable: -XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee. Please pay attention to the quotes. In my copy, the line becomes:

    DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME" -XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
    
  4. Save the file and quit the editor.
  5. Run the command again.

Here is the result:

$ sdkmanager --list
Installed packages:
  Path    | Version | Description              | Location
  ------- | ------- | -------                  | ------- 
  tools   | 26.0.1  | Android SDK Tools 26.0.1 | tools/  

Available Packages:
  Path                              | Version      | Description                      
  -------                           | -------      | -------                          
  add-ons;addon-g..._apis-google-15 | 3            | Google APIs                      
  add-ons;addon-g..._apis-google-16 | 4            | Google APIs                      
  add-ons;addon-g..._apis-google-17 | 4            | Google APIs                      
  add-ons;addon-g..._apis-google-18 | 4            | Google APIs                      
  add-ons;addon-g..._apis-google-19 | 20           | Google APIs                      
  add-ons;addon-g..._apis-google-21 | 1            | Google APIs                      
  add-ons;addon-g..._apis-google-22 | 1            | Google APIs                      
  add-ons;addon-g..._apis-google-23 | 1            | Google APIs                      
  add-ons;addon-g..._apis-google-24 | 1            | Google APIs
...

Hola! It works!

-- Edit: 2017-11-07 --

Please note that you may need to apply the fix above again after running sdkmanager --update, since the sdkmanager shell script may be overridden if the tools package is updated.

Related Answers

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

Android Studio 3.0 Execution failed for task: unable to merge dex

I Have Done and fixed this issue by just doing this jobs in my code

Open ->build.gradle Change value from

compile 'com.google.code.gson:gson:2.6.1'

to

compile 'com.google.code.gson:gson:2.8.2'

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

I ran into the same issue and adding mavenCentral() in the repositories block of my build.gradle file worked for me. I had Offline work unchecked and adding maven { url "https://maven.google.com" }. Adding this answer for the lost souls that find themselves at end of this thread.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

My error was calling NgbModal open method with incorrect parameters from .html

how to open Jupyter notebook in chrome on windows

  • Run the jupyter notebook --generate-config command on the anaconda prompt.
  • Then edit the jupyter_notebook_config.py file.

Find the c.NotebookApp.Browser like this:

c.NotebookApp.browser = 'c:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'

Works on mine.

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

@Test annotation must be imported from org.junit.jupiter.api.Test so the Junit5 can read it. Junit4 use @Test annotations imported from org.junit.Test package.

Angular - res.json() is not a function

Don't need to use this method:

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

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

Please add a @Pipe/@Directive/@Component annotation. Error

The Above error occurs if any wrong import done. For example sometimes Service files may be added in TestBed.configureTestingModule. And also while importing Material component for example import from

import {MatDialogModule} from '@angular/material/dialog'

not from

import {MatDialogModule} from '@angular/material'

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case it was a component.member which was not existing e.g.

[formControl]="personId"

Adding it to the class declaration fixed it

this.personId = new FormControl(...)

Angular HttpClient "Http failure during parsing"

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

As of the latest version of the Android command-line tools (2.1 as of this writing), it is no longer necessary to patch sdkmanager nor to downgrade to an ancient version of Java.

Simply update your SDK packages and switch your command-line tools to the latest release, which will track new versions as they come:

sdkmanager --update
sdkmanager 'cmdline-tools;latest'
sdkmanager --uninstall 'cmdline-tools;1.0'

You may need to provide the full path to sdkmanager if it's not on your PATH, and you may need to adjust your PATH afterwards if it was referring to the 1.0 tools explicitly.

Unable to merge dex

check dependencies version if they are not same then make it same it will solve your problem

compile 'com.android.support:appcompat-v7:27.0.2'
compile 'com.android.support:recyclerview-v7:27.0.2'
compile 'com.android.support:cardview-v7:27.0.2'

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

I had the exact same problem while trying to setup a Gitlab pipeline executed by a Docker runner installed on a Raspberry Pi 4

Using nload to follow bandwidth usage within Docker runner container while pipeline was cloning the repo i saw the network usage dropped down to a few bytes per seconds..

After a some deeper investigations i figured out that the Raspberry temperature was too high and the network card start to dysfunction above 50° Celsius.

Adding a fan to my Raspberry solved the issue.

How to use log4net in Asp.net core 2.0

I am porting a .Net Framework console app to .Net Core and found a similar issue with log files not getting created under certain circumstances.

When using "CreateRepository" there appears to be a difference between .net framework and .net standard.

Under .Net Framework this worked to create a unique Log instance with it's own filename using the same property from log4net.config

GlobalContext.Properties["LogName"] = LogName;
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository);

Under .Net Standard this didn't work and if you turn on tracing you see it can't find the configuration file ".config". It wasn't loading the previous known configuration. Once I added the configuration to the configurator it still didn't log, while not complaining about it either.

To get it working under .Net Standard with similar behavior as before, this is what I did.

var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository,new FileInfo("log4net.config"));
var hierarchy = (Hierarchy) loggerRepository;
var appender = (RollingFileAppender)hierarchy.Root.GetAppender("RollingLogFileAppender");
appender.File = Path.Combine(Directory.GetCurrentDirectory(), "logs", $"{LogName}.log");

I didn't want to create a configuration file for every repo, so this works. Perhaps there is a better way to get the .Net Framework behavior as before and if there is please let me know below.

Can't install laravel installer via composer

For Mac with Macports,

# port install php71-zip

Catching errors in Angular HttpClient

By using Interceptor you can catch error. Below is code:

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //Get Auth Token from Service which we want to pass thr service call
    const authToken: any = `Bearer ${sessionStorage.getItem('jwtToken')}`
    // Clone the service request and alter original headers with auth token.
    const authReq = req.clone({
      headers: req.headers.set('Content-Type', 'application/json').set('Authorization', authToken)
    });

    const authReq = req.clone({ setHeaders: { 'Authorization': authToken, 'Content-Type': 'application/json'} });

    // Send cloned request with header to the next handler.
    return next.handle(authReq).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        console.log("Service Response thr Interceptor");
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        console.log("err.status", err);
        if (err.status === 401 || err.status === 403) {
          location.href = '/login';
          console.log("Unauthorized Request - In case of Auth Token Expired");
        }
      }
    });
  }
}

You can prefer this blog..given simple example for it.

Property 'json' does not exist on type 'Object'

The other way to tackle it is to use this code snippet:

JSON.parse(JSON.stringify(response)).data

This feels so wrong but it works

How to get param from url in angular 4?

This should do the trick retrieving the params from the url:

constructor(private activatedRoute: ActivatedRoute) {
  this.activatedRoute.queryParams.subscribe(params => {
        let date = params['startdate'];
        console.log(date); // Print the parameter to the console. 
    });
}

The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).

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

I had the same problem with the laravel initiation. The solution was as follows.

1st - I checked the version of my PHP. That it was 5.6 would soon give problem with the laravel.

2nd - I changed the version of my PHP to PHP 7.1.1. ATTENTION, in my case I changed my environment variable that was getting Xampp's PHP version 5.6 I changed to 7.1.1 for laragon.

3rd - I went to the terminal / console and navigated to my folder where my project was and typed the following command: php artisan serves. And it worked! In my case it started at the port: 8000 see example below.

C: \ laragon \ www \ first> php artisan serves Laravel development server started: http://127.0.0.1:8000

I hope I helped someone who has been through the same problem as me.

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

If you need in different Layer :

Create a Static Class and expose all config properties on that layer as below :

_x000D_
_x000D_
using Microsoft.Extensions.Configuration;_x000D_
using System.IO;_x000D_
_x000D_
namespace Core.DAL_x000D_
{_x000D_
    public static class ConfigSettings_x000D_
    {_x000D_
        public static string conStr1 { get ; }_x000D_
        static ConfigSettings()_x000D_
        {_x000D_
            var configurationBuilder = new ConfigurationBuilder();_x000D_
            string path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");_x000D_
            configurationBuilder.AddJsonFile(path, false);_x000D_
            conStr1 = configurationBuilder.Build().GetSection("ConnectionStrings:ConStr1").Value;_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Search input with an icon Bootstrap 4

I made another variant with dropdown menu (perhaps for advanced search etc).. Here is how it looks like:

Bootstrap 4 searh bar with dropdown menu

<div class="input-group my-4 col-6 mx-auto">
    <input class="form-control py-2 border-right-0 border" type="search" placeholder="Type something..." id="example-search-input">
    <span class="input-group-append">
        <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split border border-left-0 border-right-0 rounded-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <span class="sr-only">Toggle Dropdown</span>
        </button>
        <button class="btn btn-outline-primary rounded-right" type="button">
            <i class="fas fa-search"></i>
        </button>
        <div class="dropdown-menu dropdown-menu-right">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
            <a class="dropdown-item" href="#">Something else here</a>
            <div role="separator" class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Separated link</a>
        </div>
    </span>
</div>

Note: It appears green in the screenshot because my site main theme is green.

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

Make sure you're adding these dependencies in android/app/build.gradle, not android/build.gradle

Getting Image from API in Angular 4/5+?

There is no need to use angular http, you can get with js native functions

_x000D_
_x000D_
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
     // on the first then you will return blob from response_x000D_
    return await fetch(url).then(r => r.blob())_x000D_
    .then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
         _x000D_
        return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;_x000D_
    });_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
    // with file reader you will transform the file in a data url file;_x000D_
    var reader = new FileReader();_x000D_
    reader.readAsDataURL(file);_x000D_
    reader.onloadend = () => {_x000D_
    _x000D_
    // just putting the data url to img element_x000D_
        document.querySelector('#image').src = reader.result ;_x000D_
    }_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
_x000D_
_x000D_

Kotlin Android start new Activity

You have to give the second argument of class type. You can also have it a little bit more tidy like below.

startActivity(Intent(this, Page2::class.java).apply {
    putExtra("extra_1", value1)
    putExtra("extra_2", value2)
    putExtra("extra_3", value3)
})

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

For fire base to install properly all the versions of the fire base compiles must be in same version so

compile 'com.google.firebase:firebase-messaging:11.0.4' 
compile 'com.google.android.gms:play-services-maps:11.0.4' 
compile 'com.google.android.gms:play-services-location:11.0.4'

this is the correct way to do it.

Angular 4 HttpClient Query Parameters

If you have an object that can be converted to {key: 'stringValue'} pairs, you can use this shortcut to convert it:

this._Http.get(myUrlString, {params: {...myParamsObject}});

I just love the spread syntax!

Anaconda vs. miniconda

Anaconda or Miniconda?

Choose Anaconda if you:

  1. Are new to conda or Python.

  2. Like the convenience of having Python and over 1,500 scientific packages automatically installed at once.

  3. Have the time and disk space---a few minutes and 3 GB.

  4. Do not want to individually install each of the packages you want to use.

Choose Miniconda if you:

  1. Do not mind installing each of the packages you want to use individually.

  2. Do not have time or disk space to install over 1,500 packages at once.

  3. Want fast access to Python and the conda commands and you wish to sort out the other programs later.

Source

How to get autocomplete in jupyter notebook without using tab?

I would suggest hinterland extension.

In other answers I couldn't find the method for how to install it from pip, so this is how you install it.

First, install jupyter contrib nbextensions by running

pip install jupyter_contrib_nbextensions

Next install js and css file for jupyter by running

jupyter contrib nbextension install --user

and at the end run,

jupyter nbextension enable hinterland/hinterland

The output of last command will be

Enabling notebook extension hinterland/hinterland...
      - Validating: OK

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

change

compile 'com.android.support:appcompat-v7:26.0'

to

`compile 'com.android.support:appcompat-v7:26.+'`

worked for me fine.

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I was facing the same issue for one of my PhoneGap project (Android studio 3.0.1). To resolve this I have followed, the following step

1) Right click on Project name (In my Case android), select "Open Module Settings"

2) Select modules (android and CordovaLib)

3) Click properties on top

4) Chose Compile SDK version (I have chosen API 26: Android 8.0 )

5) Choose Build Tools Version (I have chosen 26.0.2)

6) Source Compatibility ( 1.6)

7) Target Compatibility ( 1.6)

Click Ok and rebuild project.

The following link shows my setting for step I have followed

https://app.box.com/s/o11xc8dy0c2c7elsaoppa0kwe1d94ogh https://app.box.com/s/ofdcg0a8n0zalumvpyju58he402ag1th

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:

let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');

or

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

Update: adding multiple headers

let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');

or

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

Update: accept object map for HttpClient headers & params

Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders object an directly pass an object map as argument. So now its possible to do the following:

http.get('someurl',{
   headers: {'header1':'value1','header2':'value2'}
});

How to format JSON in notepad++

Always google so you can locate the latest package for both NPP and NPP Plugins.

I googled "notepad++ 64bit". Downloaded the free latest version at Notepad++ (64-bit) - Free download and software. Installed notepad++ by double-click on npp.?.?.?.Installer.x64.exe, installed the .exe to default Windows 64bit path which is, "C:\Program Files".

Then, I googled "notepad++ 64 json viewer plug". Knowing SourceForge.Net is a renowned download site, downloaded JSToolNpp [email protected]. I unzipped and copied JSMinNPP.dll to notePad++ root dir.

I loaded my newly installed notepad++ 64bit. I went to Settings and selected [import plug-in]. I pointed to the location of JSMinNPP.dll and clicked open.

I reloaded notepad++, went to PlugIns menu. To format one-line json string to multi-line json doc, I clicked JSTool->JSFormat or reverse multi-line json doc to one-line json string by JSTool->JSMin (json-Minified)!

All items are in this picture.

Angular 4.3 - HttpClient set params

Another option to do it is:

this.httpClient.get('path', {
    params: Object.entries(data).reduce(
    (params, [key, value]) => params.set(key, value), new HttpParams());
});

Cannot find the '@angular/common/http' module

note: This is for @angular/http, not the asked @angular/common/http!

Just import in this way, WORKS perfectly:

// Import HttpModule from @angular/http
import {HttpModule} from '@angular/http';


@NgModule({
  declarations: [
    MyApp,
    HelloIonicPage,
    ItemDetailsPage,
    ListPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [... ]
})

and then you contruct in the service.ts like this:

constructor(private http: Http) { }

getmyClass(): Promise<myClass[]> {
  return this.http.get(URL)
             .toPromise()
             .then(response => response.json().data as myClass[])
             .catch(this.handleError);
}

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Difference between HttpModule and HttpClientModule

HttpClient is a new API that came with 4.3, it has updated API's with support for progress events, json deserialization by default, Interceptors and many other great features. See more here https://angular.io/guide/http

Http is the older API and will eventually be deprecated.

Since their usage is very similar for basic tasks I would advise using HttpClient since it is the more modern and easy to use alternative.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Component is not part of any NgModule or the module has not been imported into your module

I ran into this same issue and none of what I was seeing here was working. If you are listing your Component in the app-routing.module issue you may have run into the same problem I was having.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './app.routing';
import {HomeModule} from './Home/home.module';
// import HomeComponent here

@NgModule({
  declarations: [
    AppComponent,
    FooterbarComponent,
    TopbarComponent,
    NavbarComponent,
    // add HomeComponent here
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule,
    HomeModule  // remove this

  ],
  providers: [MRDBGlobalConstants],
  bootstrap: [AppComponent]
})
export class AppModule { }

home/index.ts

export * from './';

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components';

const routes: Routes = [
    { path: 'app/home', component: HomeComponent },
    { path: '', redirectTo: 'app/home', pathMatch: 'full' },
    { path: '**', redirectTo: 'app/home' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

home/home.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { HomeComponent } from './home.component'; This would cause app to break
import { HomeComponent } from './';
@NgModule({
  imports: [
    CommonModule
  ],
  exports: [HomeComponent],
  declarations: [HomeComponent]
})
export class HomeModule { }

I won't claim to understand exactly why this is the case, but when using indexing to export components (and I would assume the same for services, etc.), when referencing the same component in separate modules you need to import them from the same file, in this case the index, in order to avoid this issue.

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

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

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

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

If issue remains even after updating dependency version, then delete everything present under
C:\Users\[your_username]\.m2\repository\com\fasterxml

And, make sure following dependencies are present:

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>

Android dependency has different version for the compile and runtime

The answer for me was to also add this to my build.gradle file:

configurations.all {
  resolutionStrategy.eachDependency { details ->
      if (details.requested.group == 'com.android.support'
              && !details.requested.name.contains('multidex') ) {
          details.useVersion "26.1.0"
      }
  }
}

In my case, it was nessisary to enclose the resolution strategy in a configurations.all { .. } block. I placed the configurations.all block directly into my app/build.gradle file (ie configurations.all was not nested in anything else)

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

I had a very similar problem after moving a working project to a new subdirectory on my file system. It turned out I had failed to move the file named .angular-cli.json to the subfolder along with everything else. After noticing that and moving the file into the subdirectory, all was back to normal.

'router-outlet' is not a known element

Thank you Hero Editor example, where I found the correct definition:

When I generate app routing module:

ng generate module app-routing --flat --module=app

and update the app-routing.ts file to add:

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

Here are the full example:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent }   from './dashboard/dashboard.component';
import { HeroesComponent }      from './heroes/heroes.component';
import { HeroDetailComponent }  from './hero-detail/hero-detail.component';

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

and add AppRoutingModule into app.module.ts imports:

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [...],
  bootstrap: [AppComponent]
})

Setting up Gradle for api 26 (Android)

you must add in your MODULE-LEVEL build.gradle file with:

//module-level build.gradle file
repositories {
    maven {
        url 'https://maven.google.com'

    }
}

see: Google's Maven repository

I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

//project-level build.gradle file
allprojects {
 repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
  }
}

UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

What's the difference between implementation and compile in Gradle?

Brief Solution:

The better approach is to replace all compile dependencies with implementation dependencies. And only where you leak a module’s interface, you should use api. That should cause a lot less recompilation.

 dependencies {
         implementation fileTree(dir: 'libs', include: ['*.jar'])
 
         implementation 'com.android.support:appcompat-v7:25.4.0'
         implementation 'com.android.support.constraint:constraint-layout:1.0.2'
         // …
 
         testImplementation 'junit:junit:4.12'
         androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
             exclude group: 'com.android.support', module: 'support-annotations'
         })
 }

Explain More:

Before Android Gradle plugin 3.0: we had a big problem which is one code change causes all modules to be recompiled. The root cause for this is that Gradle doesn’t know if you leak the interface of a module through another one or not.

After Android Gradle plugin 3.0: the latest Android Gradle plugin now requires you to explicitly define if you leak a module’s interface. Based on that it can make the right choice on what it should recompile.

As such the compile dependency has been deprecated and replaced by two new ones:

  • api: you leak the interface of this module through your own interface, meaning exactly the same as the old compile dependency

  • implementation: you only use this module internally and does not leak it through your interface

So now you can explicitly tell Gradle to recompile a module if the interface of a used module changes or not.

Courtesy of Jeroen Mols blog

Bootstrap 4: Multilevel Dropdown Inside Navigation

The following is MultiLevel dropdown based on bootstrap4. I tried it was according to the bootstrap4 basic dropdown.

_x000D_
_x000D_
.dropdown-submenu{_x000D_
    position: relative;_x000D_
}_x000D_
.dropdown-submenu a::after{_x000D_
    transform: rotate(-90deg);_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 40%;_x000D_
}_x000D_
.dropdown-submenu:hover .dropdown-menu, .dropdown-submenu:focus .dropdown-menu{_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    position: absolute !important;_x000D_
    margin-top: -30px;_x000D_
    left: 100%;_x000D_
}_x000D_
@media (max-width: 992px) {_x000D_
    .dropdown-menu{_x000D_
        width: 50%;_x000D_
    }_x000D_
    .dropdown-menu .dropdown-submenu{_x000D_
        width: auto;_x000D_
    }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link 1</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" data-toggle="dropdown" href="#">Something else here</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <a class="dropdown-item" href="#">A</a>_x000D_
              <a class="dropdown-item" href="#">b</a>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Get Path from another app (WhatsApp)

You can't get a path to file from WhatsApp. They don't expose it now. The only thing you can get is InputStream:

InputStream is = getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/16695"));

Using is you can show a picture from WhatsApp in your app.

Failed to load AppCompat ActionBar with unknown error in android studio

The solution to this problem depends on the version of the Android support library you're using:

Support library 26.0.0-beta2

This android support library version has a bug causing the mentioned problem

In your Gradle build file use:

compile 'com.android.support:appcompat-v7:26.0.0'

with:

buildToolsVersion '26.0.0' 

and

classpath 'com.android.tools.build:gradle:3.0.0-alpha8'

everything should work fine now.


Library version 28 (beta)

These new versions seem to suffer from similar difficulties again.

In your res/values/styles.xml modify the AppTheme style from

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

(note the added Base.)

Or alternatively downgrade the library until the problem is fixed:

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

Cannot find control with name: formControlName in angular reactive form

I also had this error, and you helped me solve it. If formGroup or formGroupName are not written with the good case, then the name of the control is not found. Correct the case of formGroup or formGroupName and it is OK.

Is there a way to list all resources in AWS

I think this may help! Here, you need to enter the region name and you have to configure AWS CLI before try this.

aws resourcegroupstaggingapi get-resources --region region_name

It will list all the recourses in the region by the following format.

- ResourceARN: arn:aws:cloudformation:eu-west-1:5524534535:stack/auction-services-dev/*******************************
  Tags:
  - Key: STAGE
    Value: dev
- ResourceARN: arn:aws:cloudformation:eu-west-1:********************
Tags:
-- More  --

More than one file was found with OS independent path 'META-INF/LICENSE'

Try to remove multidex from default config and check the build error log. If that log is some relatable with INotification class. Use this in android{}

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
}

This helps me.

Customize Bootstrap checkboxes

_x000D_
_x000D_
/* The customcheck */_x000D_
.customcheck {_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    padding-left: 35px;_x000D_
    margin-bottom: 12px;_x000D_
    cursor: pointer;_x000D_
    font-size: 22px;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
    position: absolute;_x000D_
    opacity: 0;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 25px;_x000D_
    width: 25px;_x000D_
    background-color: #eee;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
    background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
    background-color: #02cf32;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
    content: "";_x000D_
    position: absolute;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
    left: 9px;_x000D_
    top: 5px;_x000D_
    width: 5px;_x000D_
    height: 10px;_x000D_
    border: solid white;_x000D_
    border-width: 0 3px 3px 0;_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
 <h1>Custom Checkboxes</h1></br>_x000D_
 _x000D_
        <label class="customcheck">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Three_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Four_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

I had a similar problem after updating my VS2017. Project built fine; but lots of 'errors' when code was brought up in the editor. Even tried reinstalling VS. I was able to solve it by setting the option “Ignore Standard Include Paths” to Yes. Attempted to build the solution with lots of errors. Went back and set the option to No. After rebuilding, my problem went away.

Android Room - simple select query - Cannot access database on the main thread

For quick queries you can allow room to execute it on UI thread.

AppDatabase db = Room.databaseBuilder(context.getApplicationContext(),
        AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();

In my case I had to figure out of the clicked user in list exists in database or not. If not then create the user and start another activity

       @Override
        public void onClick(View view) {



            int position = getAdapterPosition();

            User user = new User();
            String name = getName(position);
            user.setName(name);

            AppDatabase appDatabase = DatabaseCreator.getInstance(mContext).getDatabase();
            UserDao userDao = appDatabase.getUserDao();
            ArrayList<User> users = new ArrayList<User>();
            users.add(user);
            List<Long> ids = userDao.insertAll(users);

            Long id = ids.get(0);
            if(id == -1)
            {
                user = userDao.getUser(name);
                user.setId(user.getId());
            }
            else
            {
                user.setId(id);
            }

            Intent intent = new Intent(mContext, ChatActivity.class);
            intent.putExtra(ChatActivity.EXTRAS_USER, Parcels.wrap(user));
            mContext.startActivity(intent);
        }
    }

Android Studio - Failed to notify project evaluation listener error

In my case I had to update all the Firebase libraries to the latest versions.

Load json from local file with http.get() in angular 2

If you are using Angular CLI: 7.3.3 What I did is, On my assets folder I put my fake json data then on my services I just did this.

const API_URL = './assets/data/db.json';

getAllPassengers(): Observable<PassengersInt[]> {
    return this.http.get<PassengersInt[]>(API_URL);
  }

enter image description here

If '<selector>' is an Angular component, then verify that it is part of this module

are you importing it in your app.module.ts like so and remove the directives bit:-

@NgModule({
    bootstrap: [AppComponent],
    imports: [MyComponentModule],// or whatever the name of the module is that declares your component.

    declarations: [AppComponent],
    providers: []
})
export class AppModule {}

Your MyComponentModule should be like this:-

@NgModule({
    imports: [],
    exports: [MyComponentComponent],
    declarations: [MyComponentComponent],
    providers: [],
})
export class MyComponentModule {
}

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

Visual Studio Code pylint: Unable to import 'protorpc'

I was still getting these errors even after confirming that the correct python and pylint were being used from my virtual env.

Eventually I figured out that in Visual Studio Code I was A) opening my project directory, which is B) where my Python virtual environment was, but I was C) running my main Python program from two levels deeper. Those three things need to be in sync for everything to work.

Here's what I would recommend:

  1. In Visual Studio Code, open the directory containing your main Python program. (This may or may not be the top level of the project directory.)

  2. Select Terminal menu > New Terminal, and create an virtual environment directly inside the same directory.

    python3 -m venv env
    
  3. Install pylint in the virtual environment. If you select any Python file in the sidebar, Visual Studio Code will offer to do this for you. Alternatively, source env/bin/activate then pip install pylint.

  4. In the blue bottom bar of the editor window, choose the Python interpreter env/bin/python. Alternatively, go to Settings and set "Python: Python Path." This sets python.pythonPath in Settings.json.

How to Install Font Awesome in Laravel Mix

For Laravel >= 5.5

  • Run npm install font-awesome --save
  • Add @import "~font-awesome/scss/font-awesome.scss"; in resources/assets/saas/app.scss
  • Run npm run dev (or npm run watch or even npm run production)

PHP7 : install ext-dom issue

sudo apt install php-xml will work but the thing is it will download the plugin for the latest PHP version.

If your PHP version is not the latest, then you can add version in it:

# PHP 7.1
sudo apt install php7.1-xml

# PHP 7.2:
sudo apt install php7.2-xml

# PHP 7.3
sudo apt install php7.3-xml


# PHP 7.4
sudo apt install php7.4-xml

# PHP 8
sudo apt install php-xml

Is Visual Studio Community a 30 day trial?

IMPORTANT DISCLAIMER: Information provided below is for educational purposes only! Extending a trial period of Visual Studio Community 2017 might be ILLEGAL!

So let's get started.

Registry key of interest: HKEY_CLASSES_ROOT\Licenses\5C505A59-E312-4B89-9508-E162F8150517\08878. I assume the 08878 subkey may differ from installation to installation (why not, isn't?). I have tested only on my own one. So check other subkeys if you can not match proper values described below. Binary value stored in that key is encrypted with CryptProtectData. So decrypt it first with CryptUnprotectData. Bytes of interest (little-endian):

  • [-16] and [-15] is a year of expiration;
  • [-14] and [-13] is a month of expiration;
  • [-12] and [-11] is a day of expiration.

Increasing these values (preferable the year :) ) WILL extend your trial period and get rid of a blocking screen! I know nothing of such a tool that allows to edit encrypted registry values, so my small program in C++ and Windows API looks like:

RegGetValue
CryptUnprotectData
Data.pbData[Data.cbData-16]++;
CryptProtectData
RegSetValue

Actual language doesn't matter if you have access to registry and crypto functions in your language. I'm just fluent in C++. Sorry, I do not publish a ready-to-use code for ethical reason.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

I changed all support library versions to 25.3.1 and worked like a charm:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'

You also need to change compileSdkVersion and targetSdkVersion to 25:

compileSdkVersion 25
targetSdkVersion 25

How to POST using HTTPclient content type = application/x-www-form-urlencoded

 var params= new Dictionary<string, string>();
 var url ="Please enter URLhere"; 
 params.Add("key1", "value1");
 params.Add("key2", "value2");

 using (HttpClient client = new HttpClient())
  {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
              var tokne= response.Content.ReadAsStringAsync().Result;
}

//Get response as expected

How to center the elements in ConstraintLayout

add these tag in your view

    app:layout_constraintCircleRadius="0dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"

and you can right click in design mode and choose center.

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

Make sure you are using default gradle wrapper in Open File > Settings > Build,Execution,Deployment > Build Tools > Gradle.

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.

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

My system version: ubuntu 20.04 LTS.

  • I solved this by generate a new MOK and enroll it into shim.

  • Without disable of Secure Boot, although it also really works for me.

  • Simply execute this command and follow what it suggests:

    sudo update-secureboot-policy --enroll-key
    

According to ubuntu's wiki: How can I do non-automated signing of drivers

No provider for Router?

Nothing works from this tread. "forRoot" doesn't help.

Sorry. Sorted this out. I've managed to make it work by setting correct "routes" for this "forRoot" router setup routine


    import {RouterModule, Routes} from '@angular/router';    
    import {AppComponent} from './app.component';
    
    const appRoutes: Routes = [
      {path: 'UI/part1/Details', component: DetailsComponent}
    ];
    
    @NgModule({
      declarations: [
        AppComponent,
        DetailsComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot(appRoutes)
      ],
      providers: [DetailsService],
      bootstrap: [AppComponent]
    })

Also may be helpful (spent some time to realize this) Optional route part:

    const appRoutes: Routes = [
       {path: 'UI/part1/Details', component: DetailsComponent},
       {path: ':project/UI/part1/Details', component: DetailsComponent}
    ];

Second rule allows to open URLs like
hostname/test/UI/part1/Details?id=666
and
hostname/UI/part1/Details?id=666

Been working as a frontend developer since 2012 but never stuck in a such over-complicated thing as angular2 (I have 3 years experience with enterprise level ExtJS)

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

Try this

npm i react-router-dom@next

in your App.js

import { BrowserRouter as Router, Route } from 'react-router-dom'

const Home = () => <h1>Home</h1>

const App = () =>(
  <Router>
    <Route path="/" component={Home} />
  </Router>
)

export default App;

CORS: credentials mode is 'include'

Just add Axios.defaults.withCredentials=true instead of ({credentials: true}) in client side, and change app.use(cors()) to

app.use(cors(
  {origin: ['your client side server'],
  methods: ['GET', 'POST'],
  credentials:true,
}
))

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Angular cli generate a service and include the provider in one step

slight change in syntax from the accepted answer for Angular 5 and angular-cli 1.7.0

ng g service backendApi --module=app.module

How to download Visual Studio 2017 Community Edition for offline installation?

Just use the following for a "minimal" C# installation:

vs_Community.exe --layout f:\vs2017c --lang en-US --add Microsoft.VisualStudio.Workload.ManagedDesktop

This works for sure. The error in your first commandline was the trailing backslash. Without it it works. You don't have to download all..

You can add for example the following workloads (or a subset) to the commandline:

Microsoft.VisualStudio.Workload.Data Microsoft.VisualStudio.Workload.NetWeb Microsoft.VisualStudio.Workload.Universal Microsoft.VisualStudio.Workload.NetCoreTools

Sometimes the downloader seems to not like too much packages. But you can download the packages (add the other workloads) step-by-step, this works. Like you want.

The interesting thing. The installer afterwards will download (only) the packages you selected which you have NOT downloaded before, so it is quite smart (in this point).

(Of course there are more packages available).

Google API authentication: Not valid origin for the client

Creating new oauth credentials worked for me

Laravel: PDOException: could not find driver

If you can, run :

composer update

composer require doctrine/dbal

It looks like you have a missing dependency

Edit:

You might need to comment out the following in your php.ini file.

;extension=pdo_mysql.so

Taken from this post: Laravel 5 PDOException Could Not Find Driver . I think I had to do something exactly like this when setting up laravel on digital ocean.

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

I faced the same issue, but fixed it by adding

maven { url "http://jcenter.bintray.com"}

in the project Level Gradle File

buildscript {
repositories {
    jcenter()
    maven { url "http://jcenter.bintray.com"}
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
}
}
allprojects {
repositories {
    mavenCentral()
    jcenter{ url "http://jcenter.bintray.com/" }
    maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

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

just add this :

compile 'com.android.support:mediarouter-v7:25.2.0'

Updated for new SDK versions

compile 'com.android.support:mediarouter-v7:28.0.0-alpha3'

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

Solution for me (Android Studio) :

1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure

2) and increase the level of SDK "Compile SDK Version".

Can't bind to 'routerLink' since it isn't a known property

You need to add RouterModule to imports of every @NgModule() where components use any component or directive from (in this case routerLink and <router-outlet>.

declarations: [] is to make components, directives, pipes, known inside the current module.

exports: [] is to make components, directives, pipes, available to importing modules. What is added to declarations only is private to the module. exports makes them public.

See also https://angular.io/api/router/RouterModule#usage-notes

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int it will be accepted as input (although it will be questionable if that's the right way to do it).

It would be better to convert your training scores by using scikit's labelEncoder function.

The same is true for your DecisionTree and KNeighbors qualifier.

from sklearn import preprocessing
from sklearn import utils

lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)

print(utils.multiclass.type_of_target(trainingScores))
>>> continuous

print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass

print(utils.multiclass.type_of_target(encoded))
>>> multiclass

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

Align button to the right

Maybe you can use float:right;:

_x000D_
_x000D_
.one {_x000D_
  padding-left: 1em;_x000D_
  text-color: white;_x000D_
   display:inline; _x000D_
}_x000D_
.two {_x000D_
  background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
  float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
 _x000D_
  </head>_x000D_
  <body>_x000D_
      <div class="row">_x000D_
       <h3 class="one">Text</h3>_x000D_
       <button class="btn btn-secondary pull-right">Button</button>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

go to the phpmyadmin and open the console and execute this request

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

`col-xs-*` not working in Bootstrap 4

They dropped XS because Bootstrap is considered a mobile-first development tool. It's default is considered xs and so doesn't need to be defined.

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Open a terminal and take a look at:

/Applications/Python 3.6/Install Certificates.command

Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.

(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)

How to read values from the querystring with ASP.NET Core?

StringValues is an array of strings. You can get your string value by providing an index, e.g. HttpContext.Request.Query["page"][0].

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

In my case, I added my component to declarations and entryComponents and got the same errors. I also needed to add MatDialogModule to imports.

Anaconda export Environment file

  1. First activate your conda environment (the one u want to export/backup)
conda activate myEnv
  1. Export all packages to a file (myEnvBkp.txt)
conda list --explicit > myEnvBkp.txt
  1. Restore/import the environment:
conda create --name myEnvRestored --file myEnvBkp.txt

Angular2 module has no exported member

I was facing same issue and I just started app with new port and everything looks good.

ng serve --port 4201

Unable to Resolve Module in React Native App

For me, using expo, I just had to restart expo. ctrl + c and yarn start or expo start and the run on ios simulator or your device, whichever you're testing with.

Changing background color of selected item in recyclerview

in the Kotlin you can do this simply: all you need is to create a static variable like this:

companion object {
     var last_position = 0
}

then in your onBindViewHolder add this code:

holder.item.setOnClickListener{
        holder.item.setBackgroundResource(R.drawable.selected_item)
        notifyItemChanged(last_position)
        last_position=position
    }

which item is the child of recyclerView which you want to change its background after clicking on it.

How to read request body in an asp.net core webapi controller?

In ASP.Net Core it seems complicated to read several times the body request, however if your first attempt does it the right way, you should be fine for the next attempts.

I read several turnaround for example by substituting the body stream, but I think the following is the cleanest:

The most important points being

  1. to let the request know that you will read its body twice or more times,
  2. to not close the body stream, and
  3. to rewind it to its initial position so the internal process does not get lost.

[EDIT]

As pointed out by Murad, you may also take advantage of the .Net Core 2.1 extension: EnableBuffering It stores large requests onto the disk instead of keeping it in memory, avoiding large-streams issues stored in memory (files, images, ...). You can change the temporary folder by setting ASPNETCORE_TEMP environment variable, and files are deleted once the request is over.

In an AuthorizationFilter, you can do the following:

// Helper to enable request stream rewinds
using Microsoft.AspNetCore.Http.Internal;
[...]
public class EnableBodyRewind : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var bodyStr = "";
        var req = context.HttpContext.Request;

        // Allows using several time the stream in ASP.Net Core
        req.EnableRewind(); 

        // Arguments: Stream, Encoding, detect encoding, buffer size 
        // AND, the most important: keep stream opened
        using (StreamReader reader 
                  = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
        {
            bodyStr = reader.ReadToEnd();
        }

        // Rewind, so the core is not lost when it looks the body for the request
        req.Body.Position = 0;

        // Do whatever work with bodyStr here

    }
}



public class SomeController : Controller
{
    [HttpPost("MyRoute")]
    [EnableBodyRewind]
    public IActionResult SomeAction([FromBody]MyPostModel model )
    {
        // play the body string again
    }
}

Then you can use the body again in the request handler.

In your case if you get a null result, it probably means that the body has already been read at an earlier stage. In that case you may need to use a middleware (see below).

However be careful if you handle large streams, that behavior implies that everything is loaded into memory, this should not be triggered in case of a file upload.

You may want to use this as a Middleware

Mine looks like this (again, if you download/upload large files, this should be disabled to avoid memory issues):

public sealed class BodyRewindMiddleware
{
    private readonly RequestDelegate _next;

    public BodyRewindMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try { context.Request.EnableRewind(); } catch { }
        await _next(context);
        // context.Request.Body.Dipose() might be added to release memory, not tested
    }
}
public static class BodyRewindExtensions
{
    public static IApplicationBuilder EnableRequestBodyRewind(this IApplicationBuilder app)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }

        return app.UseMiddleware<BodyRewindMiddleware>();
    }

}

Angular2: custom pipe could not be found

I encountered a similar issue, but putting it in my page’s module didn’t work.

I had created a component, which needed a pipe. This component was declared and exported in a ComponentsModule file, which holds all of the app’s custom components.

I had to put my PipesModule in my ComponentsModule as an import, in order for these components to use these pipes and not in the page’s module using that component.

Credits: enter link description here Answer by: tumain

error: package com.android.annotations does not exist

You shouldn't edit any code manually jetify should do this job for you, if you are running/building from cli using react-native you dont' need to do anything but if you are running/building Andriod studio you need to run jetify as pre-build, here is how can you automate this:

1- From the above menu go to edit configurations:

enter image description here

2- Add the bottom of the screen you will find before launch click on the plus and choose Run External Tool

enter image description here

2- Fill the following information, note that the working directory is your project root directory (not the android directory):

enter image description here

3- Make sure this run before anything else, in the end, your configuration should look something like this: enter image description here

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Django model "doesn't declare an explicit app_label"

I had a similar issue, but I was able to solve mine by specifying explicitly the app_label using Meta Class in my models class

class Meta:
    app_label  = 'name_of_my_app'

How to request Location Permission at runtime

check this code from MainActivity

 // Check location permission is granted - if it is, start
// the service, otherwise request the permission
fun checkOrAskLocationPermission(callback: () -> Unit) {
    // Check GPS is enabled
    val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "Please enable location services", Toast.LENGTH_SHORT).show()
        buildAlertMessageNoGps(this)
        return
    }

    // Check location permission is granted - if it is, start
    // the service, otherwise request the permission
    val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
    if (permission == PackageManager.PERMISSION_GRANTED) {
        callback.invoke()
    } else {
        // callback will be inside the activity's onRequestPermissionsResult(
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            PERMISSIONS_REQUEST
        )
    }
}

plus

   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == PERMISSIONS_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
              // Permission ok. Do work.
         }
    }
}

plus

 fun buildAlertMessageNoGps(context: Context) {
    val builder = AlertDialog.Builder(context);
    builder.setMessage("Your GPS is disabled. Do you want to enable it?")
        .setCancelable(false)
        .setPositiveButton("Yes") { _, _ -> context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }
        .setNegativeButton("No") { dialog, _ -> dialog.cancel(); }
    val alert = builder.create();
    alert.show();
}

usage

checkOrAskLocationPermission() {
            // Permission ok. Do work.
        }

Default FirebaseApp is not initialized

By following @Gabriel Lidenor answer, initializing app with context is not work in my case. What if you are trying to create firebase-app without google-service.json ? So before initializing any number of firebase app, first need to initialize as;

FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("APP_ID")
                    .setGcmSenderId("SENDER_ID").build();
FirebaseApp.initializeApp(context, options, "[DEFAULT]");

Bootstrap date time picker

Try This:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>_x000D_
  <script src="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
      <div class='col-sm-6'>_x000D_
        <div class="form-group">_x000D_
          <div class='input-group date' id='datetimepicker1'>_x000D_
            <input type='text' class="form-control" />_x000D_
            <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
            </span>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <script type="text/javascript">_x000D_
        $(function() {_x000D_
          $('#datetimepicker1').datetimepicker();_x000D_
        });_x000D_
      </script>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Deprecation warning in Moment.js - Not in a recognized ISO format

I ran into this error because I was trying to pass in a date from localStorage. Passing the date into a new Date object, and then calling .toISOString() did the trick for me:

const dateFromStorage = localStorage.getItem('someDate');
const date = new Date(dateFromStorage);
const momentDate = moment(date.toISOString());

This suppressed any warnings in the console.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

Plugin with id 'com.google.gms.google-services' not found

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

add above line at the bottom of your app gradle.build.

Min / Max Validator in Angular 2 Final

In latest Angular versions, min and max are already added. Here is the link: https://angular.io/api/forms/Validators#max

This is how I used Max validator in my project:

<mat-form-field class="globalInput">
          <input (change)="CalculateAmount()" matInput placeholder="Quantity" name="productQuantity" type="number" [formControl]="quantityFormControl">
        </mat-form-field>
        <mat-error *ngIf="quantityFormControl.hasError('max')">
          Only <strong>{{productQuantity}}</strong> available!
        </mat-error>

Initialize the form control and add the validator in the component:

  quantityFormControl = new FormControl('', Validators.max(15));

You can also set validator dynamically on an event like this:

  quantityFormControl = new FormControl();

OnProductSelected(){
    this.quantityFormControl.setValidators(Validators.max(this.someVariable));
  }

Hope it helps.

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

1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.

android {
   ...
   defaultConfig {
      multiDexEnabled true
      ...
   }
}

dependencies {
  // add dependency 
  implementation 'com.android.support:multidex:1.0.1'
}

2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        .
        .
        .
        .
        .
    </application>

3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.

    public class MyApplication extends Application {

    @Override 
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    } 

If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]

Hopefully, It works for you.

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306 - you provided 3360. The 3306 is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect() is the port, which is where it should be specified.

You could just remove the port specification altogether, as you're using the default port, making it

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

References

Angular2: Cannot read property 'name' of undefined

In order to avoid this, you could as well initialize the selectedHero member of your component to an empty object (instead of leaving it undefined).

In your example code, that would give something like this :

export class AppComponent {
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero:Hero = new Hero();

  onSelect(hero: Hero):void{
      this.selectedHero = hero;
  }
}

Apache POI error loading XSSFWorkbook class

Please note that 4.0 is not sufficient since ListValuedMap, was introduced in version 4.1.

You need to use this maven repository link for version 4.1. Replicated below for convenience

 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
 <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.1</version>
</dependency>

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

If you add the android:theme="@style/Theme.AppCompat.Light" to <application> in AndroidManifest.xml file, problem is solving.

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

This is fixed by:

a) adding schemas: [ CUSTOM_ELEMENTS_SCHEMA ] to every component or

b) adding

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

and

schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],

to your module.

How to import component into another root component in Angular 2

Angular RC5 & RC6

If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({}).

The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.

If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses> is in your template file.

Here is an example:

import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';

describe('CoursesComponent', () => {
  let component: CoursesComponent;
  let fixture: ComponentFixture<CoursesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CoursesComponent
      ],
      imports: [
        BrowserModule
        // If you have any other imports add them here
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoursesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

How to fetch JSON file in Angular 2

Keep the json file in Assets (parallel to app dir) directory

Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:

::app/services/myservice.ts

getOrderSummary(): Observable {
    // get users from api
    return this.http.get('assets/ordersummary.json')//, options)
        .map((response: Response) => {
            console.log("mock data" + response.json());
            return response.json();
        }
    )
    .catch(this.handleError);
} 

Extension gd is missing from your system - laravel composer Update

It may not be enabled for php-cli, you can enable like this;

sudo phpenmod gd

UPDATE

I guess, you are using ppa:ondrej php package (5.6), which is confusing you with default ubuntu 14.04 php package (5.5.9).

To install php 5.6 gd library from ppa:ondrej, you should use:

sudo apt-get install php5.6-gd

@ViewChild in *ngIf

As was mention by others, the fastest and quickest solution is to use [hidden] instead of *ngIf. Taking this approach the component will be created but not visible, therefore you have access to it. This might not be the most efficient way.

How to convert JSON object to an Typescript array?

To convert any JSON to array, use the below code:

const usersJson: any[] = Array.of(res.json());

Error: Unexpected value 'undefined' imported by the module

I had this issue, it is true that the error on the console ain't descriptive. But if you look at the angular-cli output:

You will see a WARNING, pointing to the circular dependency

WARNING in Circular dependency detected:
module1 -> module2
module2 -> module1

So the solution is to remove one import from one of the Modules.

Can't bind to 'formGroup' since it isn't a known property of 'form'

Import ReactiveFormsModule in the corresponded module

pandas dataframe convert column type to string or categorical

To convert a column into a string type (that will be an object column per se in pandas), use astype:

df.zipcode = zipcode.astype(str)

If you want to get a Categorical column, you can pass the parameter 'category' to the function:

df.zipcode = zipcode.astype('category')

Call child component method from parent class - Angular

I had an exact situation where the Parent-component had a Select element in a form and on submit, I needed to call the relevant Child-Component's method according to the selected value from the select element.

Parent.HTML:

<form (ngSubmit)='selX' [formGroup]="xSelForm">
    <select formControlName="xSelector">
      ...
    </select>
<button type="submit">Submit</button>
</form>
<child [selectedX]="selectedX"></child>

Parent.TS:

selX(){
  this.selectedX = this.xSelForm.value['xSelector'];
}

Child.TS:

export class ChildComponent implements OnChanges {
  @Input() public selectedX;

  //ngOnChanges will execute if there is a change in the value of selectedX which has been passed to child as an @Input.

  ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
    this.childFunction();
  }
  childFunction(){ }
}

Hope this helps.

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

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

ASP.NET Core Identity - get current user

private readonly UserManager<AppUser> _userManager;

 public AccountsController(UserManager<AppUser> userManager)
 {
            _userManager = userManager;
 }

[Authorize(Policy = "ApiUser")]
[HttpGet("api/accounts/GetProfile", Name = "GetProfile")]
public async Task<IActionResult> GetProfile()
{
   var userId = ((ClaimsIdentity)User.Identity).FindFirst("Id").Value;
   var user = await _userManager.FindByIdAsync(userId);

   ProfileUpdateModel model = new ProfileUpdateModel();
   model.Email = user.Email;
   model.FirstName = user.FirstName;
   model.LastName = user.LastName;
   model.PhoneNumber = user.PhoneNumber;

   return new OkObjectResult(model);
}

Load different application.yml in SpringBoot Test

We can use @SpringBootTest annotation which loads the yml file from src\main\java\com...hence when we execute the unit test, all of the properties are already there in the config properties class.

@RunWith(SpringRunner.class)
@SpringBootTest
public class AddressFieldsTest {

    @InjectMocks
    AddressFieldsValidator addressFieldsValidator;

    @Autowired
    AddressFieldsConfig addressFieldsConfig;
    ...........

    @Before
    public void setUp() throws Exception{
        MockitoAnnotations.initMocks(this);
        ReflectionTestUtils.setField(addressFieldsValidator,"addressFieldsConfig", addressFieldsConfig);
    }

}

We can use @Value annotation if you have few configs or other wise we can use a config properties class. For e.g

@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "address.fields.regex")
public class AddressFieldsConfig {

    private int firstName;
    private int lastName;
    .........

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I faced the same issue. I had missed the forms module import tag in the app.module.ts

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [BrowserModule,
        FormsModule
    ],

ASP.NET Core 1.0 on IIS error 502.5

I had the same problem.

To find out the exact source of it I switched on logging in web.config file:

<aspNetCore processPath="dotnet" arguments=".\MyWebService.dll" stdoutLogEnabled="**true**" stdoutLogFile=".\logs\stdout" />

and created logs subfolder in MyWebService root folder.

After restarting IIS and trying to execute API I got an error and it was missing of proper Core Runtime. After downloading an installing DotNetCore.1.0.5_1.1.2-WindowsHosting the error gone.

error: RPC failed; curl transfer closed with outstanding read data remaining

can be two reason

  1. Internet is slow (this was in my case)
  2. buffer size is less,in this case you can run command git config --global http.postBuffer 524288000

How to get HttpContext.Current in ASP.NET Core?

As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.

HttpContext.Current was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.

HttpContext property

You can access the current HTTP context via the HttpContext property on any controller. The closest thing to your original code sample would be to pass HttpContext into the method you are calling:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Other code
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Other code
}

HttpContext parameter in middleware

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically:

public Task Invoke(HttpContext context)
{
    // Do something with the current HTTP context...
}

HTTP context accessor

Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

Request this interface in your constructor:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

You can then access the current HTTP context in a safe way:

var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...

IHttpContextAccessor isn't always added to the service container by default, so register it in ConfigureServices just to be safe:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    // if < .NET Core 2.2 use this
    //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}

How to get current available GPUs in tensorflow?

Ensure you have the latest TensorFlow 2.x GPU installed in your GPU supporting machine, Execute the following code in python,

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf 

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

Will get an output looks like,

2020-02-07 10:45:37.587838: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-02-07 10:45:37.588896: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0, 1, 2, 3, 4, 5, 6, 7 Num GPUs Available: 8

Node.js heap out of memory

You can also change Window's environment variables with:

 $env:NODE_OPTIONS="--max-old-space-size=8192"

Getting "Cannot call a class as a function" in my React Project

Happened to me because I used

PropTypes.arrayOf(SomeClass)

instead of

PropTypes.arrayOf(PropTypes.instanceOf(SomeClass))

Deep copy in ES6 using the spread syntax

const cloneData = (dataArray) => {
    newData= []
    dataArray.forEach((value) => {
        newData.push({...value})
    })
    return newData
}
  • a = [{name:"siva"}, {name:"siva1"}] ;
  • b = myCopy(a)
  • b === a // false`

How to fix git error: RPC failed; curl 56 GnuTLS

Additionally,this error may occurs in you are using any proxy in command line.

if you export any proxy before , unset it .

$ unset all_proxy && unset ALL_PROXY

How to decode JWT Token?

Using .net core jwt packages, the Claims are available:

[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = "Bearer")]
public class AbstractController: ControllerBase
{
    protected string UserId()
    {
        var principal = HttpContext.User;
        if (principal?.Claims != null)
        {
            foreach (var claim in principal.Claims)
            {
               log.Debug($"CLAIM TYPE: {claim.Type}; CLAIM VALUE: {claim.Value}");
            }

        }
        return principal?.Claims?.SingleOrDefault(p => p.Type == "username")?.Value;
    }
}

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

How to use sed to remove all double quotes within a file

Additional comment. Yes this works:

    sed 's/\"//g' infile.txt  > outfile.txt

(however with batch gnu sed, will just print to screen)

In batch scripting (GNU SED), this was needed:

    sed 's/\x22//g' infile.txt  > outfile.txt

Check if returned value is not null and if so assign it, in one line, with one method call

If you're not on java 1.8 yet and you don't mind to use commons-lang you can use org.apache.commons.lang3.ObjectUtils#defaultIfNull

Your code would be:

dinner = ObjectUtils.defaultIfNull(cage.getChicken(),getFreeRangeChicken())

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

What are the differences between a multidimensional array and an array of arrays in C#?

A multidimensional array creates a nice linear memory layout while a jagged array implies several extra levels of indirection.

Looking up the value jagged[3][6] in a jagged array var jagged = new int[10][5] works like this: Look up the element at index 3 (which is an array) and look up the element at index 6 in that array (which is a value). For each dimension in this case, there's an additional look up (this is an expensive memory access pattern).

A multidimensional array is laid out linearly in memory, the actual value is found by multiplying together the indexes. However, given the array var mult = new int[10,30], the Length property of that multidimensional array returns the total number of elements i.e. 10 * 30 = 300.

The Rank property of a jagged array is always 1, but a multidimensional array can have any rank. The GetLength method of any array can be used to get the length of each dimension. For the multidimensional array in this example mult.GetLength(1) returns 30.

Indexing the multidimensional array is faster. e.g. given the multidimensional array in this example mult[1,7] = 30 * 1 + 7 = 37, get the element at that index 37. This is a better memory access pattern because only one memory location is involved, which is the base address of the array.

A multidimensional array therefore allocates a continuous memory block, while a jagged array does not have to be square, e.g. jagged[1].Length does not have to equal jagged[2].Length, which would be true for any multidimensional array.

Performance

Performance wise, multidimensional arrays should be faster. A lot faster, but due to a really bad CLR implementation they are not.

 23.084  16.634  15.215  15.489  14.407  13.691  14.695  14.398  14.551  14.252 
 25.782  27.484  25.711  20.844  19.607  20.349  25.861  26.214  19.677  20.171 
  5.050   5.085   6.412   5.225   5.100   5.751   6.650   5.222   6.770   5.305 

The first row are timings of jagged arrays, the second shows multidimensional arrays and the third, well that's how it should be. The program is shown below, FYI this was tested running mono. (The windows timings are vastly different, mostly due to the CLR implementation variations).

On windows, the timings of the jagged arrays are greatly superior, about the same as my own interpretation of what multidimensional array look up should be like, see 'Single()'. Sadly the windows JIT-compiler is really stupid, and this unfortunately makes these performance discussions difficult, there are too many inconsistencies.

These are the timings I got on windows, same deal here, the first row are jagged arrays, second multidimensional and third my own implementation of multidimensional, note how much slower this is on windows compared to mono.

  8.438   2.004   8.439   4.362   4.936   4.533   4.751   4.776   4.635   5.864
  7.414  13.196  11.940  11.832  11.675  11.811  11.812  12.964  11.885  11.751
 11.355  10.788  10.527  10.541  10.745  10.723  10.651  10.930  10.639  10.595

Source code:

using System;
using System.Diagnostics;
static class ArrayPref
{
    const string Format = "{0,7:0.000} ";
    static void Main()
    {
        Jagged();
        Multi();
        Single();
    }

    static void Jagged()
    {
        const int dim = 100;
        for(var passes = 0; passes < 10; passes++)
        {
            var timer = new Stopwatch();
            timer.Start();
            var jagged = new int[dim][][];
            for(var i = 0; i < dim; i++)
            {
                jagged[i] = new int[dim][];
                for(var j = 0; j < dim; j++)
                {
                    jagged[i][j] = new int[dim];
                    for(var k = 0; k < dim; k++)
                    {
                        jagged[i][j][k] = i * j * k;
                    }
                }
            }
            timer.Stop();
            Console.Write(Format,
                (double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
        }
        Console.WriteLine();
    }

    static void Multi()
    {
        const int dim = 100;
        for(var passes = 0; passes < 10; passes++)
        {
            var timer = new Stopwatch();
            timer.Start();
            var multi = new int[dim,dim,dim];
            for(var i = 0; i < dim; i++)
            {
                for(var j = 0; j < dim; j++)
                {
                    for(var k = 0; k < dim; k++)
                    {
                        multi[i,j,k] = i * j * k;
                    }
                }
            }
            timer.Stop();
            Console.Write(Format,
                (double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
        }
        Console.WriteLine();
    }

    static void Single()
    {
        const int dim = 100;
        for(var passes = 0; passes < 10; passes++)
        {
            var timer = new Stopwatch();
            timer.Start();
            var single = new int[dim*dim*dim];
            for(var i = 0; i < dim; i++)
            {
                for(var j = 0; j < dim; j++)
                {
                    for(var k = 0; k < dim; k++)
                    {
                        single[i*dim*dim+j*dim+k] = i * j * k;
                    }
                }
            }
            timer.Stop();
            Console.Write(Format,
                (double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
        }
        Console.WriteLine();
    }
}

Blur or dim background when Android PopupWindow active

findViewById(R.id.drawer_layout).setAlpha((float) 0.7);

R.id.drawer_layout is the id of the layout of which you want to dim the brightness.

history.replaceState() example?

history.pushState pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.

Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.

The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title parameter completely.

Here is a simple example of pushState that I use on my website.

(function($){
    // Use AJAX to load the page, and change the title
    function loadPage(sel, p){
        $(sel).load(p + ' #content', function(){
            document.title = $('#pageData').data('title');
        });
    }

    // When a link is clicked, use AJAX to load that page
    // but use pushState to change the URL bar
    $(document).on('click', 'a', function(e){
        e.preventDefault();
        history.pushState({page: this.href}, '', this.href);
        loadPage('#frontPage', this.href);
    });

    // This event is triggered when you visit a page in the history
    // like when yu push the "back" button
    $(window).on('popstate', function(e){
        loadPage('#frontPage', location.pathname);
        console.log(e.originalEvent.state);
    });
}(jQuery));

Java AES encryption and decryption

Try this, a simpler solution.

byte[] salt = "ThisIsASecretKey".getBytes();
Key key = new SecretKeySpec(salt, 0, 16, "AES");

Cipher cipher = Cipher.getInstance("AES");

PHP How to find the time elapsed since a date time?

Most of the answers seem focused around converting the date from a string to time. It seems you're mostly thinking about getting the date into the '5 days ago' format, etc.. right?

This is how I'd go about doing that:

$time = strtotime('2010-04-28 17:25:43');

echo 'event happened '.humanTiming($time).' ago';

function humanTiming ($time)
{

    $time = time() - $time; // to get the time since that moment
    $time = ($time<1)? 1 : $time;
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }

}

I haven't tested that, but it should work.

The result would look like

event happened 4 days ago

or

event happened 1 minute ago

cheers

How to remove an element from the flow?

There's display: none, but I think that might be a bit more than what you're looking for.

Java: How to convert List to Map

I like Kango_V's answer, but I think it's too complex. I think this is simpler - maybe too simple. If inclined, you could replace String with a Generic marker, and make it work for any Key type.

public static <E> Map<String, E> convertListToMap(Collection<E> sourceList, ListToMapConverterInterface<E> converterInterface) {
    Map<String, E> newMap = new HashMap<String, E>();
    for( E item : sourceList ) {
        newMap.put( converterInterface.getKeyForItem( item ), item );
    }
    return newMap;
}

public interface ListToMapConverterInterface<E> {
    public String getKeyForItem(E item);
}

Used like this:

        Map<String, PricingPlanAttribute> pricingPlanAttributeMap = convertListToMap( pricingPlanAttributeList,
                new ListToMapConverterInterface<PricingPlanAttribute>() {

                    @Override
                    public String getKeyForItem(PricingPlanAttribute item) {
                        return item.getFullName();
                    }
                } );

Unsupported major.minor version 52.0

You need to use JDK 1.7.0 rather than JDK 1.8.0.

To make sure it, you need to delete JDK 1.8.0 on your computer.

If you use Mac, you need to delete:

/Library/Java/JavaVirtualMachines/jdk.jdk

/Library/PreferencePanes/JavaControlPanel.prefPane

/Library/Internet Plug-Ins/JavaAppletPlugin.plugin

Then, you need to reinstall JDK 1.7.0, and you will succeed to generate the .jar file.

Passing parameters in Javascript onClick event

Another simple way ( might not be the best practice) but works like charm. Build the HTML tag of your element(hyperLink or Button) dynamically with javascript, and can pass multiple parameters as well.

// variable to hold the HTML Tags 
var ProductButtonsHTML  ="";

//Run your loop
for (var i = 0; i < ProductsJson.length; i++){
// Build the <input> Tag with the required parameters for Onclick call. Use double quotes.

ProductButtonsHTML += " <input type='button' value='" + ProductsJson[i].DisplayName + "'  
onclick = \"BuildCartById('" + ProductsJson[i].SKU+ "'," + ProductsJson[i].Id + ")\"></input> ";

}

// Add the Tags to the Div's innerHTML.
document.getElementById("divProductsMenuStrip").innerHTML = ProductButtonsHTML;

getting only name of the class Class.getName()

Here is the Groovy way of accessing object properties:

this.class.simpleName    # returns the simple name of the current class

How to remove item from array by value?

I used the most voted option and created a function that would clean one array of words using another array of unwanted words:

function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
  $.each(unwantedTermsArray, function( index, value ) {
    var index = array.indexOf(value);
    if (index > -1) {
      array.splice(index, 1);        
    }
  });
  return array;
}

To use, do the following:

var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];

cleanArrayOfSpecificTerms(splitTerms,notInclude)

Making a Sass mixin with optional arguments

I am new to css compilers, hope this helps,

        @mixin positionStyle($params...){

            $temp:nth($params,1);
            @if $temp != null{
            position:$temp;
            }

             $temp:nth($params,2);
            @if $temp != null{
            top:$temp;
            }

             $temp:nth($params,3);
            @if $temp != null{
            right:$temp;
            }

             $temp:nth($params,4);
            @if $temp != null{
            bottom:$temp;
            }

            $temp:nth($params,5);
            @if $temp != null{
            left:$temp;
            }

    .someClass{
    @include positionStyle(absolute,30px,5px,null,null);
    }

//output

.someClass{
position:absolute;
 top: 30px;
 right: 5px;
}

How to get the browser language using JavaScript

The "JavaScript" way:

var lang = navigator.language || navigator.userLanguage; //no ?s necessary

Really you should be doing language detection on the server, but if it's absolutely necessary to know/use via JavaScript, it can be gotten.

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

In my case, I don't put namespace_name in the url tag ex: {% url 'url_name or pattern name' %}. you have to specify the namespace_name like: {% url 'namespace_name:url_name or pattern name' %}.

Explanation: In project urls.py path('', include('blog.urls',namespace='blog')), and in app's urls.py you have to specify the app_name. like app_name = 'blog'. namespace_name is the app_name.

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

Multiline TextView in Android?

Below code can work for Single line and Multi-line textview

isMultiLine = If true then Textview showing with Multi-line otherwise single line

    if (isMultiLine) {
        textView.setElegantTextHeight(true);
        textView.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        textView.setSingleLine(false);
        
    } else {
        textView.setSingleLine(true);
        textView.setEllipsize(TextUtils.TruncateAt.END);
    }

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

how to define ssh private key for servers fetched by dynamic inventory in files

I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.

The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):

[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem

Here is the patch for ec2.py:

204a205,206
>     'ssh_key_path': '~/.ssh',
>     'ssh_key_suffix': '.pem',
422a425,428
>         # SSH key setup
>         self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
>         self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
> 
1490a1497
>         instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)

"401 Unauthorized" on a directory

You need to check the folder permissions on your server and check that the account that you are using to run your application has access to that folder.

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

How do I get the first element from an IEnumerable<T> in .net?

FirstOrDefault ?

Elem e = enumerable.FirstOrDefault();
//do something with e

Custom Card Shape Flutter SDK

When Card I always use RoundedRectangleBorder.

Card(
  color: Colors.grey[900],
  shape: RoundedRectangleBorder(
    side: BorderSide(color: Colors.white70, width: 1),
    borderRadius: BorderRadius.circular(10),
  ),
  margin: EdgeInsets.all(20.0),
  child: Container(
    child: Column(
        children: <Widget>[
        ListTile(
            title: Text(
            'example',
            style: TextStyle(fontSize: 18, color: Colors.white),
            ),
        ),
        ],
    ),
  ),
),

SQL to search objects, including stored procedures, in Oracle

I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.

If you need to know the functions and Procs inside the packages try something like this:

select * from all_source
 where type = 'PACKAGE'
   and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
   and owner != 'SYS';

The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.

How does a PreparedStatement avoid or prevent SQL injection?

The problem with SQL injection is, that a user input is used as part of the SQL statement. By using prepared statements you can force the user input to be handled as the content of a parameter (and not as a part of the SQL command).

But if you don't use the user input as a parameter for your prepared statement but instead build your SQL command by joining strings together, you are still vulnerable to SQL injections even when using prepared statements.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

You almost always want autocrlf=input unless you really know what you are doing.

Some additional context below:

It should be either core.autocrlf=true if you like DOS ending or core.autocrlf=input if you prefer unix-newlines. In both cases, your Git repository will have only LF, which is the Right Thing. The only argument for core.autocrlf=false was that automatic heuristic may incorrectly detect some binary as text and then your tile will be corrupted. So, core.safecrlf option was introduced to warn a user if a irreversable change happens. In fact, there are two possibilities of irreversable changes -- mixed line-ending in text file, in this normalization is desirable, so this warning can be ignored, or (very unlikely) that Git incorrectly detected your binary file as text. Then you need to use attributes to tell Git that this file is binary.

The above paragraph was originally pulled from a thread on gmane.org, but it has since gone down.

Shared folder between MacOSX and Windows on Virtual Box

At first I was stuck trying to figure out out to "insert" the Guest Additions CD image in Windows because I presumed it was a separate download that I would have to mount or somehow attach to the virtual CD drive. But just going through the Mac VirtualBox Devices menu and picking "Insert Guest Additions CD Image..." seemed to do the trick. Nothing to mount, nothing to "insert".

Elsewhere I found that the Guest Additions update was part of the update package, so I guess the new VB found the new GA CD automatically when Windows went looking. I wish I had known that to start.

Also, it appears that when I installed the Guest Additions on my Linked Base machine, it propagated to the other machines that were based on it. Sweet. Only one installation for multiple "machines".

I still haven't found that documented, but it appears to be the case (probably I'm not looking for the right explanation terms because I don't already know the explanation). How that works should probably be a different thread.

Toggle Class in React

Toggle function in react

At first you should create constructor like this

constructor(props) {
        super(props);
        this.state = {
            close: true,
        };
    }

Then create a function like this

yourFunction = () => {
        this.setState({
            close: !this.state.close,
        });
    };

then use this like

render() {
        const {close} = this.state;
        return (

            <Fragment>

                 <div onClick={() => this.yourFunction()}></div>

                 <div className={close ? "isYourDefaultClass" : "isYourOnChangeClass"}></div>

            </Fragment>
        )
    }
}

Please give better solutions

Set timeout for webClient.DownloadFile()

My answer comes from here

You can make a derived class, which will set the timeout property of the base WebRequest class:

using System;
using System.Net;

public class WebDownload : WebClient
{
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
    {
        this.Timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = this.Timeout;
        }
        return request;
    }
}

and you can use it just like the base WebClient class.

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_

SQL grammar for SELECT MIN(DATE)

You need to use GROUP BY instead of DISTINCT if you want to use aggregation functions.

SELECT title, MIN(date)
FROM table
GROUP BY title

Splitting String and put it on int array

Let's consider that you have input as "1,2,3,4".

That means the length of the input is 7. So now you write the size = 7/2 = 3.5. But as size is an int, it will be rounded off to 3. In short, you are losing 1 value.

If you rewrite the code as below it should work:

String input;
int length, count, size;
Scanner keyboard = new Scanner(System.in);
input = keyboard.next();
length = input.length();

String strarray[] = input.split(",");
int intarray[] = new int[strarray.length];

for (count = 0; count < intarray.length ; count++) {
    intarray[count] = Integer.parseInt(strarray[count]);
}

for (int s : intarray) {
    System.out.println(s);
}

Find elements inside forms and iframe using Java and Selenium WebDriver

By using https://github.com/nick318/FindElementInFrames You can find webElement across all frames:

SearchByFramesFactory searchFactory = new SearchByFramesFactory(driver);
SearchByFrames searchInFrame = searchFactory.search(() -> driver.findElement(By.tagName("body")));
Optional<WebElement> elem = searchInFrame.getElem();

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4


typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;

...

# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

How to count number of files in each directory?

This will give the overall count.

for file in */; do echo "$file -> $(ls $file | wc -l)"; done | cut -d ' ' -f 3| py --ji -l 'numpy.sum(l)'

RESTful Authentication via Spring

Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.

I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home

There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

I'm not sure why the simplest way has been ignored/omitted in the answers above:

SELECT FORMAT(GetDate(),'yyyy-MM-dd');--= 2020-01-02

SELECT FORMAT(GetDate(),'dd MMM yyyy HH:mm:ss');-- = 02 Jan 2020 08:08:08

I prefer the second one because whichever language you speak, you will understand what date it is!

Also SQL Server always 'understands' it when you send that to your save procedure, regardless of which regional formats are set in the computers - I always use full year (yyyy), month name (MMM) and 24 hour format (capital HH) for hour in my programming.

How to call a stored procedure from Java and JPA

From JPA 2.1 , JPA supports to call stored procedures using the dynamic StoredProcedureQuery, and the declarative @NamedStoredProcedureQuery.

"for" vs "each" in Ruby

It looks like there is no difference, for uses each underneath.

$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):4

Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment

for .. in .. sets the iterator outside the scope of the loop, so

for a in [1,2]
  puts a
end

leaves a defined after the loop is finished. Where as each doesn't. Which is another reason in favor of using each, because the temp variable lives a shorter period.

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

How to mock a final class with mockito

As others have stated, this won't work out of the box with Mockito. I would suggest using reflection to set the specific fields on the object that is being used by the code under test. If you find yourself doing this a lot, you can wrap this functionality in a library.

As an aside, if you are the one marking classes final, stop doing that. I ran across this question because I am working with an API where everything was marked final to prevent my legitimate need for extension (mocking), and I wish that the developer had not assumed that I would never need to extend the class.

MySQL: How to copy rows, but change a few fields?

As long as Event_ID is Integer, do this:

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, (Event_ID + 155)
  FROM Table
WHERE Event_ID = "120"

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

this could happen if you are trying to use your public key to create certificate instead of your private key. you should use private key

Generate a random double in a range

import java.util.Random;

public class MyClass {
     public static void main(String args[]) {
          Double min = 0.0;  // Set To Your Desired Min Value
          Double max = 10.0; // Set To Your Desired Max Value
          double x = (Math.random() * ((max - min) + 1)) + min;   // This Will Create A Random Number Inbetween Your Min And Max.
          double xrounded = Math.round(x * 100.0) / 100.0;   // Creates Answer To The Nearest 100 th, You Can Modify This To Change How It Rounds.
          System.out.println(xrounded);    // This Will Now Print Out The Rounded, Random Number.
     }
}

Variable used in lambda expression should be final or effectively final

Although other answers prove the requirement, they don't explain why the requirement exists.

The JLS mentions why in §15.27.2:

The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.

To lower risk of bugs, they decided to ensure captured variables are never mutated.

Changing the color of an hr element

Some browsers use the color attribute and some use the background-color attribute. To be safe:

hr{
    color: #color;
    background-color: #color;
}

Shell script variable not empty (-z option)

Of course it does. After replacing the variable, it reads [ !-z ], which is not a valid [ command. Use double quotes, or [[.

if [ ! -z "$errorstatus" ]

if [[ ! -z $errorstatus ]]

Error in finding last used cell in Excel with VBA

Sub lastRow()

    Dim i As Long
        i = Cells(Rows.Count, 1).End(xlUp).Row
            MsgBox i

End Sub

sub LastRow()

'Paste & for better understanding of the working use F8 Key to run the code .

dim WS as worksheet
dim i as long

set ws = thisworkbook("SheetName")

ws.activate

ws.range("a1").select

ws.range("a1048576").select

activecell.end(xlup).select

i= activecell.row

msgbox "My Last Row Is " & i

End sub

How to resize html canvas element?

You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:

canvasNode.width  = 200; // in pixels
canvasNode.height = 100; // in pixels

At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.

Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:

interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;

  DOMString toDataURL();
  DOMString toDataURL(in DOMString type, [Variadic] in any args);

  DOMObject getContext(in DOMString contextId);
};

As you can see it defines 2 attributes width and height, and both of them are unsigned long.

How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
numArray.sort(function(a, b) {_x000D_
  return a - b;_x000D_
});_x000D_
_x000D_
console.log(numArray);
_x000D_
_x000D_
_x000D_

In ES6, you can simplify this with arrow functions:

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort

Documentation:

Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Inf - Inf is NaN, not 0).

Also examples of sorting objects by key.

Java : How to determine the correct charset encoding of a stream

Can you pick the appropriate char set in the Constructor:

new InputStreamReader(new FileInputStream(in), "ISO8859_1");

What is a callback in java

In Java, callback methods are mainly used to address the "Observer Pattern", which is closely related to "Asynchronous Programming".

Although callbacks are also used to simulate passing methods as a parameter, like what is done in functional programming languages.

JavaScript property access: dot notation vs. brackets?

(Sourced from here.)

Square bracket notation allows the use of characters that can't be used with dot notation:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

including non-ASCII (UTF-8) characters, as in myForm["?"] (more examples).

Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

Roundup:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables

Another example of characters that can't be used with dot notation is property names that themselves contain a dot.

For example a json response could contain a property called bar.Baz.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

How do I get column names to print in this C# program?

You can access column name specifically like this too if you don't want to loop through all columns:

table.Columns[1].ColumnName

@Media min-width & max-width

The correct value for the content attribute should include initial-scale instead:

_x000D_
_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
                                                   ^^^^^^^^^^^^^^^
_x000D_
_x000D_
_x000D_

Java: How to convert a File object to a String object in java?

Why you just not read the File line by line and add it to a StringBuffer?

After you reach end of File you can get the String from the StringBuffer.

Creating a DateTime in a specific Time Zone in c#

Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.

Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:

public struct DateTimeWithZone
{
    private readonly DateTime utcDateTime;
    private readonly TimeZoneInfo timeZone;

    public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
    {
        var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); 
        this.timeZone = timeZone;
    }

    public DateTime UniversalTime { get { return utcDateTime; } }

    public TimeZoneInfo TimeZone { get { return timeZone; } }

    public DateTime LocalTime
    { 
        get 
        { 
            return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 
        }
    }        
}

You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.

Should Jquery code go in header or footer?

Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?

There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.

Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.

In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.

How to use JNDI DataSource provided by Tomcat in Spring?

If using Spring's XML schema based configuration, setup in the Spring context like this:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
...
<jee:jndi-lookup id="dbDataSource"
   jndi-name="jdbc/DatabaseName"
   expected-type="javax.sql.DataSource" />

Alternatively, setup using simple bean configuration like this:

<bean id="DatabaseName" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/DatabaseName"/>
</bean>

You can declare the JNDI resource in tomcat's server.xml using something like this:

<GlobalNamingResources>
    <Resource name="jdbc/DatabaseName"
              auth="Container"
              type="javax.sql.DataSource"
              username="dbUser"
              password="dbPassword"
              url="jdbc:postgresql://localhost/dbname"
              driverClassName="org.postgresql.Driver"
              initialSize="20"
              maxWaitMillis="15000"
              maxTotal="75"
              maxIdle="20"
              maxAge="7200000"
              testOnBorrow="true"
              validationQuery="select 1"
              />
</GlobalNamingResources>

And reference the JNDI resource from Tomcat's web context.xml like this:

  <ResourceLink name="jdbc/DatabaseName"
   global="jdbc/DatabaseName"
   type="javax.sql.DataSource"/>

Reference documentation:

Edit: This answer has been updated for Tomcat 8 and Spring 4. There have been a few property name changes for Tomcat's default datasource resource pool setup.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.

CSS strikethrough different color from text?

If it helps someone you can just use css property

text-decoration-color: red;

Git error when trying to push -- pre-receive hook declined

Issue: "PUSH Failed refs/head/ - pre-receive hook declined"

I've faced the problem of unable to push my changes to my origin branch and anything to master branch of a particular project repository as the size of that repo was over hard limit of 2GB. It was throwing the error. That's because we had pushed the test data unknowingly to bitbucket from other testing branches.

PUSH Failed refs/head/ - pre-receive hook declined

So tried checking is that the same with other project repo's and they weren't having any issues.

Fix:

My colleague noticed that when we cloned the project back locally, the size of the project was 110MB. So then we started cleaning the branches we merged earlier and active branches which are no more required. Once that cleaning is done for couple of branches we realized the size of the repo went drastically down from 2GB to 120MB. Then we tried to push the changes to my branch and it worked.

Beamer: How to show images as step-by-step images

You can simply specify a series of images like this:

\includegraphics<1>{A}
\includegraphics<2>{B}
\includegraphics<3>{C}

This will produce three slides with the images A to C in exactly the same position.

How can I edit a view using phpMyAdmin 3.2.4?

try running SHOW CREATE VIEW my_view_name in the sql portion of phpmyadmin and you will have a better idea of what is inside the view

Angular window resize event

Here is a better way to do it. Based on Birowsky's answer.

Step 1: Create an angular service with RxJS Observables.

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

@Injectable()
export class WindowService {
    height$: Observable<number>;
    //create more Observables as and when needed for various properties
    hello: string = "Hello";
    constructor() {
        let windowSize$ = new BehaviorSubject(getWindowSize());

        this.height$ = (windowSize$.pluck('height') as Observable<number>).distinctUntilChanged();

        Observable.fromEvent(window, 'resize')
            .map(getWindowSize)
            .subscribe(windowSize$);
    }

}

function getWindowSize() {
    return {
        height: window.innerHeight
        //you can sense other parameters here
    };
};

Step 2: Inject the above service and subscribe to any of the Observables created within the service wherever you would like to receive the window resize event.

import { Component } from '@angular/core';
//import service
import { WindowService } from '../Services/window.service';

@Component({
    selector: 'pm-app',
    templateUrl: './componentTemplates/app.component.html',
    providers: [WindowService]
})
export class AppComponent { 

    constructor(private windowService: WindowService) {

        //subscribe to the window resize event
        windowService.height$.subscribe((value:any) => {
            //Do whatever you want with the value.
            //You can also subscribe to other observables of the service
        });
    }

}

A sound understanding of Reactive Programming will always help in overcoming difficult problems. Hope this helps someone.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

I spoke too soon! Rebuild brought the errors back into play...

I found this works - right click in Solution Explorer and exclude it from the project. Click Show all files, right click and now include it in the project again. Now undo pending changes...

For some reason this sorted it out for me and was relatively painless!

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Quickest way to find missing number in an array of numbers

Well, use a bloom filter.

int findmissing(int arr[], int n)
{
    long bloom=0;
    int i;
    for(i=0; i<;n; i++)bloom+=1>>arr[i];
    for(i=1; i<=n, (bloom<<i & 1); i++);
    return i;
}

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

it was happened to me because I've a strange clash in the namespaces: I had AssemblyA with namespace AssemblyA.ParentNamespace witch defines ClassA and in the same assembly another namespace with name AssemblyA.ParentNamespace.ChildNamespace witch defines a different ClassA (but with the same name)

I had then in AssemblyA.ParentNamespace IInterfaceB witch had a method that in the beginning returns IEnumerable and a ClassB witch implements IInterfaceB

I had later modified the method in ClassB to return IEnumerable but I've forgot to update the IInterfaceB definition, so the method there was still returning IEnumerable the fun fact was that the solution still complile if I did a rebuild all, but the tests witch refers AssemblyA didsn't work and returns the "Metadata file could not be found"error.

updating InterfaceB to correctly return IEnumerable as its implementor ClassB did solved the problem, unfortunately the error message was vague and also the fact that the compilation worked makes me suppose that maybe there is something to fix in the compiler

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

For me the solution was to simply make sure I had installed the correct Docker package. For example, for Ubuntu the depreciated packages are:

  • docker
  • docker-engine
  • docker.io
  • containerd
  • runc

For installation check https://docs.docker.com. Instructions are provided for Ubuntu, CentOS, Debian and Fedora at the time of writing.

Decoding JSON String in Java

This is the JSON String we want to decode :

{ 
   "stats": { 
       "sdr": "aa:bb:cc:dd:ee:ff", 
       "rcv": "aa:bb:cc:dd:ee:ff", 
       "time": "UTC in millis", 
       "type": 1, 
       "subt": 1, 
       "argv": [
          {"1": 2}, 
          {"2": 3}
       ]}
}

I store this string under the variable name "sJSON" Now, this is how to decode it :)

// Creating a JSONObject from a String 
JSONObject nodeRoot  = new JSONObject(sJSON); 

// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");

// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");

How to center form in bootstrap 3

A simple way is to add

.center_div{
    margin: 0 auto;
    width:80% /* value of your choice which suits your alignment */
}

to you class .container.Add width:xx % to it and you get perfectly centered div!

eg :

<div class="container center_div">

but i feel that by default container is centered in BS!

How to use AND in IF Statement

I think you should append .value in IF statement:

If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
    Cells(i, "C").Value = "BA"
End IF

How comment a JSP expression?

My Suggestion best way use comments in JSP page <%-- Comment --%> . Because It will not displayed (will not rendered in HTML pages) in client browsers.

Using a .php file to generate a MySQL dump

You can use the exec() function to execute an external command.

Note: between shell_exec() and exec(), I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.


That external command will :

  • be a call to mysqldump, with the right parameters,
  • and redirect the output to a file.

For example :

mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql


Which means your PHP code would look like this :

exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');


Of course, up to you to use the right connection information, replacing the ... with those.

SQL - select distinct only on one column

A very typical approach to this type of problem is to use row_number():

select t.*
from (select t.*,
             row_number() over (partition by number order by id) as seqnum
      from t
     ) t
where seqnum = 1;

This is more generalizable than using a comparison to the minimum id. For instance, you can get a random row by using order by newid(). You can select 2 rows by using where seqnum <= 2.

Multi-character constant warnings

Even if you're willing to look up what behavior your implementation defines, multi-character constants will still vary with endianness.

Better to use a (POD) struct { char[4] }; ... and then use a UDL like "WAVE"_4cc to easily construct instances of that class

Drop primary key using script in SQL Server database

You can look up the constraint name in the sys.key_constraints table:

SELECT name
FROM   sys.key_constraints
WHERE  [type] = 'PK'
       AND [parent_object_id] = Object_id('dbo.Student');

If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:

DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);

SELECT @table = N'dbo.Student';

SELECT @sql = 'ALTER TABLE ' + @table 
    + ' DROP CONSTRAINT ' + name + ';'
    FROM sys.key_constraints
    WHERE [type] = 'PK'
    AND [parent_object_id] = OBJECT_ID(@table);

EXEC sp_executeSQL @sql;

This code is from Aaron Bertrand (source).

An error has occured. Please see log file - eclipse juno

If nothing works, then try uninstalling and then reinstalling Eclipse. This is how i just fixed this problem after trying everything suggested on this forum.

Printf long long int in C with GCC?

You can try settings of code::block, there is a complier..., then you select in C mode.

enter image description here

Reloading .env variables without restarting server (Laravel 5, shared hosting)

In config/database.php I changed the default DB connection from mysql to sqlite. I deleted the .env file (actually renamed it) and created the sqlite file with touch storage/database.sqlite. The migration worked with sqlite.

Then I switched back the config/database.php default DB connection to mysql and recovered the .env file. The migration worked with mysql.

It doesn't make sense I guess. Maybe was something serverside.

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

How to make a Java Generic method static?

public static <E> E[] appendToArray(E[] array, E item) { ...

Note the <E>.

Static generic methods need their own generic declaration (public static <E>) separate from the class's generic declaration (public class ArrayUtils<E>).

If the compiler complains about a type ambiguity in invoking a static generic method (again not likely in your case, but, generally speaking, just in case), here's how to explicitly invoke a static generic method using a specific type (_class_.<_generictypeparams_>_methodname_):

String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");

This would only happen if the compiler can't determine the generic type because, e.g. the generic type isn't related to the method arguments.

How do you iterate through every file/directory recursively in standard C++?

In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using Boost.FileSystem. This has been accepted for inclusion in TR2, so this gives you the best chance of keeping your implementation as close as possible to the standard.

An example, taken straight from the website:

bool find_file( const path & dir_path,         // in this directory,
                const std::string & file_name, // search for this name,
                path & path_found )            // placing path here if found
{
  if ( !exists( dir_path ) ) return false;
  directory_iterator end_itr; // default construction yields past-the-end
  for ( directory_iterator itr( dir_path );
        itr != end_itr;
        ++itr )
  {
    if ( is_directory(itr->status()) )
    {
      if ( find_file( itr->path(), file_name, path_found ) ) return true;
    }
    else if ( itr->leaf() == file_name ) // see below
    {
      path_found = itr->path();
      return true;
    }
  }
  return false;
}

How to select all checkboxes with jQuery?

$('.checkall').change(function() {
    var checkboxes = $(this).closest('table').find('td').find(':checkbox');
    if($(this).is(':checked')) {
        checkboxes.attr('checked', 'checked');
    } else {
        checkboxes.removeAttr('checked');
    }
});

Jquery post, response in new window

I did it with an ajax post and then returned using a data url:

$(document).ready(function () {
    var exportClick = function () {
        $.ajax({
           url: "/api/test.php",
           type: "POST",
           dataType: "text",
           data: {
              action: "getCSV",
              filter: "name = 'smith'",
           },
           success: function(data) {
              var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
              w.focus();
           },
           error: function () {
              alert('Problem getting data');
           },
        });
    }
});

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

How do I set up the database.yml file in Rails?

The database.yml is a file that is created with new rails applications in /config and defines the database configurations that your application will use in different environments. Read this for details.

Example database.yml:

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: mysql
  encoding: utf8
  database: your_db
  username: root
  password: your_pass
  socket: /tmp/mysql.sock
  host: your_db_ip     #defaults to 127.0.0.1
  port: 3306           

How to delete large data of table in SQL without log?

Shorter syntax

select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
  DELETE TOP (10000) LargeTable 
  WHERE readTime < dateadd(MONTH,-7,GETDATE())
END

C# removing items from listbox

The error you are getting means that

foreach (string item in listBox1.Items)

should be replaced with

for(int i = 0; i < listBox1.Items.Count; i++) {
    string item = (string)listBox1.Items[i];

In other words, don't use a foreach.

EDIT: Added cast to string in code above

EDIT2: Since you are using RemoveAt(), remember that your index for the next iteration (variable i in the example above) should not increment (since you just deleted it).

How to clear PermGen space Error in tomcat

If tomcat is running as Windows Service neither CATALINA_OPTS nor JAVA_OPTS seems to have any effect.

You need to set it in Java options in GUI.

The below link explains it well

http://www.12robots.com/index.cfm/2010/10/8/Giving-more-memory-to-the-Tomcat-Service-in-Windows

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

I was getting this error too, although my issue was that I kept switching between two corporate networks via my Virtual Machine, with different access credentials. I had to run the command prompt:

ipconfig /renew

After this my network issues were resolved and I could connect once again to SQL.

java : non-static variable cannot be referenced from a static context Error

The simplest change would be something like this:

public static void main (String[] args) throws Exception {
  testconnect obj = new testconnect();
  obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
  obj.con2.close();
}

Android canvas draw rectangle

//white background
canvas.drawRGB(255, 255, 255);
//border's properties
paint.setColor(Color.BLACK);
paint.setStrokeWidth(0);        
paint.setStyle(Paint.Style.STROKE);         
canvas.drawRect(100, 100, 200, 200, paint);

Navigation Drawer (Google+ vs. YouTube)

Edit #3:

The Navigation Drawer pattern is officially described in the Android documentation!

enter image description here Check out the following links:

  • Design docs can be found here.
  • Developer docs can be found here.

Edit #2:

Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.


Edit #1:

I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).


Original Answer:

Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".

To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.

With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,

  1. One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.

  2. The G+ app uses a ViewPager to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.

    On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).

You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).

Adding a new SQL column with a default value

If you are learning it's helpful to use a GUI like SQLyog, make the changes using the program and then see the History tab for the DDL statements that made those changes.

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

Check if checkbox is NOT checked on click - jQuery

Check out some of the answers to this question - I think it might apply to yours:

how to run click function after default behaviour of a element

I think you're running into an inconsistency in the browser implementation of the onclick function. Some choose to toggle the checkbox before the event is fired and some after.

curl_init() function not working

I got it working in ubuntu 16.04 by following steps.My php version was 7.0

sudo apt-get install php7.0-curl

sudo service apache2 restart

i got it from this link check here for more details

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

How to allow CORS in react.js?

You just have to add cors to your backend server.js file in order to do cross-origin API Calls.

const cors = require('cors');
app.use(cors())

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

In addition to the native versions, but you may want to try BitNami MAMP Stacks (disclaimer, I am one of the developers). They are completely free, all-in-one bundles of Apache, MySQL, PHP and a several other third-party libraries and utilities that are useful when developing locally. In particular, they are completely self-contained so you can have several one installed at the same time, with different versions of Apache and MySQL and they will not interfere with each other. You can get them from http://bitnami.org/stack/mampstack or directly from the Mac OS X app store https://itunes.apple.com/app/mamp-stack/id571310406

How to use BeanUtils.copyProperties?

As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance

 private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
                @Nullable String... ignoreProperties) throws BeansException {

            Assert.notNull(source, "Source must not be null");
            Assert.notNull(target, "Target must not be null");

            Class<?> actualEditable = target.getClass();
            if (editable != null) {
                if (!editable.isInstance(target)) {
                    throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                            "] not assignable to Editable class [" + editable.getName() + "]");
                }
                actualEditable = editable;
            }
            **PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
            List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

            for (PropertyDescriptor targetPd : targetPds) {
                Method writeMethod = targetPd.getWriteMethod();
                if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                    PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                    if (sourcePd != null) {
                        Method readMethod = sourcePd.getReadMethod();
                        if (readMethod != null &&
                                ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                            try {
                                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                    readMethod.setAccessible(true);
                                }
                                Object value = readMethod.invoke(source);
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                            catch (Throwable ex) {
                                throw new FatalBeanException(
                                        "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                            }
                        }
                    }
                }
            }
        }

So it's better to use plain setters given the cost reflection

oracle - what statements need to be committed?

DML (Data Manipulation Language) commands need to be commited/rolled back. Here is a list of those commands.

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency

How to rename a file using svn?

The behaviour differs depending on whether the target file name already exists or not. It's usually a safety mechanism, and there are at least 3 different cases:

Target file does not exist:

In this case svn mv should work as follows:

$ svn mv old_file_name new_file_name
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding     new_file_name
Deleting   old_file_name
Committing transaction...

Target file already exists in repository:

In this case, the target file needs to be removed explicitly, before the source file can be renamed. This can be done in the same transaction as follows:

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ svn rm new_file_name 
D         new_file_name
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
R  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Replacing      new_file_name
Deleting       old_file_name
Committing transaction...

In the output of svn stat, the R indicates that the file has been replaced, and that the file has a history.

Target file already exists locally (unversioned):

In this case, the content of the local file would be lost. If that's okay, then the file can be removed locally before renaming the existing file.

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ rm new_file_name 
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding         new_file_name
Deleting       old_file_name
Committing transaction...

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

How to pass all arguments passed to my bash script to a function of mine?

The $@ variable expands to all command-line parameters separated by spaces. Here is an example.

abc "$@"

When using $@, you should (almost) always put it in double-quotes to avoid misparsing of arguments containing spaces or wildcards (see below). This works for multiple arguments. It is also portable to all POSIX-compliant shells.

It is also worth nothing that $0 (generally the script's name or path) is not in $@.

The Bash Reference Manual Special Parameters Section says that $@ expands to the positional parameters starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is "$@" is equivalent to "$1" "$2" "$3"....

Passing some arguments:

If you want to pass all but the first arguments, you can first use shift to "consume" the first argument and then pass "$@" to pass the remaining arguments to another command. In bash (and zsh and ksh, but not in plain POSIX shells like dash), you can do this without messing with the argument list using a variant of array slicing: "${@:3}" will get you the arguments starting with "$3". "${@:3:4}" will get you up to four arguments starting at "$3" (i.e. "$3" "$4" "$5" "$6"), if that many arguments were passed.

Things you probably don't want to do:

"$*" gives all of the arguments stuck together into a single string (separated by spaces, or whatever the first character of $IFS is). This looses the distinction between spaces within arguments and the spaces between arguments, so is generally a bad idea. Although it might be ok for printing the arguments, e.g. echo "$*", provided you don't care about preserving the space within/between distinction.

Assigning the arguments to a regular variable (as in args="$@") mashes all the arguments together just like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc (note that bash array indexes start at 0, so $1 will be in args[0], etc).

Leaving off the double-quotes, with either $@ or $*, will try to split each argument up into separate words (based on whitespace or whatever's in $IFS), and also try to expand anything that looks like a filename wildcard into a list of matching filenames. This can have really weird effects, and should almost always be avoided.

How to change border color of textarea on :focus

Probably a more appropriate way of changing outline color is using the outline-color CSS rule.

textarea {
  outline-color: #719ECE;
}

or for input

input {
  outline-color: #719ECE;
}

box-shadow isn't quite the same thing and it may look different than the outline, especially if you apply custom styling to your element.

How to determine if one array contains all elements of another array

a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]

a - b
# => [5, 1, 14, 8]

b - a
# => [15]

(b - a).empty?
# => false

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

To diagnose this issue, place the line of code causing the TargetInvocationException inside the try block.

To troubleshoot this type of error, get the inner exception. It could be due to a number of different issues.

try
{
    // code causing TargetInvocationException
}
catch (Exception e)
{
    if (e.InnerException != null)
    {
    string err = e.InnerException.Message;
    }
}

How to output loop.counter in python jinja template?

Inside of a for-loop block, you can access some special variables including loop.index --but no loop.counter. From the official docs:

Variable    Description
loop.index  The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex   The number of iterations from the end of the loop (1 indexed)
loop.revindex0  The number of iterations from the end of the loop (0 indexed)
loop.first  True if first iteration.
loop.last   True if last iteration.
loop.length The number of items in the sequence.
loop.cycle  A helper function to cycle between a list of sequences. See the explanation below.
loop.depth  Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem   The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem   The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val)  True if previously called with a different value (or not called at all).

FileProvider - IllegalArgumentException: Failed to find configured root

I was getting this error Failed to find configured root that contains...

The following work around resolves my issue

res/xml/file_paths.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="media" path="." />
</paths>

AndroidManifest.xml

<provider
      android:name="android.support.v4.content.FileProvider"
      android:authorities="[PACKAGE_NAME]"
      android:exported="false"
      android:grantUriPermissions="true">
         <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths">
         </meta-data>
</provider>

ActivityClass.java

void shareImage() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,"com.slappstudio.pencilsketchphotomaker", selectedFilePath));
        startActivity(Intent.createChooser(intent,getString(R.string.string_share_with)));
    }

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Here is one more option for completeness sake, that prevents the link from doing anything even if JavaScript is disabled, and it's short :)

<a href="#void" onclick="myJsFunc()">Run JavaScript function</a>

If the id is not present on the page, then the link will do nothing.

Generally, I agree with the Aaron Wagner's answer, the JavaScript link should be injected with JavaScript code into the document.

How to find the kth largest element in an unsorted array of length n in O(n)?

This is called finding the k-th order statistic. There's a very simple randomized algorithm (called quickselect) taking O(n) average time, O(n^2) worst case time, and a pretty complicated non-randomized algorithm (called introselect) taking O(n) worst case time. There's some info on Wikipedia, but it's not very good.

Everything you need is in these powerpoint slides. Just to extract the basic algorithm of the O(n) worst-case algorithm (introselect):

Select(A,n,i):
    Divide input into ?n/5? groups of size 5.

    /* Partition on median-of-medians */
    medians = array of each group’s median.
    pivot = Select(medians, ?n/5?, ?n/10?)
    Left Array L and Right Array G = partition(A, pivot)

    /* Find ith element in L, pivot, or G */
    k = |L| + 1
    If i = k, return pivot
    If i < k, return Select(L, k-1, i)
    If i > k, return Select(G, n-k, i-k)

It's also very nicely detailed in the Introduction to Algorithms book by Cormen et al.

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 
ADD NewId INT IDENTITY (1, 1);

Update:

OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

Copy an entire worksheet to a new worksheet in Excel 2010

I really liked @brettdj's code, but then I found that when I added additional code to edit the copy, it overwrote my original sheet instead. I've tweaked his answer so that further code pointed at ws1 will affect the new sheet rather than the original.

Sub Test()
    Dim ws1 as Worksheet
    ThisWorkbook.Worksheets("Master").Copy
    Set ws1 = ThisWorkbook.Worksheets("Master (2)")
End Sub

Redirect echo output in shell script to logfile

I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will through syntax error

@AspectJ pointcut for all methods of a class with specific annotation

From Spring's AnnotationTransactionAspect:

/**
 * Matches the execution of any public method in a type with the Transactional
 * annotation, or any subtype of a type with the Transactional annotation.
 */
private pointcut executionOfAnyPublicMethodInAtTransactionalType() :
    execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *);

CSS Background image not loading

I had changed the document root for my wamp-server-installed apache web server. so using the relative url i.e. (images/img.png) didn't work. I had to use the absolute url in order for it to work i.e.

background-image:url("http://localhost/project_x/images/img.png");

How to use a class object in C++ as a function parameter

holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...

#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);


int main()
{

int i;
float  maxSize=3, size;
float  lettergrades[5], numericgrades[100], average;

size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}

int getgrades(float a[])
{ 


int i, max=3;

for (i = 0; i <max; i++)
{
    //ask use for input
    cout << "\nPlease Enter grade " << i+1 << " : ";
    cin >> a[i];
    //makes sure that user enters a vlue between 0 and 100

   if(a[i] < 0 || a[i] >100)
    {
        cout << "Wrong input. Please
 enter a value between 0 and 100 only." << endl;
        cout << "\nPlease Reenter grade " << i+1 << " : ";
        cin >> a[i];

        return i;
    }
}
}

int getaverage(float a[], float n) 
{ 
int i;
float sum = 0;
 if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}                               


int printResults(float a[], float n, float average, float letters[]) 
{
int i;
cout << "Index Number | input  |
array values address in memory " << endl;

for (i = 0; i < 3; i++)
{
cout <<"     "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;

}

invalid use of non-static data member

In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA doesn't have any specific instance of foo whose a it can be returning. I'm guessing that what you want is something like:

    class bar {
      private:
        foo * const owner;
      public:
        bar(foo & owner) : owner(&owner) { }
        int getA() {return owner->a;}
    };

But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected member a. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)

Should I use window.navigate or document.location in JavaScript?

You can move your page using

window.location.href =Url;

How to push local changes to a remote git repository on bitbucket

Use git push origin master instead.

You have a repository locally and the initial git push is "pushing" to it. It's not necessary to do so (as it is local) and it shows everything as up-to-date. git push origin master specifies a a remote repository (origin) and the branch located there (master).

For more information, check out this resource.

How to navigate back to the last cursor position in Visual Studio Code?

With VSCode 1.43 (Q1 2020), those Alt+? / Alt+?, or Ctrl+- / Ctrl+Shift+- will also... preserve selection.

See issue 89699:

Benjamin Pasero (bpasero) adds:

going back/forward restores selections as they were.

Note that in order to get a history entry there needs to be at least 10 lines between the positions to consider the entry as new entry.

Go back/Forward selection -- https://user-images.githubusercontent.com/900690/73729489-6ca7da80-4735-11ea-9345-1228f0302110.gif

Html helper for <input type="file" />

You can also use:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

Base64: java.lang.IllegalArgumentException: Illegal character

I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".

AngularJS sorting by property

As you can see in the code of angular-JS ( https://github.com/angular/angular.js/blob/master/src/ng/filter/orderBy.js ) ng-repeat does not work with objects. Here is a hack with sortFunction.

http://jsfiddle.net/sunnycpp/qaK56/33/

<div ng-app='myApp'>
    <div ng-controller="controller">
    <ul>
        <li ng-repeat="test in testData | orderBy:sortMe()">
            Order = {{test.value.order}} -> Key={{test.key}} Name=:{{test.value.name}}
        </li>
    </ul>
    </div>
</div>

myApp.controller('controller', ['$scope', function ($scope) {

    var testData = {
        a:{name:"CData", order: 2},
        b:{name:"AData", order: 3},
        c:{name:"BData", order: 1}
    };
    $scope.testData = _.map(testData, function(vValue, vKey) {
        return { key:vKey, value:vValue };
    }) ;
    $scope.sortMe = function() {
        return function(object) {
            return object.value.order;
        }
    }
}]);

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

row-level trigger vs statement-level trigger

The main difference between statement level trigger is below :

statement level trigger : based on name it works if any statement is executed. Does not depends on how many rows or any rows effected.It executes only once. Exp : if you want to update salary of every employee from department HR and at the end you want to know how many rows get effected means how many got salary increased then use statement level trigger. please note that trigger will execute even if zero rows get updated because it is statement level trigger is called if any statement has been executed. No matters if it is affecting any rows or not.

Row level trigger : executes each time when an row is affected. if zero rows affected.no row level trigger will execute.suppose if u want to delete one employye from emp table whose department is HR and u want as soon as employee deleted from emp table the count in dept table from HR section should be reduce by 1.then you should opt for row level trigger.

If condition inside of map() React

You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:

renderItem = (id) => {
    // just standard if statement
    if (this.props.schema.collectionName.length < 0) {
        return (
            <Expandable>
                <ObjectDisplay
                    key={id}
                    parentDocumentId={id}
                    schema={schema[this.props.schema.collectionName]}
                    value={this.props.collection.documents[id]}
                />
            </Expandable>
        );
    }
    return (
        <h1>hejsan</h1>
    );
}

Then just call it when mapping:

render() {
    return (
        <div>
            <div className="box">
                { 
                    this.props.collection.ids
                        .filter(
                            id =>
                            // note: this is only passed when in top level of document
                            this.props.collection.documents[id][
                                this.props.schema.foreignKey
                            ] === this.props.parentDocumentId
                        )
                        .map(this.renderItem)
                }
            </div>
        </div>
    )
}

Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

Python Request Post with param data

params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

You could split out the URL parameters as well:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

then post your data with:

import requests

url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, json=data)

The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, data=json.dumps(data), headers=headers)

Toolbar navigation icon never set

Use setNavigationIcon to change it. don't forget create ActionBarDrawerToggle first!

sample code work for me:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    drawer = (DrawerLayout)findViewById(R.id.drawer_layout);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);

    toggle.syncState();

    toolbar.setNavigationIcon(R.drawable.ic_menu);

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

How do I handle Database Connections with Dapper in .NET?

Everyone appears to be opening their connections entirely too early? I had this same question, and after digging through the Source here - https://github.com/StackExchange/dapper-dot-net/blob/master/Dapper/SqlMapper.cs

You will find that every interaction with the database checks the connection to see if it is closed, and opens it as necessary. Due to this, we simply utilize using statements like above without the conn.open(). This way the connection is opened as close to the interaction as possible. If you notice, it also immediately closes the connection. This will also be quicker than it closing automatically during disposal.

One of the many examples of this from the repo above:

    private static int ExecuteCommand(IDbConnection cnn, ref CommandDefinition command, Action<IDbCommand, object> paramReader)
    {
        IDbCommand cmd = null;
        bool wasClosed = cnn.State == ConnectionState.Closed;
        try
        {
            cmd = command.SetupCommand(cnn, paramReader);
            if (wasClosed) cnn.Open();
            int result = cmd.ExecuteNonQuery();
            command.OnCompleted();
            return result;
        }
        finally
        {
            if (wasClosed) cnn.Close();
            cmd?.Dispose();
        }
    }

Below is a small example of how we use a Wrapper for Dapper called the DapperWrapper. This allows us to wrap all of the Dapper and Simple Crud methods to manage connections, provide security, logging, etc.

  public class DapperWrapper : IDapperWrapper
  {
    public IEnumerable<T> Query<T>(string query, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
    {
      using (var conn = Db.NewConnection())
      {
          var results = conn.Query<T>(query, param, transaction, buffered, commandTimeout, commandType);
          // Do whatever you want with the results here
          // Such as Security, Logging, Etc.
          return results;
      }
    }
  }

Batch command date and time in file name

I realise this is a moot question to the OP, but I just brewed this, and I'm a tad proud of myself for thinking outside the box.

Download gawk for Windows at http://gnuwin32.sourceforge.net/packages/gawk.htm .... Then it's a one liner, without all that clunky DOS batch syntax, where it takes six FOR loops to split the strings (WTF? That's really really BAD MAD AND SAD! ... IMHO of course)

If you already know C, C++, Perl, or Ruby then picking-up AWK (which inherits from the former two, and contributes significantly to the latter two) is a piece of the proverbial CAKE!!!

The DOS Batch command:

echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"

Prints:

Tue 04/09/2012 10:40:38.25
20120904-104038

Now that's not quite the full story... I'm just going to be lazy and hard-code the rest of my log-file-name in the printf statement, because it's simple... But if anybody knows how to set a %NOW% variable to AWK's output (yeilding the guts of a "generic" now function) then I'm all ears.


EDIT:

A quick search on Stack Overflow filled in that last piece of the puzzle, Batch equivalent of Bash backticks.

So, these three lines of DOS batch:

echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
set /p now=<%temp%\now.txt
echo %now%

Produce:

20120904-114434

So now I can include a datetime in the name of the log-file produced by my SQL Server installation (2005+) script thus:

sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log

And I'm a happy camper again (except life was still SOOOOO much easier on Unix).

Split Java String by New Line

For preserving empty lines from getting squashed use:

String lines[] = String.split("\\r?\\n", -1);

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

PHP: Get key from array?

If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.

Sort an Array by keys based on another Array?

There you go:

function sortArrayByArray(array $array, array $orderArray) {
    $ordered = array();
    foreach ($orderArray as $key) {
        if (array_key_exists($key, $array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered + $array;
}

eclipse won't start - no java virtual machine was found

Make sure both the Java version and Eclipse are belongs to same architecture.So install 64 bit java for 64 bit eclipse.

Why Anaconda does not recognize conda command?

I suspect you forget to export PATH, anaconda/bin must be added in your $PATH. (Linux, OSX common problem). On Windows make sure you run install and commands as administrator.

Android Min SDK Version vs. Target SDK Version

When you set targetSdkVersion="xx", you are certifying that your app works properly (e.g., has been thoroughly and successfully tested) at API level xx.

A version of Android running at an API level above xx will apply compatibility code automatically to support any features you might be relying upon that were available at or prior to API level xx, but which are now obsolete at that Android version's higher level.

Conversely, if you are using any features that became obsolete at or prior to level xx, compatibility code will not be automatically applied by OS versions at higher API levels (that no longer include those features) to support those uses. In that situation, your own code must have special case clauses that test the API level and, if the OS level detected is a higher one that no longer has the given API feature, your code must use alternate features that are available at the running OS's API level.

If it fails to do this, then some interface features may simply not appear that would normally trigger events within your code, and you may be missing a critical interface feature that the user needs to trigger those events and to access their functionality (as in the example below).

As stated in other answers, you might set targetSdkVersion higher than minSdkVersion if you wanted to use some API features initially defined at higher API levels than your minSdkVersion, and had taken steps to ensure that your code could detect and handle the absence of those features at lower levels than targetSdkVersion.

In order to warn developers to specifically test for the minimum API level required to use a feature, the compiler will issue an error (not just a warning) if code contains a call to any method that was defined at a later API level than minSdkVersion, even if targetSdkVersion is greater than or equal to the API level at which that method was first made available. To remove this error, the compiler directive

@TargetApi(nn)

tells the compiler that the code within the scope of that directive (which will precede either a method or a class) has been written to test for an API level of at least nn prior to calling any method that depends upon having at least that API level. For example, the following code defines a method that can be called from code within an app that has a minSdkVersion of less than 11 and a targetSdkVersion of 11 or higher:

@TargetApi(11)
    public void refreshActionBarIfApi11OrHigher() {
      //If the API is 11 or higher, set up the actionBar and display it
      if(Build.VERSION.SDK_INT >= 11) {
        //ActionBar only exists at API level 11 or higher
        ActionBar actionBar = getActionBar();

        //This should cause onPrepareOptionsMenu() to be called.
        // In versions of the API prior to 11, this only occurred when the user pressed 
        // the dedicated menu button, but at level 11 and above, the action bar is 
        // typically displayed continuously and so you will need to call this
        // each time the options on your menu change.
        invalidateOptionsMenu();

        //Show the bar
        actionBar.show();
    }
}

You might also want to declare a higher targetSdkVersion if you had tested at that higher level and everything worked, even if you were not using any features from an API level higher than your minSdkVersion. This would be just to avoid the overhead of accessing compatibility code intended to adapt from the target level down to the min level, since you would have confirmed (through testing) that no such adaptation was required.

An example of a UI feature that depends upon the declared targetSdkVersion would be the three-vertical-dot menu button that appears on the status bar of apps having a targetSdkVersion less than 11, when those apps are running under API 11 and higher. If your app has a targetSdkVersion of 10 or below, it is assumed that your app's interface depends upon the existence of a dedicated menu button, and so the three-dot button appears to take the place of the earlier dedicated hardware and/or onscreen versions of that button (e.g., as seen in Gingerbread) when the OS has a higher API level for which a dedicated menu button on the device is no longer assumed. However, if you set your app's targetSdkVersion to 11 or higher, it is assumed that you have taken advantage of features introduced at that level that replace the dedicated menu button (e.g., the Action Bar), or that you have otherwise circumvented the need to have a system menu button; consequently, the three-vertical-dot menu "compatibility button" disappears. In that case, if the user can't find a menu button, she can't press it, and that, in turn, means that your activity's onCreateOptionsMenu(menu) override might never get invoked, which, again in turn, means that a significant part of your app's functionality could be deprived of its user interface. Unless, of course, you have implemented the Action Bar or some other alternative means for the user to access these features.

minSdkVersion, by contrast, states a requirement that a device's OS version have at least that API level in order to run your app. This affects which devices are able to see and download your app when it is on the Google Play app store (and possibly other app stores, as well). It's a way of stating that your app relies upon OS (API or other) features that were established at that level, and does not have an acceptable way to deal with the absence of those features.

An example of using minSdkVersion to ensure the presence of a feature that is not API-related would be to set minSdkVersion to 8 in order to ensure that your app will run only on a JIT-enabled version of the Dalvik interpreter (since JIT was introduced to the Android interpreter at API level 8). Since performance for a JIT-enabled interpreter can be as much as five times that of one lacking that feature, if your app makes heavy use of the processor then you might want to require API level 8 or above in order to ensure adequate performance.

Null or empty check for a string variable

Yes, it works. Check the below example. Assuming @value is not int

WITH CTE 
AS
(
    SELECT NULL AS test
    UNION
    SELECT '' AS test
    UNION
    SELECT '123' AS test
)

SELECT 
    CASE WHEN isnull(test,'')='' THEN 'empty' ELSE test END AS IS_EMPTY 
FROM CTE

Result :

IS_EMPTY
--------
empty
empty
123

How to print to the console in Android Studio?

Be careful when using Logcat, it will truncate your message after ~4,076 bytes which can cause a lot of headache if you're printing out large amounts of data.

To get around this you have to write a function that will break it up into multiple parts like so.

How do I check my gcc C++ compiler version for my Eclipse?

The answer is:

gcc --version

Rather than searching on forums, for any possible option you can always type:

gcc --help

haha! :)

How can I find an element by CSS class with XPath?

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')]

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

Open Facebook page from Android app?

Declare constants

  private String FACEBOOK_URL="https://www.facebook.com/approids";
    private String FACEBOOK_PAGE_ID="approids";

Declare Method

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) {
                    Log.d("main","fb first url");
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else {
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL;
        }
    }

Call Function

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
                String facebookUrl = getFacebookPageURL(MainActivity.this);
                facebookIntent.setData(Uri.parse(facebookUrl));
                startActivity(facebookIntent);

Angular 2 Dropdown Options Default Value

According to https://angular.io/api/forms/SelectControlValueAccessor you just need the following:

theView.html:

<select [compareWith]="compareFn"  [(ngModel)]="selectedCountries">
    <option *ngFor="let country of countries" [ngValue]="country">
        {{country.name}}
    </option>
</select>

theComponent.ts

import { SelectControlValueAccessor } from '@angular/forms';
    compareFn(c1: Country, c2: Country): boolean {
    return c1 && c2 ? c1.id === c2.id : c1 === c2;
}

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

Pretty straight forward approach using filterBy in angularJs

For working plnkr follow this link

http://plnkr.co/edit/US6xE4h0gD5CEYV0aMDf?p=preview

This has specially used a single property to search against multiple column but not all.

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="[email protected]" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
    <script data-require="[email protected]" data-semver="0.5.2" src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.2/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="myCtrl as vm">
  <input type="text" placeholder="enter your search text" ng-model="vm.searchText" />
   <table>
     <tr ng-repeat="row in vm.tableData | filterBy: ['col1','col2']: vm.searchText">
       <td>{{row.col1}}</td>
       <td>{{row.col2}}</td>
       <td>{{row.col3}}</td>
     </tr>
   </table>
   <p>This will show filter from <b>two columns</b> only(col1 and col2) . Not from all. Whatever columns you add into filter array they
   will be searched. all columns will be used by default if you use <b>filter: vm.searchText</b></p>
  </body>
</html>

controller

// Code goes here
(function(){

  var myApp = angular.module('myApp',['angular.filter']);

  myApp.controller('myCtrl', function($scope){
    var vm= this;
    vm.x = 20;

    vm.tableData = [
      {
        col1: 'Ashok',
        col2: 'Tewatia',
        col3: '12'
      },{
        col1: 'Babita',
        col2: 'Malik',
        col3: '34'
      },{
        col1: 'Dinesh',
        col2: 'Tewatia',
        col3: '56'
      },{
        col1: 'Sabita',
        col2: 'Malik',
        col3: '78'
      }
      ];
  })

})();

Sending event when AngularJS finished loading

If you want to generate JS with server-side data (JSP, PHP) you could add your logic to a service, that will be loaded automatically when your controller is loaded.

Additionally, if you want to react when all directives are done compiling/linking, you could add the appropriate proposed solutions above in the initialization logic.

module.factory('YourControllerInitService', function() {

    // add your initialization logic here

    // return empty service, because it will not be used
    return {};
});


module.controller('YourController', function (YourControllerInitService) {
});

Making a mocked method return an argument that was passed to it

This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:

@Test
fun demo() {
  // mock a sample function
  val aMock: (String) -> (String) = mockk()

  // make it return the same as the argument on every invocation
  every {
    aMock.invoke(any())
  } answers {
    firstArg()
  }

  // test it
  assertEquals("senko", aMock.invoke("senko"))
  assertEquals("senko1", aMock.invoke("senko1"))
  assertNotEquals("not a senko", aMock.invoke("senko"))
}

Is it possible to insert multiple rows at a time in an SQLite database?

Yes, sql can do this, but with a different syntax. The sqlite documentation is pretty good, by the way. It will also tell you that the only way to insert several row is use a select statement as the source of the data to be inserted.

Postgres Error: More than one row returned by a subquery used as an expression

This error means that the SELECT store_key FROM store query has returned two or more rows in the SERVER1 database. If you would like to update all customers, use a join instead of a scalar = operator. You need a condition to "connect" customers to store items in order to do that.

If you wish to update all customer_ids to the same store_key, you need to supply a WHERE clause to the remotely executed SELECT so that the query returns a single row.

Stopping a CSS3 Animation on last frame

If you want to add this behaviour to a shorthand animation property definition, the order of sub-properties is as follows

animation-name - default none

animation-duration - default 0s

animation-timing-function - default ease

animation-delay - default 0s

animation-iteration-count - default 1

animation-direction - default normal

animation-fill-mode - you need to set this to forwards

animation-play-state - default running

Therefore in the most common case, the result will be something like this

animation: colorchange 1s ease 0s 1 normal forwards;

See the MDN documentation here

Convert file path to a file URI?

At least in .NET 4.5+ you can also do:

var uri = new System.Uri("C:\\foo", UriKind.Absolute);

Rearrange columns using cut

Expanding on the answer from @Met, also using Perl:
If the input and output are TAB-delimited:

perl -F'\t' -lane 'print join "\t", @F[1, 0]' in_file

If the input and output are whitespace-delimited:

perl -lane 'print join " ", @F[1, 0]' in_file

Here,
-e tells Perl to look for the code inline, rather than in a separate script file,
-n reads the input 1 line at a time,
-l removes the input record separator (\n on *NIX) after reading the line (similar to chomp), and add output record separator (\n on *NIX) to each print,
-a splits the input line on whitespace into array @F,
-F'\t' in combination with -a splits the input line on TABs, instead of whitespace into array @F.

@F[1, 0] is the array made up of the 2nd and 1st elements of array @F, in this order. Remember that arrays in Perl are zero-indexed, while fields in cut are 1-indexed. So fields in @F[0, 1] are the same fields as the ones in cut -f1,2.

Note that such notation enables more flexible manipulation of input than in some other answers posted above (which are fine for a simple task). For example:

# reverses the order of fields:
perl -F'\t' -lane 'print join "\t", reverse @F' in_file

# prints last and first fields only:
perl -F'\t' -lane 'print join "\t", @F[-1, 0]' in_file

Iterate over values of object

EcmaScript 2017 introduced Object.entries that allows you to iterate over values and keys. Documentation

var map = { key1 : 'value1', key2 : 'value2' }

for (let [key, value] of Object.entries(map)) {
    console.log(`${key}: ${value}`);
}

The result will be:

key1: value1
key2: value2

How do I pass a method as a parameter in Python

Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.

Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self parameter).

To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:

def method1(self):
    return 'hello world'

def method2(self, methodToRun):
    result = methodToRun()
    return result

obj.method2(obj.method1)

Note: I believe a __call__() method does exist, i.e. you could technically do methodToRun.__call__(), but you probably should never do so explicitly. __call__() is meant to be implemented, not to be invoked from your own code.

If you wanted method1 to be called with arguments, then things get a little bit more complicated. method2 has to be written with a bit of information about how to pass arguments to method1, and it needs to get values for those arguments from somewhere. For instance, if method1 is supposed to take one argument:

def method1(self, spam):
    return 'hello ' + str(spam)

then you could write method2 to call it with one argument that gets passed in:

def method2(self, methodToRun, spam_value):
    return methodToRun(spam_value)

or with an argument that it computes itself:

def method2(self, methodToRun):
    spam_value = compute_some_value()
    return methodToRun(spam_value)

You can expand this to other combinations of values passed in and values computed, like

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham_value)

or even with keyword arguments

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham=ham_value)

If you don't know, when writing method2, what arguments methodToRun is going to take, you can also use argument unpacking to call it in a generic way:

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, positional_arguments, keyword_arguments):
    return methodToRun(*positional_arguments, **keyword_arguments)

obj.method2(obj.method1, ['spam'], {'ham': 'ham'})

In this case positional_arguments needs to be a list or tuple or similar, and keyword_arguments is a dict or similar. In method2 you can modify positional_arguments and keyword_arguments (e.g. to add or remove certain arguments or change the values) before you call method1.

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

For iPhone cocoa-touch projects:

I had this problem and thanks to Eric Farraro's comment, I was able to get it resolved. I was importing a class WSHelper.h in many of my other classes. But I also was importing some of those same classes in my WSHelper.h (circular like Eric said). So, to fix this I moved the imports from my WSHelper.h file to my WSHelper.m file as they weren't really needed in the .h file anyway.

How to export a table dataframe in PySpark to csv?

How about this (in you don't want an one liner) ?

for row in df.collect():
    d = row.asDict()
    s = "%d\t%s\t%s\n" % (d["int_column"], d["string_column"], d["string_column"])
    f.write(s)

f is a opened file descriptor. Also the separator is a TAB char, but it's easy to change to whatever you want.

Given URL is not permitted by the application configuration

Missing from the other answers is how to allow localhost(or 0.0.0.0 or whatever) as an oauth callback url. Here is the explanation. How can I add localhost:3000 to Facebook App for development

Which is the best library for XML parsing in java

Java supports two methods for XML parsing out of the box.

SAXParser

You can use this parser if you want to parse large XML files and/or don't want to use a lot of memory.

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html

Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

DOMParser

You can use this parser if you need to do XPath queries or need to have the complete DOM available.

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilderFactory.html

Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

Use CSS to make a span not clickable

CSS relates to visual styling and not behaviour, so the answer is no really.

You could however either use javascript to modify the behaviour or change the styling of the span in question so that it doesn't have the pointy finger, underline, etc. Styling it like that will still leave it clickable.

Even better, change your markup so that it reflects what you want it to do.

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

implementation 'com.android.support:appcompat-v7:26.1.0'

after this line You have to add new Line in your gradle

implementation 'com.android.support:design:26.1.0'

How to convert a negative number to positive?

If you are working with numpy you can use

import numpy as np
np.abs(-1.23)
>> 1.23

It will provide absolute values.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

Print a variable in hexadecimal in Python

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

How to convert BigInteger to String in java

You can also use Java's implicit conversion:

BigInteger m = new BigInteger(bytemsg); 
String mStr = "" + m;  // mStr now contains string representation of m.

iFrame onload JavaScript event

_x000D_
_x000D_
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
    this.style.backgroundColor = "red";_x000D_
    alert(this.nodeName);_x000D_
_x000D_
    console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
_x000D_
_x000D_

How to add a border just on the top side of a UIView

Swift 4.2 and AutoLayout

I went through the offered solutions. Many are based in frames This is a simple extension that works with AutoLayout - use View instead of Layer to make sure we can use AutoLayout - Single subview with 4 constraints

Use as follows:

self.addBorder(.bottom, color: .lightGray, thickness: 0.5)


extension UIView {
    func addBorder(_ edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
        let subview = UIView()
        subview.translatesAutoresizingMaskIntoConstraints = false
        subview.backgroundColor = color
        self.addSubview(subview)
        switch edge {
        case .top, .bottom:
            subview.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
            subview.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
            subview.heightAnchor.constraint(equalToConstant: thickness).isActive = true
            if edge == .top {
                subview.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            } else {
                subview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            }
        case .left, .right:
            subview.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            subview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            subview.widthAnchor.constraint(equalToConstant: thickness).isActive = true
            if edge == .left {
                subview.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
            } else {
                subview.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
            }
        default:
            break
        }
    }
}

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

If you are doing something nobody here will listen you about because "you're doing it the wrong way", but you have to do it "the wrong way" for reasons too asinine to explain and also beyond your ability to control, you can try this:

Get libffi and install it into your user install area the usual way.

git clone https://github.com/libffi/libffi.git
cd libffi
./configure --prefix=path/to/your/install/root
make
make install

Then go back to your Python 3 source and find this part of the code in setup.py at the top level of the python source directory

        ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
        if not ffi_inc or ffi_inc[0] == '':
            ffi_inc = find_file('ffi.h', [], inc_dirs)
        if ffi_inc is not None:
            ffi_h = ffi_inc[0] + '/ffi.h'
            if not os.path.exists(ffi_h):
                ffi_inc = None
                print('Header file {} does not exist'.format(ffi_h))
        ffi_lib = None
        if ffi_inc is not None:
            for lib_name in ('ffi', 'ffi_pic'):
                if (self.compiler.find_library_file(lib_dirs, lib_name)):
                    ffi_lib = lib_name
                    break

        ffi_lib="ffi"  # --- AND INSERT THIS LINE HERE THAT DOES NOT APPEAR ---
        if ffi_inc and ffi_lib:
            ext.include_dirs.extend(ffi_inc)
            ext.libraries.append(ffi_lib)
            self.use_system_libffi = True

and add the line I have marked above with the comment. Why it is necessary, and why there is no way to get configure to respect '--without-system-ffi` on Linux platforms, perhaps I will find out why that is "unsupported" in the next couple of hours, but everything has worked ever since. Otherwise, best of luck... YMMV.

WHAT IT DOES: just overrides the logic there and causes the compiler linking command to add "-lffi" which is all that it really needs. If you have the library user-installed, it is probably detecting the headers fine as long as your PKG_CONFIG_PATH includes path/to/your/install/root/lib/pkgconfig.

How to make a hyperlink in telegram without using bots?

In telegram desktop, use this hotkey: ctrl+K

In android:

  1. type your text
  2. select it
  3. and click on Create Link from its options

You can see these steps in this image: link creation in telegram android

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

I had the same problem, in my case handler was in two places:

<system.web>
...
<httpHandlers>
 <add verb="*" path="*.ashx" type="ApplicArt.Extranet2.Controller.FrontController, ApplicArt.Extranet2.Web.UI" />
  </httpHandlers>
</system.web>

<system.webServer>
<handlers>
   ...
  <add name="FrontController" verb="*" path="*.ashx" type="ApplicArt.Extranet2.Controller.FrontController, ApplicArt.Extranet2.Web.UI"/>
</handlers>
</system.webServer>

And when I removed my handler from [system.webServer] my problem disappeared.

How do I measure request and response times at once using cURL?

A shortcut you can add to your .bashrc etc, based on other answers here:

function perf {
  curl -o /dev/null -s -w "%{time_connect} + %{time_starttransfer} = %{time_total}\n" "$1"
}

Usage:

> perf stackoverflow.com
0.521 + 0.686 = 1.290

Group query results by month and year in postgresql

There is another way to achieve the result using the date_part() function in postgres.

 SELECT date_part('month', txn_date) AS txn_month, date_part('year', txn_date) AS txn_year, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY date_part('month', txn_date)

Thanks

Determine the process pid listening on a certain port

netstat -p -l | grep $PORT and lsof -i :$PORT solutions are good but I prefer fuser $PORT/tcp extension syntax to POSIX (which work for coreutils) as with pipe:

pid=`fuser $PORT/tcp`

it prints pure pid so you can drop sed magic out.

One thing that makes fuser my lover tools is ability to send signal to that process directly (this syntax is also extension to POSIX):

$ fuser -k $port/tcp       # with SIGKILL
$ fuser -k -15 $port/tcp   # with SIGTERM
$ fuser -k -TERM $port/tcp # with SIGTERM

Also -k is supported by FreeBSD: http://www.freebsd.org/cgi/man.cgi?query=fuser

How to get the return value from a thread in python?

Parris / kindall's answer join/return answer ported to Python 3:

from threading import Thread

def foo(bar):
    print('hello {0}'.format(bar))
    return "foo"

class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):
        Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon)

        self._return = None

    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)

    def join(self):
        Thread.join(self)
        return self._return


twrv = ThreadWithReturnValue(target=foo, args=('world!',))

twrv.start()
print(twrv.join())   # prints foo

Note, the Thread class is implemented differently in Python 3.

How do I return an int from EditText? (Android)

Set the digits attribute to true, which will cause it to only allow number inputs.

Then do Integer.valueOf(editText.getText()) to get an int value out.

React hooks useState Array

To expand on Ryan's answer:

Whenever setStateValues is called, React re-renders your component, which means that the function body of the StateSelector component function gets re-executed.

React docs:

setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

Essentially, you're setting state with:

setStateValues(allowedState);

causing a re-render, which then causes the function to execute, and so on. Hence, the loop issue.

To illustrate the point, if you set a timeout as like:

  setTimeout(
    () => setStateValues(allowedState),
    1000
  )

Which ends the 'too many re-renders' issue.

In your case, you're dealing with a side-effect, which is handled with UseEffectin your component functions. You can read more about it here.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Turning multi-line string into single comma-separated

You can also print like this:

Just awk: using printf

bash-3.2$ cat sample.log
something1:    +12.0   (some unnecessary trailing data (this must go))
something2:    +15.5   (some more unnecessary trailing data)
something4:    +9.0   (some other unnecessary data)
something1:    +13.5  (blah blah blah)

bash-3.2$ awk ' { if($2 != "") { if(NR==1) { printf $2 } else { printf "," $2 } } }' sample.log
+12.0,+15.5,+9.0,+13.5

Font is not available to the JVM with Jasper Reports

Copy your Fonts on the following directory JDK_HOME\jre\lib\fonts

Dynamic height for DIV

as prior ans remove the height attrib. if u want your expansion along with its min height then use min-height: 102px instead of height: 102px.

note ie 6 and min-height http://www.dustindiaz.com/min-height-fast-hack/

How do I convert an enum to a list in C#?

private List<SimpleLogType> GetLogType()
{
  List<SimpleLogType> logList = new List<SimpleLogType>();
  SimpleLogType internalLogType;
  foreach (var logtype in Enum.GetValues(typeof(Log)))
  {
    internalLogType = new SimpleLogType();
    internalLogType.Id = (int) (Log) Enum.Parse(typeof (Log), logtype.ToString(), true);
    internalLogType.Name = (Log)Enum.Parse(typeof(Log), logtype.ToString(), true);
    logList.Add(internalLogType);
  }
  return logList;
}

in top Code , Log is a Enum and SimpleLogType is a structure for logs .

public enum Log
{
  None = 0,
  Info = 1,
  Warning = 8,
  Error = 3
}

"UnboundLocalError: local variable referenced before assignment" after an if statement

Your if statement is always false and T gets initialized only if a condition is met, so the code doesn't reach the point where T gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.

Try:

def temp_sky(lreq, breq):
    T = <some_default_value> # None is often a good pick
    for line in tfile:
        data = line.split()
        if abs(float(data[0])-lreq) <= 0.1 and abs(float(data[1])-breq) <= 0.1:            
            T = data[2]
    return T

jQuery: Clearing Form Inputs

You may try

$("#addRunner input").each(function(){ ... });

Inputs are no selectors, so you do not need the : Haven't tested it with your code. Just a fast guess!

Android Studio doesn't recognize my device

Did you try to configure the "Media Mode" in "Camera (PTP)" instead of "Media device (MTP)"? This is sometimes solving the issue. Its in the USB Computer Connection options of your Android device, you should see an "authorize" dialog then.

Update 04/2017: looks like it has been fixed in Android 7.1.2

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

When you face the following issue:

PHP throwing error "Warning: mysql_connect() http://function.mysql-connect: 2002 No such file or directory (trying to connect via unix:///tmp/mysql.sock)"

Set "mysql.default_socket" value in your /etc/php.ini to

 "mysql.default_socket = /var/mysql/mysql.sock". 

Then restart web service in server admin

LINQ's Distinct() on a particular property

Please give a try with below code.

var Item = GetAll().GroupBy(x => x .Id).ToList();