Programs & Examples On #Construct

Construct is a powerful declarative parser for binary data.

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

this in equals method

this refers to the current instance of the class (object) your equals-method belongs to. When you test this against an object, the testing method (which is equals(Object obj) in your case) will check wether or not the object is equal to the current instance (referred to as this).

An example:

Object obj = this; this.equals(obj); //true   Object obj = this; new Object().equals(obj); //false 

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

is it possible to add colors to python output?

IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.

You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle documentation just tells you the basics of using IDLE itself, and its idlelib library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.


Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)

Learning to read the termcap entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.

Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.

But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

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

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

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

TS1086: An accessor cannot be declared in ambient context

I've updated typescript and tslint versions and removed packages I wasn't using. This solved the problem for me.

As others pointed here, it seems to be an issue with different TypeScript versions where the generated typings from some library aren't compatible with your TypeScript version.

Server Discovery And Monitoring engine is deprecated

Update

Mongoose 5.7.1 was release and seems to fix the issue, so setting up the useUnifiedTopology option work as expected.

mongoose.connect(mongoConnectionString, {useNewUrlParser: true, useUnifiedTopology: true});

Original answer

I was facing the same issue and decided to deep dive on Mongoose code: https://github.com/Automattic/mongoose/search?q=useUnifiedTopology&unscoped_q=useUnifiedTopology

Seems to be an option added on version 5.7 of Mongoose and not well documented yet. I could not even find it mentioned in the library history https://github.com/Automattic/mongoose/blob/master/History.md

According to a comment in the code:

  • @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to true to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine.

There is also an issue on the project GitHub about this error: https://github.com/Automattic/mongoose/issues/8156

In my case I don't use Mongoose in a replica set or sharded cluster and though the option should be false. But if false it complains the setting should be true. Once is true it still don't work, probably because my database does not run on a replica set or sharded cluster.

I've downgraded to 5.6.13 and my project is back working fine. So the only option I see for now is to downgrade it and wait for the fix to update for a newer version.

Angular @ViewChild() error: Expected 2 arguments, but got 1

you should use second argument with ViewChild like this:

@ViewChild("eleDiv", { static: false }) someElement: ElementRef;

Invalid hook call. Hooks can only be called inside of the body of a function component

Yesterday, I shortened the code (just added <Provider store={store}>) and still got this invalid hook call problem. This made me suddenly realized what mistake I did: I didn't install the react-redux software in that folder.

I had installed this software in the other project folder, so I didn't realize this one also needed it. After installing it, the error is gone.

How to set value to form control in Reactive Forms in Angular

To assign value to a single Form control/individually, I propose to use setValue in the following way:

this.editqueForm.get('user').setValue(this.question.user);

this.editqueForm.get('questioning').setValue(this.question.questioning);

Flutter Countdown Timer

If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!

countDownTimer() async {
 int timerCount;
 for (int x = 5; x > 0; x--) {
   await Future.delayed(Duration(seconds: 1)).then((_) {
     setState(() {
       timerCount -= 1;
    });
  });
 }
}

Can't perform a React state update on an unmounted component

There is a hook that's fairly common called useIsMounted that solves this problem (for functional components)...

import { useRef, useEffect } from 'react';

export function useIsMounted() {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);

  return isMounted;
}

then in your functional component

function Book() {
  const isMounted = useIsMounted();
  ...

  useEffect(() => {
    asyncOperation().then(data => {
      if (isMounted.current) { setState(data); }
    })
  });
  ...
}

TypeScript and React - children type?

From the TypeScript site: https://github.com/Microsoft/TypeScript/issues/6471

The recommended practice is to write the props type as {children?: any}

That worked for me. The child node can be many different things, so explicit typing can miss cases.

There's a longer discussion on the followup issue here: https://github.com/Microsoft/TypeScript/issues/13618, but the any approach still works.

How can I force component to re-render with hooks in React?

My variation of forceUpdate is not via a counter but rather via an object:

// Emulates `forceUpdate()`
const [unusedState, setUnusedState] = useState()
const forceUpdate = useCallback(() => setUnusedState({}), [])

Because {} !== {} every time.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

Just want to point out that this answer provides a better explanation.
Basically you can either have @Getter and @NoArgConstructor together
or let Lombok regenerates @ConstructorProperties using lombok.config file,
or compile your java project with -parameters flags,
or let Jackson use Lombok's @Builder

expected assignment or function call: no-unused-expressions ReactJS

For me the error occured when using map. And I didn't use the return Statement inside the map.

{cart.map((cart_products,index) => {
    <span>{cart_products.id}</span>; 
})};

Above code produced error.

{cart.map((cart_products,index) => {
    return (<span>{cart_products.id}</span>); 
})};

Simply adding return solved it.

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

Although not specific to the answer, this error mostly occurs when you mistakenly using a JavaScript expression inside a JavaScript context using {}

For example

let x=5;

export default function App(){ return( {x} ); };

Correct way to do this would be

let x=5;
export default function App(){ return( x ); };

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

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Another cause might be the fact that you're pointing to the wrong port.

Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.

Check the ports and run some query against the db.

Set focus on <input> element

I'm having same scenario, this worked for me but i'm not having the "hide/show" feature you have. So perhaps you could first check if you get the focus when you have the field always visible, and then try to solve why does not work when you change visibility (probably that's why you need to apply a sleep or a promise)

To set focus, this is the only change you need to do:

your Html mat input should be:

<input #yourControlName matInput>

in your TS class, reference like this in the variables section (

export class blabla...
    @ViewChild("yourControlName") yourControl : ElementRef;

Your button it's fine, calling:

  showSearch(){
       ///blabla... then finally:
       this.yourControl.nativeElement.focus();
}

and that's it. You can check this solution on this post that I found, so thanks to --> https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f

Angular - "has no exported member 'Observable'"

In my case this error was happening because I had an old version of ng cli in my computer.

The problem was solved after running:

ng update

ng update @angular/cli

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

I had the same error and I solved it by importing HttpModule in app.module.ts

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

and then in the imports[] array:

HttpModule

Property '...' has no initializer and is not definitely assigned in the constructor

It is because TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor. A workaround is to add the ! as a postfix to the variable name:

makes!: any[];

Angular 5 ngHide ngShow [hidden] not working

If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none

Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:

enter image description here

If you found display of [hidden] class is overridden, you need to add this css code to your style:

[hidden] {
    display: none !important;
}

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

getDerivedStateFromProps is used whenever you want to update state before render and update with the condition of props

GetDerivedStateFromPropd updating the stats value with the help of props value

read https://www.w3schools.com/REACT/react_lifecycle.asp#:~:text=Lifecycle%20of%20Components,Mounting%2C%20Updating%2C%20and%20Unmounting.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

In case you do need to define dataSource(), for example when you have multiple data sources, you can use:

@Autowired Environment env;

@Primary
@Bean
public DataSource customDataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("custom.datasource.url"));
    dataSource.setUsername(env.getProperty("custom.datasource.username"));
    dataSource.setPassword(env.getProperty("custom.datasource.password"));

    return dataSource;

}

By setting up the dataSource yourself (instead of using DataSourceBuilder), it fixed my problem which you also had.

The always knowledgeable Baeldung has a tutorial which explains in depth.

ReactJS: Maximum update depth exceeded error

1.If we want to pass argument in the call then we need to call the method like below As we are using arrow functions no need to bind the method in cunstructor.

onClick={() => this.save(id)} 

when we bind the method in constructor like this

this.save= this.save.bind(this);

then we need to call the method without passing any argument like below

onClick={this.save}

and we try to pass argument while calling the function as shown below then error comes like maximum depth exceeded.

 onClick={this.save(id)}

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']]);
    }

how to format date in Component of angular 5

You can find more information about the date pipe here, such as formats.

If you want to use it in your component, you can simply do

pipe = new DatePipe('en-US'); // Use your own locale

Now, you can simply use its transform method, which will be

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');

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

I had this problem too. It turned out I forgot to include one of the components in app.module.ts

Property 'value' does not exist on type 'Readonly<{}>'

The Component is defined like so:

interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }

Meaning that the default type for the state (and props) is: {}.
If you want your component to have value in the state then you need to define it like this:

class App extends React.Component<{}, { value: string }> {
    ...
}

Or:

type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
    ...
}

No provider for Http StaticInjectorError

Add these two file in your app.module.ts

import { FileTransfer } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';

after that declare these to in provider..

providers: [
    Api,
    Items,
    User,
    Camera,
    File,
    FileTransfer];

This is work for me.

How to get query parameters from URL in Angular 5?

In Angular 5, the query params are accessed by subscribing to this.route.queryParams (note that later Angular versions recommend queryParamMap, see also other answers).

Example: /app?param1=hallo&param2=123

param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
    console.log('Called Constructor');
    this.route.queryParams.subscribe(params => {
        this.param1 = params['param1'];
        this.param2 = params['param2'];
    });
}

whereas, the path variables are accessed by this.route.snapshot.params

Example: /param1/:param1/param2/:param2

param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
    this.param1 = this.route.snapshot.params.param1;
    this.param2 = this.route.snapshot.params.param2;
}

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

NullInjectorError: No provider for AngularFirestore

Open: ./src/app/app.module.ts
And import Firebase Modules at the top:

import { environment } from '../environments/environment';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';

And VERY IMPORTANT:
Remember to update 'imports' in NgModule:

@NgModule({
  declarations: [
    AppComponent,
    OtherComponent // Add other components here
    ...
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase, 'your-APP-name-here'),
    AngularFirestoreModule
  ],
  ...
})

Give it a try, it shall now work.
For detailed information follow the angularfire2 documentation:
https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md
Good luck!

Angular 5 Service to read local .json file

For Angular 7, I followed these steps to directly import json data:

In tsconfig.app.json:

add "resolveJsonModule": true in "compilerOptions"

In a service or component:

import * as exampleData from '../example.json';

And then

private example = exampleData;

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

In my case it was pretty much what Mayank Shukla's top answer says. The only detail was that my state was lacking completely the property I was defining.

For example, if you have this state:

state = {
    "a" : "A",
    "b" : "B",
}

If you're expanding your code, you might want to add a new prop so, someplace else in your code you might create a new property c whose value is not only undefined on the component's state but the property itself is undefined.

To solve this just make sure to add c into your state and give it a proper initial value.

e.g.,

state = {
    "a" : "A",
    "b" : "B",
    "c" : "C", // added and initialized property!
}

Hope I was able to explain my edge case.

Angular + Material - How to refresh a data source (mat-table)

I achieved a good solution using two resources:

refreshing both dataSource and paginator:

this.dataSource.data = this.users;
this.dataSource.connect().next(this.users);
this.paginator._changePageSize(this.paginator.pageSize);

where for example dataSource is defined here:

    users: User[];
    ...
    dataSource = new MatTableDataSource(this.users);
    ...
    this.dataSource.paginator = this.paginator;
    ...

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

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

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

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

react-router (v4) how to go back?

this.props.history.goBack();

This is the correct solution for react-router v4

But one thing you should keep in mind is that you need to make sure this.props.history is existed.

That means you need to call this function this.props.history.goBack(); inside the component that is wrapped by < Route/>

If you call this function in a component that deeper in the component tree, it will not work.

EDIT:

If you want to have history object in the component that is deeper in the component tree (which is not wrapped by < Route>), you can do something like this:

...
import {withRouter} from 'react-router-dom';

class Demo extends Component {
    ...
    // Inside this you can use this.props.history.goBack();
}

export default withRouter(Demo);

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 );

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

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

I also received this error while writing a custom form control component in Angular 7. However, none of the answers are applicable to Angular 7.

In my case, the following needed to be add to the @Component decorator:

  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MyCustomComponent),  // replace name as appropriate
      multi: true
    }
  ]

This is a case of "I don't know why it works, but it does." Chalk it up to poor design/implementation on the part of Angular.

How do you set the document title in React?

As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.

If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.

You can edit this directly or use a placeholder which will be filled from environmental variables:

/.env:

REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...

If for some reason I wanted a different title in my development environment -

/.env.development:

REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...

/public/index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...
     </head>
     <body>
         ...
     </body>
</html>

This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:

console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!

See: Adding Custom Environment Variables

No converter found capable of converting from type to type

Simple Solution::

use {nativeQuery=true} in your query.

for example

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

Catching errors in Angular HttpClient

import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

const PASSENGER_API = 'api/passengers';

getPassengers(): Observable<Passenger[]> {
  return this.http
    .get<Passenger[]>(PASSENGER_API)
    .pipe(catchError((error: HttpErrorResponse) => throwError(error)));
}

Angular 4 - Observable catch error

You should be using below

return Observable.throw(error || 'Internal Server error');

Import the throw operator using the below line

import 'rxjs/add/observable/throw';

How to get param from url in angular 4?

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

React Router Pass Param to Component

In addition to Alexander Lunas answer ... If you want to add more than one argument just use:

<Route path="/details/:id/:title" component={DetailsPage}/>

export default class DetailsPage extends Component {
  render() {
    return(
      <div>
        <h2>{this.props.match.params.id}</h2>
        <h3>{this.props.match.params.title}</h3>
      </div>
    )
  }
}

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

You need jackson dependency for this serialization and deserialization.

Add this dependency:

Gradle:

compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.

import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

@SpringBootApplication
public class MockEmployeeApplication {

  @Autowired
  private ObjectMapper objectMapper;

  public static void main(String[] args) {
    SpringApplication.run(MockEmployeeApplication.class, args);

  }

  @PostConstruct
  public void setUp() {
    objectMapper.registerModule(new JavaTimeModule());
  }
}

After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.

Add class to an element in Angular 4

If you need that each div will have its own toggle and don't want clicks to affect other divs, do this:

Here's what I did to solve this...

<div [ngClass]="{'teaser': !teaser_1 }" (click)="teaser_1=!teaser_1">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_2 }" (click)="teaser_2=!teaser_2">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_3 }" (click)="teaser_3=!teaser_3">
...content...
</div>

it requires custom numbering which sucks, but it works.

Update some specific field of an entity in android Room

I think you don't need to update only some specific field. Just update whole data.

@Update query

It is a given query basically. No need to make some new query.

@Dao
interface MemoDao {

    @Insert
    suspend fun insert(memo: Memo)

    @Delete
    suspend fun delete(memo: Memo)

    @Update
    suspend fun update(memo: Memo)
}

Memo.class

@Entity
data class Memo (
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "title") val title: String?,
    @ColumnInfo(name = "content") val content: String?,
    @ColumnInfo(name = "photo") val photo: List<ByteArray>?
)

Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this

val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)

How to add a ListView to a Column in Flutter?

You can use Flex and Flexible widgets. for example:

Flex(
direction: Axis.vertical,
children: <Widget>[
    ... other widgets ...
    Flexible(
        flex: 1,
        child: ListView.builder(
        itemCount: ...,
        itemBuilder: (context, index) {
            ...
        },
        ),
    ),
],

);

Kotlin Android start new Activity

This is my main activity where i take the username and password from edit text and setting to the intent

class MainActivity : AppCompatActivity() {
val userName = null
val password = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
    val intent = Intent(this@MainActivity,SecondActivity::class.java);
    var userName = username.text.toString()
    var password = password_field.text.toString()
    intent.putExtra("Username", userName)
    intent.putExtra("Password", password)
    startActivity(intent);
 }
}

This is my second activity where i have to receive values from the main activity

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
var strUser: String = intent.getStringExtra("Username")
var strPassword: String = intent.getStringExtra("Password")
user_name.setText("Seelan")
passwor_print.setText("Seelan")
}

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

I was having trouble with .

ERROR: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'mat-checkbox-checked': 'true'. Current value: 'false'.

The Problem here is that the updated value is not detected until the next change Detection Cycle runs.

The easiest solution is to add a Change Detection Strategy. Add these lines to your code:

import { ChangeDetectionStrategy } from "@angular/core";  // import

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: "abc",
  templateUrl: "./abc.html",
  styleUrls: ["./abc.css"],
})

NotificationCompat.Builder deprecated in Android O

  1. Need to declare a Notification channel with Notification_Channel_ID
  2. Build notification with that channel ID. For example,

...
 public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
...
...
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                NOTIFICATION_CHANNEL_ID+"_name",
                NotificationManager.IMPORTANCE_HIGH);

NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notifManager.createNotificationChannel(channel);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text))
                .setOngoing(true)
                .setContentIntent(broadcastIntent)
                .setSmallIcon(R.drawable.ic_tracker)
                .setPriority(PRIORITY_HIGH)
                .setCategory(Notification.CATEGORY_SERVICE);

        startForeground(1, builder.build());
...

Detecting real time window size changes in Angular 4

The documentation for Platform width() and height(), it's stated that these methods use window.innerWidth and window.innerHeight respectively. But using the methods are preferred since the dimensions are cached values, which reduces the chance of multiple and expensive DOM reads.

import { Platform } from 'ionic-angular';

...
private width:number;
private height:number;

constructor(private platform: Platform){
    platform.ready().then(() => {
        this.width = platform.width();
        this.height = platform.height();
    });
}

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

Important Update:

HttpModule and Http from @angular/http has been deprecated since Angular V5, should of using HttpClientModule and HttpClient from @angular/common/http instead, refer CHANGELOG.


For Angular version previous from **@4.3.0, You should inject Http from @angular/http, and HttpModule is for importing at your NgModule's import array.

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

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

Inject http at component or service

import { Http } from '@angular/http';

constructor(private http: Http) {}

For Angular version after(include) 4.3.0, you can use HttpClient from @angular/common/http instead of Http from @angular/http. Don't forget to import HttpClientModule at your NgModule's import array first.

Refer @echonax's answer.

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

What is the best way to redirect a page using React Router?

Now with react-router v15.1 and onwards we can useHistory hook, This is super simple and clear way. Here is a simple example from the source blog.

import { useHistory } from "react-router-dom";

function BackButton({ children }) {
  let history = useHistory()
  return (
    <button type="button" onClick={() => history.goBack()}>
      {children}
    </button>
  )
}

You can use this within any functional component and custom hooks. And yes this will not work with class components same as any other hook.

Learn more about this here https://reacttraining.com/blog/react-router-v5-1/#usehistory

Input type number "only numeric value" validation

Using directive it becomes easy and can be used throughout the application

HTML

<input type="text" placeholder="Enter value" numbersOnly>

As .keyCode() and .which() are deprecated, codes are checked using .key() Referred from

Directive:

@Directive({
   selector: "[numbersOnly]"
})

export class NumbersOnlyDirective {
  @Input() numbersOnly:boolean;

  navigationKeys: Array<string> = ['Backspace']; //Add keys as per requirement
  
  constructor(private _el: ElementRef) { }

  @HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
    
    if (
      // Allow: Delete, Backspace, Tab, Escape, Enter, etc
      this.navigationKeys.indexOf(e.key) > -1 || 
      (e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
      (e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
      (e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
      (e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
      (e.key === 'a' && e.metaKey === true) || // Cmd+A (Mac)
      (e.key === 'c' && e.metaKey === true) || // Cmd+C (Mac)
      (e.key === 'v' && e.metaKey === true) || // Cmd+V (Mac)
      (e.key === 'x' && e.metaKey === true) // Cmd+X (Mac)
    ) {
        return;  // let it happen, don't do anything
    }
    // Ensure that it is a number and stop the keypress
    if (e.key === ' ' || isNaN(Number(e.key))) {
      e.preventDefault();
    }
  }
}

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You get this message when you've used async in your template, but are referring to an object that isn't an Observable.

So for examples sake, lets' say I had these properties in my class:

job:Job
job$:Observable<Job>

Then in my template, I refer to it this way:

{{job | async }}

instead of:

{{job$ | async }}

You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.

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

In my case, I was moving the component UserComponent from one module appModule to anotherdashboardModule and forgot to remove the route definition from the routing of the previous moduleappModule in AppRoutingModule file.

const routes = [
 { path: 'user', component: UserComponent, canActivate: [AuthGuard]},...]

After i removed the route definition it worked fine.

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

I also have the same error. I have updated the jackson library version and error has gone.

<!-- Jackson to convert Java object to Json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

and also check your data classes that have you created getters and setters for all the properties.

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

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

MY OWN SOLUTION

I created a new component called test in this folder:

enter image description here

I also created a mock called test.json in the assests folder created by angular cli (important):

enter image description here

This mock looks like this:

[
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

In the controller of my component test import follow rxjs like this

import 'rxjs/add/operator/map'

This is important, because you have to map your response from the http get call, so you get a json and can loop it in your ngFor. Here is my code how I load the mock data. I used http get and called my path to the mock with this path this.http.get("/assets/mock/test/test.json"). After this i map the response and subscribe it. Then I assign it to my variable items and loop it with ngFor in my template. I also export the type. Here is my whole controller code:

import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'

export type Item = { id: number, name: string };

@Component({
  selector: "test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
  items: Array<Item>;

  constructor(private http: Http) {}

  ngOnInit() {
    this.http
      .get("/assets/mock/test/test.json")
      .map(data => data.json() as Array<Item>)
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }
}

And my loop in it's template:

<div *ngFor="let item of items">
  {{item.name}}
</div>

It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json. Notice that you have also to import the HTTP and Response in your controller. The same in you app.module.ts (main) like this:

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


import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

Remember to pipe Observables to async, like *ngFor item of items$ | async, where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair>, and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T.

Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

React JS get current date

You can use the react-moment package

-> https://www.npmjs.com/package/react-moment

Put in your file the next line:

import moment from "moment";

date_create: moment().format("DD-MM-YYYY hh:mm:ss")

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

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

Error: the entity type requires a primary key

I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...

Wrong PK name

public class Client
{
  public int SomeFieldName { get; set; }  // It is the ID
  ...
}

Correct PK name

public class Client
{
  public int Id { get; set; }  // It is the ID
  ...
}

public class Client
{
  public int ClientId { get; set; }  // It is the ID
  ...
}

It still posible to use wrong PK name but we have to use [Key] attribute like

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

Angular 2 Cannot find control with unspecified name attribute on formArrays

This was happening for me because I had fromArrayName instead of formArrayName somewhere

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

My case was that i was using RDS (mysql db verion 8) of AWS and was connecting my application through EC2 (my php code 5.6 was in EC2).

Here in this case since it is RDS there is no my.cnf the parameters are maintained by PARAMETER Group of AWS. Refer: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html

so what i did was:

  1. Created a new Parameter group and then edited them.

  2. Searched all character-set parameters. These are blank by default. edit them individually and select utf8 from drop down list.

character_set_client, character_set_connection, character_set_database, character_set_server

  1. SAVE

And then most important, Rebooted RDS instance.

This has solved my problem and connection from php5.6 to mysql 8.x was working great.

hope this helps.

Please view this image for better understanding. enter image description here

Async/Await Class Constructor

The other answers are missing the obvious. Simply call an async function from your constructor:

constructor() {
    setContentAsync();
}

async setContentAsync() {
    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
}

How to get input textfield values when enter key is pressed in react js?

Use onKeyDown event, and inside that check the key code of the key pressed by user. Key code of Enter key is 13, check the code and put the logic there.

Check this example:

_x000D_
_x000D_
class CartridgeShell extends React.Component {_x000D_
_x000D_
   constructor(props) {_x000D_
      super(props);_x000D_
      this.state = {value:''}_x000D_
_x000D_
      this.handleChange = this.handleChange.bind(this);_x000D_
      this.keyPress = this.keyPress.bind(this);_x000D_
   } _x000D_
 _x000D_
   handleChange(e) {_x000D_
      this.setState({ value: e.target.value });_x000D_
   }_x000D_
_x000D_
   keyPress(e){_x000D_
      if(e.keyCode == 13){_x000D_
         console.log('value', e.target.value);_x000D_
         // put the login here_x000D_
      }_x000D_
   }_x000D_
_x000D_
   render(){_x000D_
      return(_x000D_
         <input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
      )_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
_x000D_
_x000D_

Note: Replace the input element by Material-Ui TextField and define the other properties also.

ExpressionChangedAfterItHasBeenCheckedError Explained

I had a similar issue. Looking at the lifecycle hooks documentation, I changed ngAfterViewInit to ngAfterContentInit and it worked.

How to use Redirect in the new react-router-dom of Reactjs

Hi if you are using react-router v-6.0.0-beta or V6 in This version Redirect Changes to Navigate like this

import { Navigate } from 'react-router-dom'; // like this CORRECT in v6 import { Redirect } from 'react-router-dom'; // like this CORRECT in v5

import { Redirect } from 'react-router-dom'; // like this WRONG in v6 // This will give you error in V6 of react-router and react-router dom

please make sure use both same version in package.json { "react-router": "^6.0.0-beta.0", //Like this "react-router-dom": "^6.0.0-beta.0", // like this }

this above things only works well in react Router Version 6

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.

import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule

...

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    RouterModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MaterialModule],

Hibernate Error executing DDL via JDBC Statement

Another sneaky issue related to this is naming your columns with - instead of _.

Something like this will trigger an error at the moment your tables are getting created.

@Column(name="verification-token")

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Add below line to file where error is being thrown.This should fix the issue

declare var Promise: any;

P.S: This is definitely not the optimal solution

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

You are using the --noImplicitAny and TypeScript doesn't know about the type of the Users object. In this case, you need to explicitly define the user type.

Change this line:

let user = Users.find(user => user.id === query);

to this:

let user = Users.find((user: any) => user.id === query); 
// use "any" or some other interface to type this argument

Or define the type of your Users object:

//...
interface User {
    id: number;
    name: string;
    aliases: string[];
    occupation: string;
    gender: string;
    height: {ft: number; in: number;}
    hair: string;
    eyes: string;
    powers: string[]
}
//...
const Users = <User[]>require('../data');
//...

Typescript ReferenceError: exports is not defined

for me, removing "esModuleInterop": true from tsconfig.json did the trick.

How to use Object.values with typescript?

I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo.

In my case the issue was in the tsconfig.lib.json in the library folder which did not have es2017 included in the lib section.

Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json as well as your application tsconfig.json

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.

Here is what I've done to make it work

import React from 'react';
import App from './App';

import ReactDOM from 'react-dom';
import {
    HashRouter,
    Route
} from 'react-router-dom';


 ReactDOM.render((
        <HashRouter>
            <div>
                <Route path="/" render={()=><App items={temasArray}/>}/>
            </div>
        </HashRouter >
    ), document.getElementById('root'));

That's the only way I have managed to make it work without any errors or warnings.

In case you want to pass props to your component for me the easiest way is this one:

 <Route path="/" render={()=><App items={temasArray}/>}/>

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Node.js ES6 classes with require

Yes, your example would work fine.

As for exposing your classes, you can export a class just like anything else:

class Animal {...}
module.exports = Animal;

Or the shorter:

module.exports = class Animal {

};

Once imported into another module, then you can treat it as if it were defined in that file:

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

'React' must be in scope when using JSX react/react-in-jsx-scope?

Follow as in picture for removing that lint error and adding automatic fix by addin g--fix in package.json

enter image description here

REACT - toggle class onclick

Well, your addActiveClass needs to know what was clicked. Something like this could work (notice that I've added the information which divs are active as a state array, and that onClick now passes the information what was clicked as a parameter after which the state is accordingly updated - there are certainly smarter ways to do it, but you get the idea).

class Test extends Component(){

  constructor(props) {
    super(props);
    this.state = {activeClasses: [false, false, false]};
    this.addActiveClass= this.addActiveClass.bind(this);
  }

  addActiveClass(index) {
    const activeClasses = [...this.state.activeClasses.slice(0, index), !this.state.activeClasses[index], this.state.activeClasses.slice(index + 1)].flat();
    this.setState({activeClasses});
  }

  render() {
    const activeClasses = this.state.activeClasses.slice();
    return (
      <div>
        <div className={activeClasses[0]? "active" : "inactive"} onClick={() => this.addActiveClass(0)}>
          <p>0</p>
        </div>
        <div className={activeClasses[1]? "active" : "inactive"} onClick={() => this.addActiveClass(1)}>
          <p>1</p>
        </div>
          <div  onClick={() => this.addActiveClass(2)}>
          <p>2</p>
        </div>
      </div>
    );
  }
}

React: trigger onChange if input value is changing by state?

you must do 4 following step :

  1. create event

    var event = new Event("change",{
        detail: {
            oldValue:yourValueVariable,
            newValue:!yourValueVariable
        },
        bubbles: true,
        cancelable: true
    });
    event.simulated = true;
    let tracker = this.yourComponentDomRef._valueTracker;
    if (tracker) {
        tracker.setValue(!yourValueVariable);
    }
    
  2. bind value to component dom

    this.yourComponentDomRef.value = !yourValueVariable;
    
  3. bind element onchange to react onChange function

     this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
    
  4. dispatch event

    this.yourComponentDomRef.dispatchEvent(event);
    

in above code yourComponentDomRef refer to master dom of your React component for example <div className="component-root-dom" ref={(dom)=>{this.yourComponentDomRef= dom}}>

take(1) vs first()

There's one really important difference which is not mentioned anywhere.

take(1) emits 1, completes, unsubscribes

first() emits 1, completes, but doesn't unsubscribe.

It means that your upstream observable will still be hot after first() which is probably not expected behavior.

UPD: This referes to RxJS 5.2.0. This issue might be already fixed.

Laravel 5.4 redirection to custom url after login

Path Customization (tested in laravel 7) When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect path using the HOME constant defined in your RouteServiceProvider:

public const HOME = '/home';

<div> cannot appear as a descendant of <p>

I got this warning by using Material UI components, then I test the component="div" as prop to the below code and everything became correct:

import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';

<Typography component="span">
  <Grid component="span">
    Lorem Ipsum
  </Grid>
</Typography>

Actually, this warning happens because in the Material UI the default HTML tag of Grid component is div tag and the default Typography HTML tag is p tag, So now the warning happens,

Warning: validateDOMnesting(...): <div> cannot appear as a descendant of <p>

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

This is happening because this is a dynamic component and you didn't add it to entryComponents under @NgModule.

Simply add it there:

@NgModule({
  /* ----------------- */
  entryComponents: [ DialogResultExampleDialog ] // <---- Add it here

Look at how the Angular team talks about entryComponents:

entryComponents?: Array<Type<any>|any[]>

Specifies a list of components that should be compiled when this module is defined. For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.

Also, this is the list of the methods on @NgModule including entryComponents...

As you can see, all of them are optional (look at the question marks), including entryComponents which accept an array of components:

@NgModule({ 
  providers?: Provider[]
  declarations?: Array<Type<any>|any[]>
  imports?: Array<Type<any>|ModuleWithProviders|any[]>
  exports?: Array<Type<any>|any[]>
  entryComponents?: Array<Type<any>|any[]>
  bootstrap?: Array<Type<any>|any[]>
  schemas?: Array<SchemaMetadata|any[]>
  id?: string
})

Attaching click to anchor tag in angular

<a href="javascript:void(0);" (click)="onGoToPage2()">Go to Page 2</a>

How to render an array of objects in React?

Try this:

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

  }

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

angular2: Error: TypeError: Cannot read property '...' of undefined

Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class

  myObj:any = {
    doSomething: function () { console.log('doing something'); return 'doing something'; },
  };
  myArray:any;
  constructor() { }

  ngOnInit() {
    this.myArray = [this.myObj];
  }

You can use it in template html file as following:

<div>test-1: {{  myObj?.doSomething()}}</div>
<div>test-2: {{  myArray[0].doSomething()}}</div>
<div>test-3: {{  myArray[2]?.doSomething()}}</div>

No value accessor for form control

If you must use the label for the formControl. Like the Ant Design Checkbox. It may throw this error while running tests. You can use ngDefaultControl

<label nz-checkbox formControlName="isEnabled" ngDefaultControl>
    Hello
</label>

<nz-switch nzSize="small" formControlName="mandatory" ngDefaultControl></nz-switch>

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

ngOnInit() is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

ngAfterViewInit() is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.

How do you format a Date/Time in TypeScript?

For Angular you should simply use formatDate instead of the DatePipe.

import {formatDate} from '@angular/common';

constructor(@Inject(LOCALE_ID) private locale: string) { 
    this.dateString = formatDate(Date.now(),'yyyy-MM-dd',this.locale);
}

Reactive forms - disabled attribute

this.form.disable()
this.form.enable()

For one formcontrol makes disable

this.form.get('first').disable()
this.form.get('first').enable()

Or initial set method.

first: new FormControl({disabled: true}, Validators.required)

remove item from stored array in angular 2

Use splice() to remove item from the array its refresh the array index to be consequence.

delete will remove the item from the array but its not refresh the array index which means if you want to remove third item from four array items the index of elements will be after delete the element 0,1,4

this.data.splice(this.data.indexOf(msg), 1)

How to toggle boolean state of react component?

Here's an example using hooks (requires React >= 16.8.0)

_x000D_
_x000D_
// import React, { useState } from 'react';_x000D_
const { useState } = React;_x000D_
_x000D_
function App() {_x000D_
  const [checked, setChecked] = useState(false);_x000D_
  const toggleChecked = () => setChecked(value => !value);_x000D_
  return (_x000D_
    <input_x000D_
      type="checkbox"_x000D_
      checked={checked}_x000D_
      onChange={toggleChecked}_x000D_
    />_x000D_
  );_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"><div>
_x000D_
_x000D_
_x000D_

Joining Spark dataframes on the key

Alias Approach using scala (this is example given for older version of spark for spark 2.x see my other answer) :

You can use case class to prepare sample dataset ... which is optional for ex: you can get DataFrame from hiveContext.sql as well..

import org.apache.spark.sql.functions.col

case class Person(name: String, age: Int, personid : Int)

case class Profile(name: String, personid  : Int , profileDescription: String)

    val df1 = sqlContext.createDataFrame(
   Person("Bindu",20,  2) 
:: Person("Raphel",25, 5) 
:: Person("Ram",40, 9):: Nil)


val df2 = sqlContext.createDataFrame(
Profile("Spark",2,  "SparkSQLMaster") 
:: Profile("Spark",5, "SparkGuru") 
:: Profile("Spark",9, "DevHunter"):: Nil
)

// you can do alias to refer column name with aliases to  increase readablity

val df_asPerson = df1.as("dfperson")
val df_asProfile = df2.as("dfprofile")


val joined_df = df_asPerson.join(
    df_asProfile
, col("dfperson.personid") === col("dfprofile.personid")
, "inner")


joined_df.select(
  col("dfperson.name")
, col("dfperson.age")
, col("dfprofile.name")
, col("dfprofile.profileDescription"))
.show

sample Temp table approach which I don't like personally...

The reason to use the registerTempTable( tableName ) method for a DataFrame, is so that in addition to being able to use the Spark-provided methods of a DataFrame, you can also issue SQL queries via the sqlContext.sql( sqlQuery ) method, that use that DataFrame as an SQL table. The tableName parameter specifies the table name to use for that DataFrame in the SQL queries.

df_asPerson.registerTempTable("dfperson");
df_asProfile.registerTempTable("dfprofile")

sqlContext.sql("""SELECT dfperson.name, dfperson.age, dfprofile.profileDescription
                  FROM  dfperson JOIN  dfprofile
                  ON dfperson.personid == dfprofile.personid""")

If you want to know more about joins pls see this nice post : beyond-traditional-join-with-apache-spark

enter image description here

Note : 1) As mentioned by @RaphaelRoth ,

val resultDf = PersonDf.join(ProfileDf,Seq("personId")) is good approach since it doesnt have duplicate columns from both sides if you are using inner join with same table.
2) Spark 2.x example updated in another answer with full set of join operations supported by spark 2.x with examples + result

TIP :

Also, important thing in joins : broadcast function can help to give hint please see my answer

How to Call a Function inside a Render in React/Jsx

To call the function you have to add ()

{this.renderIcon()}   

module.exports vs. export default in Node.js and ES6

The issue is with

  • how ES6 modules are emulated in CommonJS
  • how you import the module

ES6 to CommonJS

At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?

Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.

ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var foo = exports.foo = 42;
exports.default = 21; 

Here we can see that the default export becomes a property on the exports object, just like foo.

Import the module

We can import the module in two ways: Either using CommonJS or using ES6 import syntax.

Your issue: I believe you are doing something like:

var bar = require('./input');
new bar();

expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!

So in order to access the default export we actually have to do

var bar = require('./input').default;

If we use ES6 module syntax, namely

import bar from './input';
console.log(bar);

Babel will transform it to

'use strict';

var _input = require('./input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_input2.default);

You can see that every access to bar is converted to access .default.

Reload child component when variables on parent component changes. Angular2

update of @Vladimir Tolstikov's answer

Create a Child Component that use ngOnChanges.

ChildComponent.ts::

import { Component, OnChanges, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

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

export class ChildComponent implements OnChanges {
  @Input() child_id;

  constructor(private route: ActivatedRoute) { }

  ngOnChanges() {
    // create header using child_id
    console.log(this.child_id);
  }
}

now use it in MasterComponent's template and pass data to ChildComponent like:

<child [child_id]="child_id"></child>

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

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

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

How to serve up images in Angular2?

Just put your images in the assets folder refer them in your html pages or ts files with that link.

Angular 2 Checkbox Two Way Data Binding

Unfortunately solution provided by @hakani is not two-way binding. It just handles One-way changing model from UI/FrontEnd part.

Instead the simple:

<input [(ngModel)]="checkboxFlag" type="checkbox"/>

will do two-way binding for checkbox.

Afterwards, when Model checkboxFlag is changed from Backend or UI part - voila, checkboxFlag stores actual checkbox state.

To be sure I've prepared Plunker code to present the result : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk

Just to complete this answer you should include the import { FormsModule } from '@angular/forms' into app.module.ts and add to imports array i.e

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

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

React component initialize state from props

You could use the short form like below if you want to add all props to state and retain the same names.

constructor(props) {
    super(props);
    this.state = {
       ...props
    }
    //...
}

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

use moment in your function like this

 moment(new Date(date)).format('MM/DD/YYYY')

How to get height and width of device display in angular2 using typescript?

For those who want to get height and width of device even when the display is resized (dynamically & in real-time):

  • Step 1:

In that Component do: import { HostListener } from "@angular/core";

  • Step 2:

In the component's class body write:

@HostListener('window:resize', ['$event'])
onResize(event?) {
   this.screenHeight = window.innerHeight;
   this.screenWidth = window.innerWidth;
}
  • Step 3:

In the component's constructor call the onResize method to initialize the variables. Also, don't forget to declare them first.

constructor() {
  this.onResize();
}    

Complete code:

import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class FooComponent implements OnInit {
    screenHeight: number;
    screenWidth: number;

    constructor() {
        this.getScreenSize();
    }

    @HostListener('window:resize', ['$event'])
    getScreenSize(event?) {
          this.screenHeight = window.innerHeight;
          this.screenWidth = window.innerWidth;
          console.log(this.screenHeight, this.screenWidth);
    }

}

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

Store that objects into Array  and then iterate the Array
export class AppComponent {

 public obj: object =null;
 public myArr=[];

  constructor(){

    this.obj = {
      jon : {username: 'Jon', genrePref: 'rock'},
      lucy : {username: 'Lucy', genrePref: 'pop'},
      mike : {username: 'Mike', genrePref: 'rock'},
      luke : {username: 'Luke', genrePref: 'house'},
      james : {username: 'James', genrePref: 'house'},
      dave : {username: 'Dave', genrePref: 'bass'},
      sarah : {username: 'Sarah', genrePref: 'country'},
      natalie : {username: 'Natalie', genrePref: 'bass'}
  }
  }
  ngOnInit(){
    this.populateCode();
  }

  populateCode(){
    for( let i in this.obj) {   //Pay attention to the 'in'
    console.log(this.obj[i]);
    this.myArr.push(this.obj[i]);
  }
  }
 }



<div *ngFor="let item of myArr ">
    {{item.username}}
    {{item.genrePref}}
  </div>

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

Error: Cannot invoke an expression whose type lacks a call signature

It means you're trying to call something that isn't a function

const foo = 'string'
foo() // error

Class constructor type in typescript?

Solution from typescript interfaces reference:

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("beep beep");
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("tick tock");
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

So the previous example becomes:

interface AnimalConstructor {
    new (): Animal;
}

class Animal {
    constructor() {
        console.log("Animal");
    }
}

class Penguin extends Animal {
    constructor() {
        super();
        console.log("Penguin");
    }
}

class Lion extends Animal {
    constructor() {
        super();
        console.log("Lion");
    }
}

class Zoo {
    AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'

    constructor(AnimalClass: AnimalConstructor) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

In my case, I forgot to add my component in the Declaration array of app.module.ts, and voila! the issue was fixed.

Update React component every second

The following code is a modified example from React.js website.

Original code is available here: https://reactjs.org/#a-simple-component

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      seconds: parseInt(props.startTimeInSeconds, 10) || 0
    };
  }

  tick() {
    this.setState(state => ({
      seconds: state.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  formatTime(secs) {
    let hours   = Math.floor(secs / 3600);
    let minutes = Math.floor(secs / 60) % 60;
    let seconds = secs % 60;
    return [hours, minutes, seconds]
        .map(v => ('' + v).padStart(2, '0'))
        .filter((v,i) => v !== '00' || i > 0)
        .join(':');
  }

  render() {
    return (
      <div>
        Timer: {this.formatTime(this.state.seconds)}
      </div>
    );
  }
}

ReactDOM.render(
  <Timer startTimeInSeconds="300" />,
  document.getElementById('timer-example')
);

How can I change the user on Git Bash?

For Mac Users

I am using Mac and I was facing the same problem while I was trying to push a project from Android Studio. The reason for that is another user had previously logged into GitHub and his credentials were saved in Keychain Access.

The solution is to delete all the information store in keychain for that process

enter image description here

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

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

While it seems @Miguel A. Arilla has pointed it out clearly and I voted up for him, I created on top of his useful solution another solution which looks neat but requires a lot more work.

It definitely depends on the above solution. So basically I created something similar to Func<string, IService>> and I called it IServiceAccessor as an interface and then I had to add a some more extensions to the IServiceCollection as such:

public static IServiceCollection AddSingleton<TService, TImplementation, TServiceAccessor>(
            this IServiceCollection services,
            string instanceName
        )
            where TService : class
            where TImplementation : class, TService
            where TServiceAccessor : class, IServiceAccessor<TService>
        {
            services.AddSingleton<TService, TImplementation>();
            services.AddSingleton<TServiceAccessor>();
            var provider = services.BuildServiceProvider();
            var implementationInstance = provider.GetServices<TService>().Last();
            var accessor = provider.GetServices<TServiceAccessor>().First();

            var serviceDescriptors = services.Where(d => d.ServiceType == typeof(TServiceAccessor));
            while (serviceDescriptors.Any())
            {
                services.Remove(serviceDescriptors.First());
            }

            accessor.SetService(implementationInstance, instanceName);
            services.AddSingleton<TServiceAccessor>(prvd => accessor);
            return services;
        }

The service Accessor looks like:

 public interface IServiceAccessor<TService>
    {
         void Register(TService service,string name);
         TService Resolve(string name);

    }

The end result,you will be able to register services with names or named instances like we used to do with other containers..for instance:

    services.AddSingleton<IEncryptionService, SymmetricEncryptionService, EncyptionServiceAccessor>("Symmetric");
    services.AddSingleton<IEncryptionService, AsymmetricEncryptionService, EncyptionServiceAccessor>("Asymmetric");

That is enough for now, but to make your work complete, it is better to add more extension methods as you can to cover all types of registrations following the same approach.

There was another post on stackoverflow, but I can not find it, where the poster has explained in details why this feature is not supported and how to work around it, basically similar to what @Miguel stated. It was nice post even though I do not agree with each point because I think there are situation where you really need named instances. I will post that link here once I find it again.

As a matter of fact, you do not need to pass that Selector or Accessor:

I am using the following code in my project and it worked well so far.

 /// <summary>
    /// Adds the singleton.
    /// </summary>
    /// <typeparam name="TService">The type of the t service.</typeparam>
    /// <typeparam name="TImplementation">The type of the t implementation.</typeparam>
    /// <param name="services">The services.</param>
    /// <param name="instanceName">Name of the instance.</param>
    /// <returns>IServiceCollection.</returns>
    public static IServiceCollection AddSingleton<TService, TImplementation>(
        this IServiceCollection services,
        string instanceName
    )
        where TService : class
        where TImplementation : class, TService
    {
        var provider = services.BuildServiceProvider();
        var implementationInstance = provider.GetServices<TService>().LastOrDefault();
        if (implementationInstance.IsNull())
        {
            services.AddSingleton<TService, TImplementation>();
            provider = services.BuildServiceProvider();
            implementationInstance = provider.GetServices<TService>().Single();
        }
        return services.RegisterInternal(instanceName, provider, implementationInstance);
    }

    private static IServiceCollection RegisterInternal<TService>(this IServiceCollection services,
        string instanceName, ServiceProvider provider, TService implementationInstance)
        where TService : class
    {
        var accessor = provider.GetServices<IServiceAccessor<TService>>().LastOrDefault();
        if (accessor.IsNull())
        {
            services.AddSingleton<ServiceAccessor<TService>>();
            provider = services.BuildServiceProvider();
            accessor = provider.GetServices<ServiceAccessor<TService>>().Single();
        }
        else
        {
            var serviceDescriptors = services.Where(d => d.ServiceType == typeof(IServiceAccessor<TService>));
            while (serviceDescriptors.Any())
            {
                services.Remove(serviceDescriptors.First());
            }
        }
        accessor.Register(implementationInstance, instanceName);
        services.AddSingleton<TService>(prvd => implementationInstance);
        services.AddSingleton<IServiceAccessor<TService>>(prvd => accessor);
        return services;
    }

    //
    // Summary:
    //     Adds a singleton service of the type specified in TService with an instance specified
    //     in implementationInstance to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection.
    //
    // Parameters:
    //   services:
    //     The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the service
    //     to.
    //   implementationInstance:
    //     The instance of the service.
    //   instanceName:
    //     The name of the instance.
    //
    // Returns:
    //     A reference to this instance after the operation has completed.
    public static IServiceCollection AddSingleton<TService>(
        this IServiceCollection services,
        TService implementationInstance,
        string instanceName) where TService : class
    {
        var provider = services.BuildServiceProvider();
        return RegisterInternal(services, instanceName, provider, implementationInstance);
    }

    /// <summary>
    /// Registers an interface for a class
    /// </summary>
    /// <typeparam name="TInterface">The type of the t interface.</typeparam>
    /// <param name="services">The services.</param>
    /// <returns>IServiceCollection.</returns>
    public static IServiceCollection As<TInterface>(this IServiceCollection services)
         where TInterface : class
    {
        var descriptor = services.Where(d => d.ServiceType.GetInterface(typeof(TInterface).Name) != null).FirstOrDefault();
        if (descriptor.IsNotNull())
        {
            var provider = services.BuildServiceProvider();
            var implementationInstance = (TInterface)provider?.GetServices(descriptor?.ServiceType)?.Last();
            services?.AddSingleton(implementationInstance);
        }
        return services;
    }

@viewChild not working - cannot read property nativeElement of undefined

it just simple :import this directory

import {Component, Directive, Input, ViewChild} from '@angular/core';

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

Simple solution :

step 1: import ReactiveFormModule

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

step 2: add "ReactiveFormsModule" to import section

imports: [

    ReactiveFormsModule
  ]

Step 3: restart App and Done

Example :

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {ReactiveFormsModule} from '@angular/forms';
import { EscalationManagementRoutingModule } from './escalation-management-routing.module';
import { EscalationManagementRouteWrapperComponent } from './escalation-management-route-wrapper.component';


@NgModule({
  declarations: [EscalationManagementRouteWrapperComponent],
  imports: [
    CommonModule,
    EscalationManagementRoutingModule,
    ReactiveFormsModule
  ]
})
export class EscalationManagementModule { }

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

Can't bind to 'ngIf' since it isn't a known property of 'div'

Instead of [ngIf] you should use *ngIf like this:

<div *ngIf="isAuth" id="sidebar">

React js change child component's state from parent component

Above answer is partially correct for me, but In my scenario, I want to set the value to a state, because I have used the value to show/toggle a modal. So I have used like below. Hope it will help someone.

class Child extends React.Component {
  state = {
    visible:false
  };

  handleCancel = (e) => {
      e.preventDefault();
      this.setState({ visible: false });
  };

  componentDidMount() {
    this.props.onRef(this)
  }

  componentWillUnmount() {
    this.props.onRef(undefined)
  }

  method() {
    this.setState({ visible: true });
  }

  render() {
    return (<Modal title="My title?" visible={this.state.visible} onCancel={this.handleCancel}>
      {"Content"}
    </Modal>)
  }
}

class Parent extends React.Component {
  onClick = () => {
    this.child.method() // do stuff
  }
  render() {
    return (
      <div>
        <Child onRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.method()</button>
      </div>
    );
  }
}

Reference - https://github.com/kriasoft/react-starter-kit/issues/909#issuecomment-252969542

Call child component method from parent class - Angular

Angular – Call Child Component’s Method in Parent Component’s Template

You have ParentComponent and ChildComponent that looks like this.

parent.component.html

enter image description here

parent.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  constructor() {
  }
}

child.component.html

<p>
  This is child
</p>

child.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor() {
  }

  doSomething() {
    console.log('do something');
  }
}

When serve, it looks like this:

enter image description here

When user focus on ParentComponent’s input element, you want to call ChildComponent’s doSomething() method.

Simply do this:

  1. Give app-child selector in parent.component.html a DOM variable name (prefix with # – hashtag), in this case we call it appChild.
  2. Assign expression value (of the method you want to call) to input element’s focus event.

enter image description here

The result:

enter image description here

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

There are multiple possible causes for this error:

1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input() decorator

Your html file:

<body [x]="...">

Your class file:

export class YourComponentClass {

  @Input()
  x: string;
  ...
}

(make sure you also have the parentheses)

2) Make sure you registered your component/directive/pipe classes in NgModule:

@NgModule({
  ...
  declarations: [
    ...,
    YourComponentClass
  ],
  ...
})

See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.

3) Also happens if you have a typo in your angular directive. For example:

<div *ngif="...">
     ^^^^^

Instead of:

<div *ngIf="...">

This happens because under the hood angular converts the asterisk syntax to:

<div [ngIf]="...">

Add timestamp column with default NOW() for new rows only

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

For some reason in Angular 6 simply importing the FormsModule did not fix my issue. What finally fixed my issue was by adding

import { CommonModule } from '@angular/common';

@NgModule({
  imports: [CommonModule],
})

export class MyClass{
}

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

From the Documentation

As with components, you can add as many directive property bindings as you need by stringing them along in the template.

Add an input property to HighlightDirective called defaultColor:

@Input() defaultColor: string;

Markup

<p [myHighlight]="color" defaultColor="violet">
  Highlight me too!
</p>

Angular knows that the defaultColor binding belongs to the HighlightDirective because you made it public with the @Input decorator.

Either way, the @Input decorator tells Angular that this property is public and available for binding by a parent component. Without @Input, Angular refuses to bind to the property.

For your example

With many parameters

Add properties into the Directive class with @Input() decorator

@Directive({
    selector: '[selectable]'
})
export class SelectableDirective{
    private el: HTMLElement;

    @Input('selectable') option:any;   
    @Input('first') f;
    @Input('second') s;

    ...
}

And in the template pass bound properties to your li element

<li *ngFor = 'let opt of currentQuestion.options' 
    [selectable] = 'opt' 
    [first]='YourParameterHere'
    [second]='YourParameterHere'
    (selectedOption) = 'onOptionSelection($event)'>
    {{opt.option}}
</li>

Here on the li element we have a directive with name selectable. In the selectable we have two @Input()'s, f with name first and s with name second. We have applied these two on the li properties with name [first] and [second]. And our directive will find these properties on that li element, which are set for him with @Input() decorator. So selectable, [first] and [second] will be bound to every directive on li, which has property with these names.

With single parameter

@Directive({
    selector: '[selectable]'
})
export class SelectableDirective{
    private el: HTMLElement;

    @Input('selectable') option:any;   
    @Input('params') params;

    ...
}

Markup

<li *ngFor = 'let opt of currentQuestion.options' 
    [selectable] = 'opt' 
    [params]='{firstParam: 1, seconParam: 2, thirdParam: 3}'
    (selectedOption) = 'onOptionSelection($event)'>
    {{opt.option}}
</li>

what is right way to do API call in react js?

This part from React v16 documentation will answer your question, read on about componentDidMount():

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

As you see, componentDidMount is considered the best place and cycle to do the api call, also access the node, means by this time it's safe to do the call, update the view or whatever you could do when document is ready, if you are using jQuery, it should somehow remind you document.ready() function, where you could make sure everything is ready for whatever you want to do in your code...

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

React prevent event bubbling in nested components on click

I had the same issue. I found stopPropagation did work. I would split the list item into a separate component, as so:

class List extends React.Component {
  handleClick = e => {
    // do something
  }

  render() {
    return (
      <ul onClick={this.handleClick}>
        <ListItem onClick={this.handleClick}>Item</ListItem> 
      </ul>
    )
  }
}

class ListItem extends React.Component {
  handleClick = e => {
    e.stopPropagation();  //  <------ Here is the magic
    this.props.onClick();
  }

  render() {
    return (
      <li onClick={this.handleClick}>
        {this.props.children}
      </li>       
    )
  }
}

WARNING: sanitizing unsafe style value url

Use this <div [ngStyle]="{'background-image':'url('+imageUrl+')'}"></div> this solved the problem for me.

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

Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:

In public class Startup

add a property

public IConfigurationRoot Configuration { get; }

And then add a singleton IHttpContextAccessor to DI in ConfigureServices.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then in Configure

    public void Configure(
              IApplicationBuilder app
             ,IHostingEnvironment env
             ,ILoggerFactory loggerFactory
    )
    {

add the DI Parameter IServiceProvider svp, so the method looks like:

    public void Configure(
           IApplicationBuilder app
          ,IHostingEnvironment env
          ,ILoggerFactory loggerFactory
          ,IServiceProvider svp)
    {

Next, create a replacement class for System.Web:

namespace System.Web
{

    namespace Hosting
    {
        public static class HostingEnvironment 
        {
            public static bool m_IsHosted;

            static HostingEnvironment()
            {
                m_IsHosted = false;
            }

            public static bool IsHosted
            {
                get
                {
                    return m_IsHosted;
                }
            }
        }
    }


    public static class HttpContext
    {
        public static IServiceProvider ServiceProvider;

        static HttpContext()
        { }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;
            }
        }


    } // End Class HttpContext 


}

Now in Configure, where you added the IServiceProvider svp, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)

and set HostingEnvironment.IsHosted to true

System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    ServiceProvider = svp;
    System.Web.HttpContext.ServiceProvider = svp;
    System.Web.Hosting.HostingEnvironment.m_IsHosted = true;


    app.UseCookieAuthentication(new CookieAuthenticationOptions()
    {
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
        AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest

       , CookieHttpOnly=false

    });

Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start in global.asax.

I stress again, this only works if you actually added

services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.


Perhaps a more maintainable method would be adding this helper class

namespace System.Web
{

    public static class HttpContext
    {
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;


        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;
        }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }


    }


}

And then calling HttpContext.Configure in Startup->Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();


    System.Web.HttpContext.Configure(app.ApplicationServices.
        GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
    );

Modify property value of the objects in list using Java 8 streams

You can do it using streams map function like below, get result in new stream for further processing.

Stream<Fruit> newFruits = fruits.stream().map(fruit -> {fruit.name+="s"; return fruit;});
        newFruits.forEach(fruit->{
            System.out.println(fruit.name);
        });

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

I experienced this when writing an import statement wrong while importing a function, rather than a class. If removeMaterial is a function in another module:

Right:

import { removeMaterial } from './ClaimForm';

Wrong:

import removeMaterial from './ClaimForm';

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

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

Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

export function HelloChandu() {

}

export function HelloTester() {

}

Then import them like so:

import { HelloChandu } from './helpers'

or...

import functions from './helpers' then functions.HelloChandu

How do I declare a model class in my Angular 2 component using TypeScript?

export class Car {
  id: number;
  make: string;
  model: string;
  color: string;
  year: Date;

  constructor(car) {
      {
        this.id = car.id;
        this.make = car.make || '';
        this.model = car.model || '';
        this.color = car.color || '';
        this.year = new Date(car.year).getYear();
      }
  }
}

The || can become super useful for very complex data objects to default data that doesn't exist.

. .

In your component.ts or service.ts file you can deserialize response data into the model:

// Import the car model
import { Car } from './car.model.ts';

// If single object
car = new Car(someObject);

// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));

How to convert an object to JSON correctly in Angular 2 with TypeScript

If you are solely interested in outputting the JSON somewhere in your HTML, you could also use a pipe inside an interpolation. For example:

<p> {{ product | json }} </p>

I am not entirely sure it works for every AngularJS version, but it works perfectly in my Ionic App (which uses Angular 2+).

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

'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) {}

Getting Unexpected Token Export

I fixed this by making an entry point file like.

// index.js
require = require('esm')(module)
module.exports = require('./app.js')

and any file I imported inside app.js and beyond worked with imports/exports now you just run it like node index.js

Note: if app.js uses export default, this becomes require('./app.js').default when using the entry point file.

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

Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');

Dec 4, 2020 4:58 PM

OtherFormats

moment.locale();         // en
moment().format('LT');   // 4:59 PM
moment().format('LTS');  // 4:59:47 PM
moment().format('L');    // 12/08/2020
moment().format('l');    // 12/8/2020
moment().format('LL');   // December 8, 2020
moment().format('ll');   // Dec 8, 2020
moment().format('LLL');  // December 8, 2020 4:59 PM
moment().format('lll');  // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

Angular 2 Date Input not binding to date value

If you are using a modern browser there's a simple solution.

First, attach a template variable to the input.

<input type="date" #date />

Then pass the variable into your receiving method.

<button (click)="submit(date)"></button>

In your controller just accept the parameter as type HTMLInputElement and use the method valueAsDate on the HTMLInputElement.

submit(date: HTMLInputElement){
    console.log(date.valueAsDate);
}

You can then manipulate the date anyway you would a normal date.

You can also set the value of your <input [value]= "..."> as you would normally.

Personally, as someone trying to stay true to the unidirectional data flow, i try to stay away from two way data binding in my components.

How do you access the element HTML from within an Angular attribute directive?

Base on @Mark answer, I add the constructor to directive and it work with me.

I share a sample to whom concern.

constructor(private el: ElementRef, private renderer: Renderer) {
}

TS file

@Directive({ selector: '[accordion]' })
export class AccordionDirective {

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  @HostListener('click', ['$event']) onClick($event) {
    console.info($event);

    this.el.nativeElement.classList.toggle('is-open');

    var content = this.el.nativeElement.nextElementSibling;
    if (content.style.maxHeight) {
      // accordion is currently open, so close it
      content.style.maxHeight = null;
    } else {
      // accordion is currently closed, so open it
      content.style.maxHeight = content.scrollHeight + "px";

    }
  }
}

HTML

<button accordion class="accordion">Accordian #1</button>
    <div class="accordion-content">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
        ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
      </p>     
    </div>

Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

I have encountered this error by mistyping the service's name, i.e. constructor (private myService: MyService).

For misspelled services, I was able to determine which service was the problem (I had several listed in the constructor) by inspecting the page in Chrome->Console. You will see as part of the message a "parameter" array list by displaying object Object, object Object, ? (or something like that). Notice where the "?" is and that is the position of the service that is causing the problem.

Angular 2 TypeScript how to find element in Array

You need to use method Array.filter:

this.persons =  this.personService.getPersons().filter(x => x.id == this.personId)[0];

or Array.find

this.persons =  this.personService.getPersons().find(x => x.id == this.personId);

Angular 2 - Setting selected value on dropdown list

In my case i was returning string value from my api eg: "35" and in my HTML i was using

       <mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
            <mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
              {{ state.stateName }}
            </mat-option>
          </mat-select>

Like others mentioned in the comment value will only accept integer values i guess. So what I did is I converted my string value to integer in my component class like below

          var x = user.state;
          var y: number = +x;

and then assigned it like

  this.EditProfileForm.get('states').setValue(y);

Now the correct values is getting setting by default.

<img>: Unsafe value used in a resource URL context

It is possible to set image as background image to avoid unsafe url error:

<div [style.backgroundImage]="'url(' + imageUrl + ')'" class="show-image"></div>

CSS:

.show-image {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-size: cover;        
}

How to create empty constructor for data class in Kotlin Android

If you give a default value to each primary constructor parameter:

data class Item(var id: String = "",
            var title: String = "",
            var condition: String = "",
            var price: String = "",
            var categoryId: String = "",
            var make: String = "",
            var model: String = "",
            var year: String = "",
            var bodyStyle: String = "",
            var detail: String = "",
            var latitude: Double = 0.0,
            var longitude: Double = 0.0,
            var listImages: List<String> = emptyList(),
            var idSeller: String = "")

and from the class where the instances you can call it without arguments or with the arguments that you have that moment

var newItem = Item()

var newItem2 = Item(title = "exampleTitle",
            condition = "exampleCondition",
            price = "examplePrice",
            categoryId = "exampleCategoryId")

How to initialize an array in angular2 and typescript

I don't fully understand what you really mean by initializing an array?

Here's an example:

class Environment {

    // you can declare private, public and protected variables in constructor signature 
    constructor(
        private id: string,
        private name: string
    ) { 
        alert( this.id );
    }
}


let environments = new Environment('a','b');

// creating and initializing array of Environment objects
let envArr: Array<Environment> = [ 
        new Environment('c','v'), 
        new Environment('c','v'), 
        new Environment('g','g'), 
        new Environment('3','e') 
  ];

Try it here : https://www.typescriptlang.org/play/index.html

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Using an array from Observable Object with ngFor and Async Pipe Angular 2

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

When to use Interface and Model in TypeScript / Angular

Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:

this.http.get('...')
    .map(res => <Product[]>res.json());

See these questions:

You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:

this.http.get('...')
    .map(res => {
      var data = res.json();
      return data.map(d => {
        return new Product(d.productNumber,
          d.productName, d.productDescription);
      });
    });

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

What is the question mark for in a Typescript parameter name

parameter?: type is a shorthand for parameter: type | undefined

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

React - changing an uncontrolled input

This generally happens only when you are not controlling the value of the filed when the application started and after some event or some function fired or the state changed, you are now trying to control the value in input field.

This transition of not having control over the input and then having control over it is what causes the issue to happen in the first place.

The best way to avoid this is by declaring some value for the input in the constructor of the component. So that the input element has value from the start of the application.

Send push to Android by C# using FCM (Firebase Cloud Messaging)

firebase cloud messaging with c#: working all .net platform (asp.net, .netmvc, .netcore)

        WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        tRequest.Method = "post";
        //serverKey - Key from Firebase cloud messaging server  
        tRequest.Headers.Add(string.Format("Authorization: key={0}", "AIXXXXXX...."));
        //Sender Id - From firebase project setting  
        tRequest.Headers.Add(string.Format("Sender: id={0}", "XXXXX.."));
        tRequest.ContentType = "application/json";
        var payload = new
        {
            to = "e8EHtMwqsZY:APA91bFUktufXdsDLdXXXXXX..........XXXXXXXXXXXXXX",
            priority = "high",
            content_available = true,
            notification = new
            {
                body = "Test",
                title = "Test",
                badge = 1
            },
            data = new 
            {
                key1 = "value1",
                key2 = "value2"
            }

        };

        string postbody = JsonConvert.SerializeObject(payload).ToString();
        Byte[] byteArray = Encoding.UTF8.GetBytes(postbody);
        tRequest.ContentLength = byteArray.Length;
        using (Stream dataStream = tRequest.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
            using (WebResponse tResponse = tRequest.GetResponse())
            {
                using (Stream dataStreamResponse = tResponse.GetResponseStream())
                {
                    if (dataStreamResponse != null) using (StreamReader tReader = new StreamReader(dataStreamResponse))
                        {
                            String sResponseFromServer = tReader.ReadToEnd();
                            //result.Response = sResponseFromServer;
                        }
                }
            }
        }

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.

I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

That usually happens when you call

onClick={this.handleButton()} - notice the () instead of:

onClick={this.handleButton} - notice here we are not calling the function when we initialize it

HTML5 event handling(onfocus and onfocusout) using angular 2

I've created a little directive that bind with the tabindex attribute. It adds/removes the has-focus class dynamically.

@Directive({
    selector: "[tabindex]"
})
export class TabindexDirective {
    constructor(private elementHost: ElementRef) {}

    @HostListener("focus")
    setInputFocus(): void {
        this.elementHost.nativeElement.classList.add("has-focus");
    }

    @HostListener("blur")
    setInputFocusOut(): void {
        this.elementHost.nativeElement.classList.remove("has-focus");
    }
}

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

Angular 2: Passing Data to Routes?

You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.

The old router allows to pass data but the new (RC.1) router doesn't yet.

Update

data was re-introduced in RC.4 How do I pass data in Angular 2 components while using Routing?

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How to get current value of RxJS Subject or Observable?

I had similar situation where late subscribers subscribe to the Subject after its value arrived.

I found ReplaySubject which is similar to BehaviorSubject works like a charm in this case. And here is a link to better explanation: http://reactivex.io/rxjs/manual/overview.html#replaysubject

How do I filter an array with TypeScript in Angular 2?

To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe

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

@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
  transform(itemList: any, searchKeyword: string) {
    if (!itemList)
      return [];
    if (!searchKeyword)
      return itemList;
    let filteredList = [];
    if (itemList.length > 0) {
      searchKeyword = searchKeyword.toLowerCase();
      itemList.forEach(item => {
        //Object.values(item) => gives the list of all the property values of the 'item' object
        let propValueList = Object.values(item);
        for(let i=0;i<propValueList.length;i++)
        {
          if (propValueList[i]) {
            if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
            {
              filteredList.push(item);
              break;
            }
          }
        }
      });
    }
    return filteredList;
  }
}

//Usage

//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>

Don't forget to import the pipe in the app module

We might need to customize the logic to filer with dates.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Just print out the embed after construction graph (ops) without running:

import tensorflow as tf

...

train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
    tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
print (embed)

This will show the shape of the embed tensor:

Tensor("embedding_lookup:0", shape=(128, 2, 64), dtype=float32)

Usually, it's good to check shapes of all tensors before training your models.

Angular 2 - View not updating after model changes

Instead of dealing with zones and change detection — let AsyncPipe handle complexity. This will put observable subscription, unsubscription (to prevent memory leaks) and changes detection on Angular shoulders.

Change your class to make an observable, that will emit results of new requests:

export class RecentDetectionComponent implements OnInit {

    recentDetections$: Observable<Array<RecentDetection>>;

    constructor(private recentDetectionService: RecentDetectionService) {
    }

    ngOnInit() {
        this.recentDetections$ = Observable.interval(5000)
            .exhaustMap(() => this.recentDetectionService.getJsonFromApi())
            .do(recent => console.log(recent[0].macAddress));
    }
}

And update your view to use AsyncPipe:

<tr *ngFor="let detected of recentDetections$ | async">
    ...
</tr>

Want to add, that it's better to make a service with a method that will take interval argument, and:

  • create new requests (by using exhaustMap like in code above);
  • handle requests errors;
  • stop browser from making new requests while offline.

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

With mysql Ver 14.14 Distrib 5.7.22 the update statement is now:

update user set authentication_string=password('1111') where user='root';

How do I pass data to Angular routed components?

One fine solution is to implement a Guard with canActivate method. In this scenario you can fetch data from a given api and let user access the component describe in the routing file. In the meantime one can set the data property of the route object and retrieve it in the component.

Let say you have this routing conf:

const routes: Routes = [
    { path: "/:projectName", component: ProjectComponent, canActivate: [ProjectGuard] }
]`

in your guard file you may have:

canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot)
: Observable<boolean> | Promise<boolean> | boolean {
return this.myProjectService.getProject(projectNameFoundElsewhere).pipe(
  map((project) => {
    if (project) {
      next.data = project;
    }
    return !!project;
  }),
);

}`

Then in your component

constructor(private route: ActivatedRoute) {
    this.route.data.subscribe((value) => (this.project = value));
}

This way is a bit different than passing via a service since service keep the value in a behaviorSubject as long as it is not unset. Passing via tha guard make the data available for the current route. I havent check if the children routes keep the data or not.

Resetting a form in Angular 2 after submit

I'm using reactive forms in angular 4 and this approach works for me:

    this.profileEditForm.reset(this.profileEditForm.value);

see reset the form flags in the Fundamentals doc

How to get current user in asp.net core

This is old question but my case shows that my case wasn't discussed here.

I like the most the answer of Simon_Weaver (https://stackoverflow.com/a/54411397/2903893). He explains in details how to get user name using IPrincipal and IIdentity. This answer is absolutely correct and I recommend to use this approach. However, during debugging I encountered with the problem when ASP.NET can NOT populate service principle properly. (or in other words, IPrincipal.Identity.Name is null)

It's obvious that to get user name MVC framework should take it from somewhere. In the .NET world, ASP.NET or ASP.NET Core is using Open ID Connect middleware. In the simple scenario web apps authenticate a user in a web browser. In this scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in response through the user’s browser, which contains claims about the user in a security token. To make it work in the code for your application, you'll need to provide the authority to which you web app delegates sign-in. When you deploy your web app to Azure Service the common scenario to meet this requirements is to configure web app: "App Services" -> YourApp -> "Authentication / Authorization" blade -> "App Service Authenticatio" = "On" and so on (https://github.com/Huachao/azure-content/blob/master/articles/app-service-api/app-service-api-authentication.md). I beliebe (this is my educated guess) that under the hood of this process the wizard adjusts "parent" web config of this web app by adding the same settings that I show in following paragraphs. Basically, the issue why this approach does NOT work in ASP.NET Core is because "parent" machine config is ignored by webconfig. (this is not 100% sure, I just give the best explanation that I have). So, to meke it work you need to setup this manually in your app.

Here is an article that explains how to manyally setup your app to use Azure AD. https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/aspnetcore2-2

Step 1: Register the sample with your Azure AD tenant. (it's obvious, don't want to spend my time of explanations).

Step 2: In the appsettings.json file: replace the ClientID value with the Application ID from the application you registered in Application Registration portal on Step 1. replace the TenantId value with common

Step 3: Open the Startup.cs file and in the ConfigureServices method, after the line containing .AddAzureAD insert the following code, which enables your application to sign in users with the Azure AD v2.0 endpoint, that is both Work and School and Microsoft Personal accounts.

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority = options.Authority + "/v2.0/";
    options.TokenValidationParameters.ValidateIssuer = false;
});

Summary: I've showed one more possible issue that could leed to an error that topic starter is explained. The reason of this issue is missing configurations for Azure AD (Open ID middleware). In order to solve this issue I propose manually setup "Authentication / Authorization". The short overview of how to setup this is added.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Here are the significant differences between lateinit var and by lazy { ... } delegated property:

  • lazy { ... } delegate can only be used for val properties, whereas lateinit can only be applied to vars, because it can't be compiled to a final field, thus no immutability can be guaranteed;

  • lateinit var has a backing field which stores the value, and by lazy { ... } creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use lateinit;

  • In addition to vals, lateinit cannot be used for nullable properties or Java primitive types (this is because of null used for uninitialized value);

  • lateinit var can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. by lazy { ... }, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

  • Initialization by lazy { ... } is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using another lazy overload). In the case of lateinit var, it's up to the user's code to initialize the property correctly in multi-threaded environments.

  • A Lazy instance can be saved, passed around and even used for multiple properties. On contrary, lateinit vars do not store any additional runtime state (only null in the field for uninitialized value).

  • If you hold a reference to an instance of Lazy, isInitialized() allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can use property::isInitialized since Kotlin 1.2.

  • A lambda passed to by lazy { ... } may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.

Also, there's another way not mentioned in the question: Delegates.notNull(), which is suitable for deferred initialization of non-null properties, including those of Java primitive types.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

How to extend / inherit components?

Alternative Solution:

This answer of Thierry Templier is an alternative way to get around the problem.

After some questions with Thierry Templier, I came to the following working example that meets my expectations as an alternative to inheritance limitation mentioned in this question:

1 - Create custom decorator:

export function CustomComponent(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

    var parentAnnotation = parentAnnotations[0];
    Object.keys(parentAnnotation).forEach(key => {
      if (isPresent(parentAnnotation[key])) {
        // verify is annotation typeof function
        if(typeof annotation[key] === 'function'){
          annotation[key] = annotation[key].call(this, parentAnnotation[key]);
        }else if(
        // force override in annotation base
        !isPresent(annotation[key])
        ){
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    var metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  }
}

2 - Base Component with @Component decorator:

@Component({
  // create seletor base for test override property
  selector: 'master',
  template: `
    <div>Test</div>
  `
})
export class AbstractComponent {

}

3 - Sub component with @CustomComponent decorator:

@CustomComponent({
  // override property annotation
  //selector: 'sub',
  selector: (parentSelector) => { return parentSelector + 'sub'}
})
export class SubComponent extends AbstractComponent {
  constructor() {
  }
}

Plunkr with complete example.

Toggle Class in React

Ori Drori's comment is correct, you aren't doing this the "React Way". In React, you should ideally not be changing classes and event handlers using the DOM. Do it in the render() method of your React components; in this case that would be the sideNav and your Header. A rough example of how this would be done in your code is as follows.

HEADER

class Header extends React.Component {
constructor(props){
    super(props);
}

render() {
    return (
        <div className="header">
            <i className="border hide-on-small-and-down"></i>
            <div className="container">
                <a ref="btn" href="#" className="btn-menu show-on-small"
                onClick=this.showNav><i></i></a>
                <Menu className="menu hide-on-small-and-down"/>
                <Sidenav ref="sideNav"/>
            </div>
        </div>
    )
}

showNav() {
  this.refs.sideNav.show();
}
}

SIDENAV

 class SideNav extends React.Component {
   constructor(props) {
     super(props);
     this.state = {
       open: false
     }
   }

   render() {
     if (this.state.open) {
       return ( 
         <div className = "sideNav">
            This is a sidenav 
         </div>
       )
     } else {
       return null;
     }

   }

   show() {
     this.setState({
       open: true
     })
   }
 }

You can see here that we are not toggling classes but using the state of the components to render the SideNav. This way, or similar is the whole premise of using react. If you are using bootstrap, there is a library which integrates bootstrap elements with the react way of doing things, allowing you to use the same elements but set state on them instead of directly manipulating the DOM. It can be found here - https://react-bootstrap.github.io/

Hope this helps, and enjoy using React!

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

How do I create a singleton service in Angular 2?

Just declare your service as provider in app.module.ts only.

It did the job for me.

providers: [Topic1Service,Topic2Service,...,TopicNService],

then either instanciate it using a constructor private parameter :

constructor(private topicService: TopicService) { }

or since if your service is used from html, the -prod option will claim:

Property 'topicService' is private and only accessible within class 'SomeComponent'.

add a member for your service and fill it with the instance recieved in the constructor:

export class SomeComponent {
  topicService: TopicService;
  constructor(private topicService: TopicService) { 
    this.topicService= topicService;
  }
}

Angular 2 execute script after template render

ngAfterViewInit() of AppComponent is a lifecycle callback Angular calls after the root component and it's children have been rendered and it should fit for your purpose.

See also https://angular.io/guide/lifecycle-hooks

ReactJS - Add custom event listener to component

If you need to handle DOM events not already provided by React you have to add DOM listeners after the component is mounted:

Update: Between React 13, 14, and 15 changes were made to the API that affect my answer. Below is the latest way using React 15 and ES7. See answer history for older versions.

class MovieItem extends React.Component {

  componentDidMount() {
    // When the component is mounted, add your DOM listener to the "nv" elem.
    // (The "nv" elem is assigned in the render function.)
    this.nv.addEventListener("nv-enter", this.handleNvEnter);
  }

  componentWillUnmount() {
    // Make sure to remove the DOM listener when the component is unmounted.
    this.nv.removeEventListener("nv-enter", this.handleNvEnter);
  }

  // Use a class arrow function (ES7) for the handler. In ES6 you could bind()
  // a handler in the constructor.
  handleNvEnter = (event) => {
    console.log("Nv Enter:", event);
  }

  render() {
    // Here we render a single <div> and toggle the "aria-nv-el-current" attribute
    // using the attribute spread operator. This way only a single <div>
    // is ever mounted and we don't have to worry about adding/removing
    // a DOM listener every time the current index changes. The attrs 
    // are "spread" onto the <div> in the render function: {...attrs}
    const attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};

    // Finally, render the div using a "ref" callback which assigns the mounted 
    // elem to a class property "nv" used to add the DOM listener to.
    return (
      <div ref={elem => this.nv = elem} aria-nv-el {...attrs} className="menu_item nv-default">
        ...
      </div>
    );
  }

}

Example on Codepen.io

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Getting reference to child component in parent component

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(Child) child:Child;

  (...)

  someOtherMethod() {
    this.searchBar.someMethod();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(Child) children:QueryList<Child>) {
    this.childcmp = children.first();
  }

  (...)
}

No 'Access-Control-Allow-Origin' header in Angular 2 app

this is server configuration, set up config.addAllowedHeader("*"); in the CorsConfiguration.

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

Do not write tests for private methods. This defeats the point of unit tests.

  • You should be testing the public API of your class
  • You should NOT be testing the implimentation details of your class

Example

class SomeClass {

  public addNumber(a: number, b: number) {
      return a + b;
  }
}

The test for this method should not need to change if later the implementation changes but the behaviour of the public API remains the same.

class SomeClass {

  public addNumber(a: number, b: number) {
      return this.add(a, b);
  }

  private add(a: number, b: number) {
       return a + b;
  }
}

Don't make methods and properties public just in order to test them. This usually means that either:

  1. You are trying to test implementation rather than API (public interface).
  2. You should move the logic in question into its own class to make testing easier.

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

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


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

TypeScript error: Type 'void' is not assignable to type 'boolean'

Your code is passing a function as an argument to find. That function takes an element argument (of type Conversation) and returns void (meaning there is no return value). TypeScript describes this as (element: Conversation) => void'

What TypeScript is saying is that the find function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations, a number and a Conversation array, and that this function should return a boolean.

So bottom line is that you either need to change your code to pass in the values to find correctly, or else you need to provide an overload to the definition of find in your definition file that accepts a Conversation and returns void.

Implementing autocomplete

I'd like to add something that no one has yet mentioned: ng2-input-autocomplete

NPM: https://www.npmjs.com/package/ng2-input-autocomplete

GitHub: https://github.com/liuy97/ng2-input-autocomplete#readme

Difference between Constructor and ngOnInit

Like a lot of other languages, you can initialize variables at the class level, the constructor, or a method. It is up to the developer to decide what is best in their particular case. But below are a list of best practices when it comes to deciding.

Class level variables

Usually, you will declare all your variables here that will be used in the rest of you component. You can initialize them if the value doesn't depend on anything else, or use const keyword to create constants if they will not change.

export class TestClass{
    let varA: string = "hello";
}

Constructor

Normally it's best practice to not do anything in the constructor and just use it for classes that will be injected. Most of the time your constructor should look like this:

   constructor(private http: Http, private customService: CustomService) {}

this will automatically create the class level variables, so you will have access to customService.myMethod() without having to do it manually.

NgOnInit

NgOnit is a lifecycle hook provided by the Angular 2 framework. Your component must implement OnInit in order to use it. This lifecycle hook gets called after the constructor is called and all the variables are initialized. The bulk of your initialization should go here. You will have the certainty that Angular has initialized your component correctly and you can start doing any logic you need in OnInit versus doing things when your component hasn't finished loading properly.

Here is an image detailing the order of what gets called:

enter image description here

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

TLDR

If you are using Angular 2 framework and need to interact with certain lifecycle events, use the methods provided by the framework for this to avoid problems.

HTML <select> selected option background-color CSS style

I realise this is an old post, but in case it helps, you can apply this CSS to have IE11 draw a dotted outline for the focus indication of a <select> element so that it resembles Firefox's focus indication: select:focus::-ms-value { background: transparent; color: inherit; outline-style: dotted; outline-width: thin; }

How to set table name in dynamic SQL query?

This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically

select @sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'

exec (@sql)

of course #tables is a dynamic table in the stored procedure

PHP 7 RC3: How to install missing MySQL PDO

Since eggyal didn't provided his comment as answer after he gave right advice in a comment - i am posting it here: In my case I had to install module php-mysql. See comments under the question for details.

MySQL Select all columns from one table and some from another table

select a.* , b.Aa , b.Ab, b.Ac from table1 a left join table2 b on a.id=b.id

this should select all columns from table 1 and only the listed columns from table 2 joined by id.

How to read the output from git diff?

The default output format (which originally comes from a program known as diff if you want to look for more info) is known as a “unified diff”. It contains essentially 4 different types of lines:

  • context lines, which start with a single space,
  • insertion lines that show a line that has been inserted, which start with a +,
  • deletion lines, which start with a -, and
  • metadata lines which describe higher level things like which file this is talking about, what options were used to generate the diff, whether the file changed its permissions, etc.

I advise that you practice reading diffs between two versions of a file where you know exactly what you changed. Like that you'll recognize just what is going on when you see it.

How To Use DateTimePicker In WPF?

There is no out of the box DateTime picker for WPF..

There are however a lot of third party DateTime pickers of course :)

http://www.devcomponents.com/dotnetbar-wpf/WPFDateTimePicker.aspx

http://marlongrech.wordpress.com/2007/09/11/wpf-datepicker/

http://www.codeplex.com/AvalonControlsLib

Just do a quick google to find more!

How to reset or change the passphrase for a GitHub SSH key?

If you had generate a SSH-key with passphrase and then you forget your passphrase for this SSH-key,there's no way to recover it, You'll need to generate a brand new SSH keypair or switch to HTTPS cloning so you can use your GitHub password instead.

BUT,there are exceptions

If you configured your SSH passphrase with the OS X Keychain, you may be able to recover it.

  1. In Finder, search for the Keychain Access app.
  2. In Keychain Access, search for SSH.
  3. Double click on the entry for your SSH key to open a new dialog box.
  4. Keychain access dialogIn the lower-left corner, select Show password.
  5. You'll be prompted for your administrative password. Type it into the "Keychain Access" dialog box.
  6. Your password will be revealed.

Refer to Github help - How do I recover my SSH key passphrase?

How can I trigger an onchange event manually?

There's a couple of ways you can do this. If the onchange listener is a function set via the element.onchange property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:

element.onchange();

If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
}
else
    element.fireEvent("onchange");

What is the easiest way to push an element to the beginning of the array?

What about using the unshift method?

ary.unshift(obj, ...) ? ary
Prepends objects to the front of self, moving other elements upwards.

And in use:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"

cannot import name patterns

As of Django 1.10, the patterns module has been removed (it had been deprecated since 1.8).

Luckily, it should be a simple edit to remove the offending code, since the urlpatterns should now be stored in a plain-old list:

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    # ... your url patterns
]

AngularJS + JQuery : How to get dynamic content working in angularjs

Another Solution in Case You Don't Have Control Over Dynamic Content

This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).

Wrap up Your Content

Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.

<div class="selector">
    <grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>

Use Angular Injector

You can use the following code to get a reference to $compile if you don't have one.

$(".selector").each(function () {
    var content = $(this);
    angular.element(document).injector().invoke(function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    });
});

Summary

The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.

One Caveat of the previous code

If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.

Here is the way to remedy it:

Replace the prevous code snippet with the following overload.

...
angular.element(document).injector().invoke(
[
    "$compile", function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    }
]);
...

This caused a lot of grief for me before I pieced it together.

Index of element in NumPy array

Use np.where to get the indices where a given condition is True.

Examples:

For a 2D np.ndarray called a:

i, j = np.where(a == value) # when comparing arrays of integers

i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays

For a 1D array:

i, = np.where(a == value) # integers

i, = np.where(np.isclose(a, value)) # floating-point

Note that this also works for conditions like >=, <=, != and so forth...

You can also create a subclass of np.ndarray with an index() method:

class myarray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        return np.array(*args, **kwargs).view(myarray)
    def index(self, value):
        return np.where(self == value)

Testing:

a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3,  4,  5,  8,  9, 10]),)

nodejs vs node on ubuntu 12.04

Late answer, but for up-to-date info...

If you install node.js using the recommend method from the node github installation readme, it suggests following the instructions on the nodesource blog article, rather than installing from the out of date apt-get repo, node.js should run using the node command, as well as the nodejs command, without having to make a new symlink.

This method from article is:

# Note the new setup script name for Node.js v0.12
curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -

# Then install with:
sudo apt-get install -y nodejs

Note that this is for v0.12, which will get likely become outdated in the not to distant future.

Also, if you're behind a corporate proxy (like me) you'll want to add the -E option to the sudo command, to preserve the env vars required for the proxy:

curl -sL https://deb.nodesource.com/setup_0.12 | sudo -E bash -

How to Free Inode Usage?

If you use docker, remove all images. They used many space....

Stop all containers

docker stop $(docker ps -a -q)

Delete all containers

docker rm $(docker ps -a -q)

Delete all images

docker rmi $(docker images -q)

Works to me

Is it possible to have multiple styles inside a TextView?

Using an auxiliary Spannable Class as Android String Resources shares at the bottom of the webpage. You can approach this by creatingCharSquences and giving them a style.

But in the example they give us, is just for bold, italic, and even colorize text. I needed to wrap several styles in aCharSequence in order to set them in a TextView. So to that Class (I named it CharSequenceStyles) I just added this function.

public static CharSequence applyGroup(LinkedList<CharSequence> content){
    SpannableStringBuilder text = new SpannableStringBuilder();
    for (CharSequence item : content) {
        text.append(item);
    }
    return text;
}

And in the view I added this.

            message.push(postMessageText);
            message.push(limitDebtAmount);
            message.push(pretMessageText);
            TextView.setText(CharSequenceStyles.applyGroup(message));

I hope this help you!

How can I display a tooltip message on hover using jQuery?

As recommended qTip and other projects are quite old I recommend using qTip2 as it is most up-to-date.

Can't push to remote branch, cannot be resolved to branch

You might have created similar branch but different case-sensitive-wise, then you have to run:

git branch -D <name-of-different-case-branch>

and then try to push again.

Where is shared_ptr?

There are at least three places where you may find shared_ptr:

  1. If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.

  2. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.

  3. Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.

SVN how to resolve new tree conflicts when file is added on two branches

I found a post suggesting a solution for that. It's about to run:

svn resolve --accept working <YourPath>

which will claim the local version files as OK.
You can run it for single file or entire project catalogues.

How to split a comma-separated value to columns

We can create a function as this

CREATE Function [dbo].[fn_CSVToTable] 
(
    @CSVList Varchar(max)
)
RETURNS @Table TABLE (ColumnData VARCHAR(100))
AS
BEGIN
    IF RIGHT(@CSVList, 1) <> ','
    SELECT @CSVList = @CSVList + ','

    DECLARE @Pos    BIGINT,
            @OldPos BIGINT
    SELECT  @Pos    = 1,
            @OldPos = 1

    WHILE   @Pos < LEN(@CSVList)
        BEGIN
            SELECT  @Pos = CHARINDEX(',', @CSVList, @OldPos)
            INSERT INTO @Table
            SELECT  LTRIM(RTRIM(SUBSTRING(@CSVList, @OldPos, @Pos - @OldPos))) Col001

            SELECT  @OldPos = @Pos + 1
        END

    RETURN
END

We can then seperate the CSV values into our respective columns using a SELECT statement

Making PHP var_dump() values display one line per value

Use output buffers: http://php.net/manual/de/function.ob-start.php

<?php
    ob_start();
    var_dump($_SERVER) ;
    $dump = ob_get_contents();
    ob_end_clean();

    echo "<pre> $dump </pre>";
?>

Yet another option would be to use Output buffering and convert all the newlines in the dump to <br> elements, e.g.

ob_start();
var_dump($_SERVER) ;
echo nl2br(ob_get_clean());

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

This is an old question but since this is the first result in google for this error, I thought I would update my progress in this issue.

I spent way too may hours on this issue. In the end I had to change my Office 365 account's password few times until my code succeeded in sending emails.

Didn't have to make any changes in code.

error: invalid type argument of ‘unary *’ (have ‘int’)

Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;. Finally, you declared c incorrectly. Since you assign it to be the address of a, where a is a pointer to int, you must declare it to be a pointer to a pointer to int.

#include <stdio.h>
int main(void)
{
    int b=10;
    int *a=&b;
    int **c=&a;
    printf("%d", **c);
    return 0;
} 

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Well, I can think of a CSS hack that will resolve this issue.

You could add the following line in your CSS file:

* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; } 

The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

How to completely remove borders from HTML table

This is what resolved the problem for me:

In your HTML tr tag, add this:

style="border-collapse: collapse; border: none;"

That removed all the borders that were showing on the table row.

git: patch does not apply

This command will apply the patch not resolving it leaving bad files as *.rej:

git apply --reject --whitespace=fix mypath.patch

You just have to resolve them. Once resolved run:

git -am resolved

Creating a new ArrayList in Java

Material please go through this Link And also try this

 ArrayList<Class> myArray= new ArrayList<Class>();

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

How do I schedule jobs in Jenkins?

By setting the schedule period to 15 13 * * * you tell Jenkins to schedule the build every day of every month of every year at the 15th minute of the 13th hour of the day.

Jenkins used a cron expression, and the different fields are:

  1. MINUTES Minutes in one hour (0-59)
  2. HOURS Hours in one day (0-23)
  3. DAYMONTH Day in a month (1-31)
  4. MONTH Month in a year (1-12)
  5. DAYWEEK Day of the week (0-7) where 0 and 7 are sunday

If you want to schedule your build every 5 minutes, this will do the job : */5 * * * *

If you want to schedule your build every day at 8h00, this will do the job : 0 8 * * *

For the past few versions (2014), Jenkins have a new parameter, H (extract from the Jenkins code documentation):

To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible.

For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.

Note also that:

The H symbol can be thought of as a random value over a range, but it actually is a hash of the job name, not a random function, so that the value remains stable for any given project.

More example of using 'H'

How do I find an array item with TypeScript? (a modern, easier way)

Part One - Polyfill

For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Part Two - Interface

You need to extend the open Array interface to include the find method.

interface Array<T> {
    find(predicate: (search: T) => boolean) : T;
}

When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

Part Three - Use it

The variable x will have the expected type... { id: number }

var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);

How to configure Docker port mapping to use Nginx as an upstream proxy?

@gdbj's answer is a great explanation and the most up to date answer. Here's however a simpler approach.

So if you want to redirect all traffic from nginx listening to 80 to another container exposing 8080, minimum configuration can be as little as:

nginx.conf:

server {
    listen 80;

    location / {
        proxy_pass http://client:8080; # this one here
        proxy_redirect off;
    }

}

docker-compose.yml

version: "2"
services:
  entrypoint:
    image: some-image-with-nginx
    ports:
      - "80:80"
    links:
      - client  # will use this one here

  client:
    image: some-image-with-api
    ports:
      - "8080:8080"

Docker docs

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

No, you cannot do that with CSS. That is the reason Microsoft initially introduced another, and maybe more practical box model. The box model that eventually won, makes it inpractical to mix percentages and units.

I don't think it is OK with you to express padding and border widths in percentage of the parent too.

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Ignore <br> with CSS?

As per your question, to solve this problem for Firefox and Opera using Aneesh Karthik C approach you need to add "float" right" attribute.

Check the example here. This CSS works in Firefox (26.0) , Opera (12.15), Chrome (32.0.1700) and Safari (7.0)

br {
   content: " ";  
   float:right; 
}

I hope this will answer your question!!

Get average color of image via Javascript

AFAIK, the only way to do this is with <canvas/>...

DEMO V2: http://jsfiddle.net/xLF38/818/

Note, this will only work with images on the same domain and in browsers that support HTML5 canvas:

function getAverageRGB(imgEl) {

    var blockSize = 5, // only visit every 5 pixels
        defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
        canvas = document.createElement('canvas'),
        context = canvas.getContext && canvas.getContext('2d'),
        data, width, height,
        i = -4,
        length,
        rgb = {r:0,g:0,b:0},
        count = 0;

    if (!context) {
        return defaultRGB;
    }

    height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
    width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;

    context.drawImage(imgEl, 0, 0);

    try {
        data = context.getImageData(0, 0, width, height);
    } catch(e) {
        /* security error, img on diff domain */
        return defaultRGB;
    }

    length = data.data.length;

    while ( (i += blockSize * 4) < length ) {
        ++count;
        rgb.r += data.data[i];
        rgb.g += data.data[i+1];
        rgb.b += data.data[i+2];
    }

    // ~~ used to floor values
    rgb.r = ~~(rgb.r/count);
    rgb.g = ~~(rgb.g/count);
    rgb.b = ~~(rgb.b/count);

    return rgb;

}

For IE, check out excanvas.

How to write a confusion matrix in Python?

Scikit-Learn provides a confusion_matrix function

from sklearn.metrics import confusion_matrix
y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
confusion_matrix(y_actu, y_pred)

which output a Numpy array

array([[3, 0, 0],
       [0, 1, 2],
       [2, 1, 3]])

But you can also create a confusion matrix using Pandas:

import pandas as pd
y_actu = pd.Series([2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2], name='Actual')
y_pred = pd.Series([0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2], name='Predicted')
df_confusion = pd.crosstab(y_actu, y_pred)

You will get a (nicely labeled) Pandas DataFrame:

Predicted  0  1  2
Actual
0          3  0  0
1          0  1  2
2          2  1  3

If you add margins=True like

df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)

you will get also sum for each row and column:

Predicted  0  1  2  All
Actual
0          3  0  0    3
1          0  1  2    3
2          2  1  3    6
All        5  2  5   12

You can also get a normalized confusion matrix using:

df_conf_norm = df_confusion / df_confusion.sum(axis=1)

Predicted         0         1         2
Actual
0          1.000000  0.000000  0.000000
1          0.000000  0.333333  0.333333
2          0.666667  0.333333  0.500000

You can plot this confusion_matrix using

import matplotlib.pyplot as plt
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)

plot_confusion_matrix(df_confusion)

plot confusion matrix

Or plot normalized confusion matrix using:

plot_confusion_matrix(df_conf_norm)  

plot confusion matrix normalized

You might also be interested by this project https://github.com/pandas-ml/pandas-ml and its Pip package https://pypi.python.org/pypi/pandas_ml

With this package confusion matrix can be pretty-printed, plot. You can binarize a confusion matrix, get class statistics such as TP, TN, FP, FN, ACC, TPR, FPR, FNR, TNR (SPC), LR+, LR-, DOR, PPV, FDR, FOR, NPV and some overall statistics

In [1]: from pandas_ml import ConfusionMatrix
In [2]: y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
In [3]: y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
In [4]: cm = ConfusionMatrix(y_actu, y_pred)
In [5]: cm.print_stats()
Confusion Matrix:

Predicted  0  1  2  __all__
Actual
0          3  0  0        3
1          0  1  2        3
2          2  1  3        6
__all__    5  2  5       12


Overall Statistics:

Accuracy: 0.583333333333
95% CI: (0.27666968568210581, 0.84834777019156982)
No Information Rate: ToDo
P-Value [Acc > NIR]: 0.189264302376
Kappa: 0.354838709677
Mcnemar's Test P-Value: ToDo


Class Statistics:

Classes                                        0          1          2
Population                                    12         12         12
P: Condition positive                          3          3          6
N: Condition negative                          9          9          6
Test outcome positive                          5          2          5
Test outcome negative                          7         10          7
TP: True Positive                              3          1          3
TN: True Negative                              7          8          4
FP: False Positive                             2          1          2
FN: False Negative                             0          2          3
TPR: (Sensitivity, hit rate, recall)           1  0.3333333        0.5
TNR=SPC: (Specificity)                 0.7777778  0.8888889  0.6666667
PPV: Pos Pred Value (Precision)              0.6        0.5        0.6
NPV: Neg Pred Value                            1        0.8  0.5714286
FPR: False-out                         0.2222222  0.1111111  0.3333333
FDR: False Discovery Rate                    0.4        0.5        0.4
FNR: Miss Rate                                 0  0.6666667        0.5
ACC: Accuracy                          0.8333333       0.75  0.5833333
F1 score                                    0.75        0.4  0.5454545
MCC: Matthews correlation coefficient  0.6831301  0.2581989  0.1690309
Informedness                           0.7777778  0.2222222  0.1666667
Markedness                                   0.6        0.3  0.1714286
Prevalence                                  0.25       0.25        0.5
LR+: Positive likelihood ratio               4.5          3        1.5
LR-: Negative likelihood ratio                 0       0.75       0.75
DOR: Diagnostic odds ratio                   inf          4          2
FOR: False omission rate                       0        0.2  0.4285714

I noticed that a new Python library about Confusion Matrix named PyCM is out: maybe you can have a look.

What is the difference between "INNER JOIN" and "OUTER JOIN"?

There are major mainly 2 types of JOINs in SQL: [INNER and OUTER]


Examples

Suppose you have two tables, with a single column each, and data as follows:

A    B
-    -
1    3
2    4
3    5
4    6
7
8

Note that (1,2,7,8) are unique to A, (3,4) are common, and (5,6) are unique to B.



  • (INNER) JOIN:

The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same.

INNER JOIN

select * from a INNER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b;

Result:

a | b
--+--
3 | 3
4 | 4


  • LEFT (OUTER) JOIN:

This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of the join. The rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

LEFT JOIN / LEFT OUTER JOIN

select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b(+);

Result:

a |  b
--+-----
1 | null
2 | null
3 |    3
4 |    4
7 | null
8 | null


  • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table

RIGHT JOIN / RIGHT OUTER JOIN

select * from a RIGHT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a(+) = b.b;

Result:

a    |  b
-----+----
3    |  3
4    |  4
null |  5
null |  6


  • FULL (OUTER) JOIN:

    FULL JOIN creates the result-set by combining the result of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which there is no matching, the result-set will contain NULL values.

FULL JOIN / FULL OUTER JOIN

select * from a FULL OUTER JOIN b on a.a = b.b;

Result:

 a   |  b
-----+-----
   1 | null
   2 | null
   3 |    3
   4 |    4
null |    6
null |    5
   7 | null
   8 | null

Test if a vector contains a given element

is.element() makes for more readable code, and is identical to %in%

v <- c('a','b','c','e')

is.element('b', v)
'b' %in% v
## both return TRUE

is.element('f', v)
'f' %in% v
## both return FALSE

subv <- c('a', 'f')
subv %in% v
## returns a vector TRUE FALSE
is.element(subv, v)
## returns a vector TRUE FALSE

Set a div width, align div center and text align left

Use auto margins.

div {
   margin-left: auto;
   margin-right: auto;
   width: NNNpx;

   /* NOTE: Only works for non-floated block elements */
   display: block;
   float: none;
}

Further reading at SimpleBits CSS Centering 101

What is the difference between the | and || or operators?

The singe pipe "|" is the "bitwise" or and should only be used when you know what you're doing. The double pipe "||" is a logical or, and can be used in logical statements, like "x == 0 || x == 1".

Here's an example of what the bitwise or does: if a=0101 and b=0011, then a|b=0111. If you're dealing with a logic system that treats any non-zero as true, then the bitwise or will act in the same way as the logical or, but it's counterpart (bitwise and, "&") will NOT. Also the bitwise or does not perform short circuit evaluation.

JSON.net: how to deserialize without using the default constructor?

Solution:

public Response Get(string jsonData) {
    var json = JsonConvert.DeserializeObject<modelname>(jsonData);
    var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
    return data;
}

Model:

public class modelname {
    public long parameter{ get; set; }
    public int parameter{ get; set; }
    public int parameter{ get; set; }
    public string parameter{ get; set; }
}

How to get the PID of a process by giving the process name in Mac OS X ?

This solution matches the process name more strictly:

ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'

This solution has the following advantages:

  • it ignores command line arguments like tail -f ~/Dropbox
  • it ignores processes inside a directory like ~/Dropbox/foo.sh
  • it ignores processes with names like ~/DropboxUID.sh

Very simple log4j2 XML configuration file using Console and File appender

log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.

Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.

Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
    <Properties>
        <Property name="filename">log/CelsiusConverter.log</Property>
    </Properties>
    <Appenders>
        <Appender type="Console" name="Console">
            <Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
        </Appender>
        <Appender type="Console" name="FLOW">
            <Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
        </Appender>
        <Appender type="File" name="File" fileName="${filename}">
            <Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
        </Appender>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="File" />
            <AppenderRef ref="Console" />
            <!-- Use FLOW to trace down exact method sending the msg -->
            <!-- <AppenderRef ref="FLOW" /> -->
        </Root>
    </Loggers>
</Configuration>

"unexpected token import" in Nodejs5 and babel?

babel-preset-es2015 is now deprecated and you'll get a warning if you try to use Laurence's solution.

To get this working with Babel 6.24.1+, use babel-preset-env instead:

npm install babel-preset-env --save-dev

Then add env to your presets in your .babelrc:

{
  "presets": ["env"]
}

See the Babel docs for more info.

Mean filter for smoothing images in Matlab

I = imread('peppers.png');
H = fspecial('average', [5 5]);
I = imfilter(I, H);
imshow(I)

Note that filters can be applied to intensity images (2D matrices) using filter2, while on multi-dimensional images (RGB images or 3D matrices) imfilter is used.

Also on Intel processors, imfilter can use the Intel Integrated Performance Primitives (IPP) library to accelerate execution.

Splitting a dataframe string column into multiple different columns

Is this what you are trying to do?

# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)

#  Split into individual elements by the '.' character
#  Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )

#  We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )

#  Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
#  V1 V2  V3  V4
#1  F US CLE V13
#2  F US CA6 U13
#3  F US CA6 U13
#4  F US CA6 U13
#5  F US CA6 U13
#6  F US CA6 U13

Could not extract response: no suitable HttpMessageConverter found for response type

public class Application {

    private static List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        return converters;
    }   

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.setMessageConverters(getMessageConverters());
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        //Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);

        ResponseEntity<Page> response = 
                  restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
        Page page = response.getBody();
        System.out.println("Name:    " + page.getId());
        System.out.println("About:   " + page.getFirst_name());
        System.out.println("Phone:   " + page.getLast_name());
        System.out.println("Website: " + page.getMiddle_name());
        System.out.println("Website: " + page.getName());
    }
}

How do I make a text input non-editable?

Add readonly:

<input type="text" value="3" class="field left" readonly>

If you want the value to be not submitted in a form, instead add the disabled attribute.

<input type="text" value="3" class="field left" disabled>

There is no way to use CSS that always works to do this.

Why? CSS can't "disable" anything. You can still turn off display or visibility and use pointer-events: none but pointer-events doesn't work on versions of IE that came out earlier than IE 11.

How do I replace text in a selection?

You can use ctrl+F to find the text.
ctrl+h to enter the replacement text. Then ctrl+shift+h to replace the current selected text and move to next matched text.

This is for windows. But you can check in mac also for which you might want to check the key bindings under Preferences.

Difference in Months between two dates in JavaScript

Sometimes you may want to get just the quantity of the months between two dates totally ignoring the day part. So for instance, if you had two dates- 2013/06/21 and 2013/10/18- and you only cared about the 2013/06 and 2013/10 parts, here are the scenarios and possible solutions:

var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths; 

1.If you want just the number of the months between the two dates excluding both month1 and month2

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;

2.If you want to include either of the months

numberOfMonths = (year2 - year1) * 12 + (month2 - month1);

3.If you want to include both of the months

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;

Map over object preserving keys

_.map using lodash like loop to achieve this

 var result={};
_.map({one: 1, two: 2, three: 3}, function(num, key){ result[key]=num * 3; });
console.log(result)

//output
{one: 1, two: 2, three: 3}

Reduce is clever looks like above answare

_.reduce({one: 1, two: 2, three: 3}, function(result, num, key) {
  result[key]=num * 3
  return result;
}, {});

//output
{one: 1, two: 2, three: 3}

What is the difference between a Docker image and a container?

An image is the blueprint from which container/s (running instances) are build.

How to change menu item text dynamically in Android

For people that need the title set statically. This can be done in the AndroidManifest.xml

<activity
    android:name=".ActivityName"
    android:label="Title Text" >
</activity>

Options Menu Title Text

Best way to randomize an array with .NET

Generate an array of random floats or ints of the same length. Sort that array, and do corresponding swaps on your target array.

This yields a truly independent sort.

Angular Directive refresh on parameter change

Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch to watch a model variable.

This watch needs to be setup in the link function.

If you use isolated scope for directive then the scope would be

scope :{typeId:'@' }

In your link function then you add a watch like

link: function(scope, element, attrs) {
    scope.$watch("typeId",function(newValue,oldValue) {
        //This gets called when data changes.
    });
 }

If you are not using isolated scope use watch on some_prop

Using Git with Visual Studio

I use Git with Visual Studio for my port of Protocol Buffers to C#. I don't use the GUI - I just keep a command line open as well as Visual Studio.

For the most part it's fine - the only problem is when you want to rename a file. Both Git and Visual Studio would rather that they were the one to rename it. I think that renaming it in Visual Studio is the way to go though - just be careful what you do at the Git side afterwards. Although this has been a bit of a pain in the past, I've heard that it actually should be pretty seamless on the Git side, because it can notice that the contents will be mostly the same. (Not entirely the same, usually - you tend to rename a file when you're renaming the class, IME.)

But basically - yes, it works fine. I'm a Git newbie, but I can get it to do everything I need it to. Make sure you have a git ignore file for bin and obj, and *.user.

SQLAlchemy: print the actual query

This works in python 2 and 3 and is a bit cleaner than before, but requires SA>=1.0.

from sqlalchemy.engine.default import DefaultDialect
from sqlalchemy.sql.sqltypes import String, DateTime, NullType

# python2/3 compatible.
PY3 = str is not bytes
text = str if PY3 else unicode
int_type = int if PY3 else (int, long)
str_type = str if PY3 else (str, unicode)


class StringLiteral(String):
    """Teach SA how to literalize various things."""
    def literal_processor(self, dialect):
        super_processor = super(StringLiteral, self).literal_processor(dialect)

        def process(value):
            if isinstance(value, int_type):
                return text(value)
            if not isinstance(value, str_type):
                value = text(value)
            result = super_processor(value)
            if isinstance(result, bytes):
                result = result.decode(dialect.encoding)
            return result
        return process


class LiteralDialect(DefaultDialect):
    colspecs = {
        # prevent various encoding explosions
        String: StringLiteral,
        # teach SA about how to literalize a datetime
        DateTime: StringLiteral,
        # don't format py2 long integers to NULL
        NullType: StringLiteral,
    }


def literalquery(statement):
    """NOTE: This is entirely insecure. DO NOT execute the resulting strings."""
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        statement = statement.statement
    return statement.compile(
        dialect=LiteralDialect(),
        compile_kwargs={'literal_binds': True},
    ).string

Demo:

# coding: UTF-8
from datetime import datetime
from decimal import Decimal

from literalquery import literalquery


def test():
    from sqlalchemy.sql import table, column, select

    mytable = table('mytable', column('mycol'))
    values = (
        5,
        u'snowman: ?',
        b'UTF-8 snowman: \xe2\x98\x83',
        datetime.now(),
        Decimal('3.14159'),
        10 ** 20,  # a long integer
    )

    statement = select([mytable]).where(mytable.c.mycol.in_(values)).limit(1)
    print(literalquery(statement))


if __name__ == '__main__':
    test()

Gives this output: (tested in python 2.7 and 3.4)

SELECT mytable.mycol
FROM mytable
WHERE mytable.mycol IN (5, 'snowman: ?', 'UTF-8 snowman: ?',
      '2015-06-24 18:09:29.042517', 3.14159, 100000000000000000000)
 LIMIT 1

Count number of 1's in binary representation

In python or any other convert to bin string then split it with '0' to get rid of 0's then combine and get the length.

len(''.join(str(bin(122011)).split('0')))-1

How to set text color in submit button?

you try this:

<input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: teal; background-color: #FFFFC0; border: 3pt ridge lightgrey" value=" Send Me! ">

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

At least 8 = {8,}:

str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)

Python 3 turn range to a list

You can just construct a list from the range object:

my_list = list(range(1, 1001))

This is how you do it with generators in python2.x as well. Typically speaking, you probably don't need a list though since you can come by the value of my_list[i] more efficiently (i + 1), and if you just need to iterate over it, you can just fall back on range.

Also note that on python2.x, xrange is still indexable1. This means that range on python3.x also has the same property2

1print xrange(30)[12] works for python2.x

2The analogous statement to 1 in python3.x is print(range(30)[12]) and that works also.

How to export a CSV to Excel using Powershell

This topic really helped me, so I'd like to share my improvements. All credits go to the nixda, this is based on his answer.

For those who need to convert multiple csv's in a folder, just modify the directory. Outputfilenames will be identical to input, just with another extension.

Take care of the cleanup in the end, if you like to keep the original csv's you might not want to remove these.

Can be easily modifed to save the xlsx in another directory.

$workingdir = "C:\data\*.csv"
$csv = dir -path $workingdir
foreach($inputCSV in $csv){
$outputXLSX = $inputCSV.DirectoryName + "\" + $inputCSV.Basename + ".xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
### $Excel.Application.International(3) = ,
### $Excel.Application.International(5) = ;
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

### Execute & delete the import query
$query.Refresh()
$query.Delete()

### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
}
## To exclude an item, use the '-exclude' parameter (wildcards if needed)
remove-item -path $workingdir -exclude *Crab4dq.csv

Conditionally ignoring tests in JUnit 4

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

SQL WHERE condition is not equal to?

I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:

 AND (isdelete is NULL or isdelete = 0)

Python read next()

Using next or readlines etc, is not necessary. As the documentation says: "For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code".

Here's an example:

with open('/path/to/file') as myfile:
    for line in myfile:
        print(line)

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

Comparing two strings in C?

The name of the array indicates the starting address. Starting address of both namet2 and nameIt2 are different. So the equal to (==) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp(), or we can compare character by character using a loop.

Android TextView padding between lines

If you want padding between text try LineSpacingExtra="10dp"

<TextView
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:lineSpacingExtra="10dp"/>

Git merge two local branches

The answer from the Abiraman was absolutely correct. However, for newbies to git, they might forget to pull the repository. Whenever you want to do a merge from branchB into branchA. First checkout and take pull from branchB (Make sure that, your branch is updated with remote branch)

git checkout branchB
git pull

Now you local branchB is updated with remote branchB Now you can checkout to branchA

git checkout branchA

Now you are in branchA, then you can merge with branchB using following command

git merge branchB

SQL how to increase or decrease one for a int column in one command

@dotjoe It is cheaper to update and check @@rowcount, do an insert after then fact.

Exceptions are expensive && updates are more frequent

Suggestion: If you want to be uber performant in your DAL, make the front end pass in a unique ID for the row to be updated, if null insert.

The DALs should be CRUD, and not need to worry about being stateless.

If you make it stateless, With good indexes, you will not see a diff with the following SQL vs 1 statement. IF (select top 1 * form x where PK=@ID) Insert else update

Delete file from internal storage

The getFilesDir() somehow didn't work. Using a method, which returns the entire path and filename gave the desired result. Here is the code:

File file = new File(inputHandle.getImgPath(id));
boolean deleted = file.delete();

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

In my instance, the name of the connectionString in the web.config file was spelled wrong. This is the name of the database context Entity Framework uses. I guess this is the error you get when EF can't match up the connectionString name with the context.

How to delete a file from SD card?

This worked for me.

String myFile = "/Name Folder/File.jpg";  

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(my_Path);
Boolean deleted = f.delete();

How to send a JSON object using html form data

You can try something like:

<html>
<head>
    <title>test</title>
</head>

<body>
    <form id="formElem">
        <input type="text" name="firstname" value="Karam">
        <input type="text" name="lastname" value="Yousef">
        <input type="submit">
    </form>
    <div id="decoded"></div>
    <button id="encode">Encode</button>
    <div id="encoded"></div>
</body>
<script>
    encode.onclick = async (e) => {
        let response = await fetch('http://localhost:8482/encode', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
        })

        let text = await response.text(); // read response body as text
        data = JSON.parse(text);
        document.querySelector("#encoded").innerHTML = text;
      //  document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/> 
      //                                                  Last name = ${data.lastname} <br/>
      //                                                  Age    = ${data.age}`
    };

    formElem.onsubmit = async (e) => {
      e.preventDefault();
      var form = document.querySelector("#formElem");
     // var form = document.forms[0];

        data = {
          firstname : form.querySelector('input[name="firstname"]').value,
          lastname : form.querySelector('input[name="lastname"]').value,
          age : 5
        }

        let response = await fetch('http://localhost:8482/decode', {
                method: 'POST', // or 'PUT'
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
        })

        let text = await response.text(); // read response body as text
        document.querySelector("#decoded").innerHTML = text;
    };
</script>
</html>

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

Keeping ASP.NET Session Open / Alive

I use JQuery to perform a simple AJAX call to a dummy HTTP Handler that does nothing but keeping my Session alive:

function setHeartbeat() {
    setTimeout("heartbeat()", 5*60*1000); // every 5 min
}

function heartbeat() {
    $.get(
        "/SessionHeartbeat.ashx",
        null,
        function(data) {
            //$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)
            setHeartbeat();
        },
        "json"
    );
}

Session handler can be as simple as:

public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest(HttpContext context)
    {
        context.Session["Heartbeat"] = DateTime.Now;
    }
}

The key is to add IRequiresSessionState, otherwise Session won't be available (= null). The handler can of course also return a JSON serialized object if some data should be returned to the calling JavaScript.

Made available through web.config:

<httpHandlers>
    <add verb="GET,HEAD" path="SessionHeartbeat.ashx" validate="false" type="SessionHeartbeatHttpHandler"/>
</httpHandlers>

added from balexandre on August 14th, 2012

I liked so much of this example, that I want to improve with the HTML/CSS and the beat part

change this

//$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)

into

beatHeart(2); // just a little "red flash" in the corner :)

and add

// beat the heart 
// 'times' (int): nr of times to beat
function beatHeart(times) {
    var interval = setInterval(function () {
        $(".heartbeat").fadeIn(500, function () {
            $(".heartbeat").fadeOut(500);
        });
    }, 1000); // beat every second

    // after n times, let's clear the interval (adding 100ms of safe gap)
    setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100);
}

HTML and CSS

<div class="heartbeat">&hearts;</div>

/* HEARBEAT */
.heartbeat {
    position: absolute;
    display: none;
    margin: 5px;
    color: red;
    right: 0;
    top: 0;
}

here is a live example for only the beating part: http://jsbin.com/ibagob/1/

CakePHP find method with JOIN

Otro example, custom Data Pagination for JOIN

CODE in Controller CakePHP 2.6 is OK:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        'conditions'=>array(
            'Clientes.requiere_senasa'=>1
        ),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

OR Example 2, NOT active conditions:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id',
                    'Clientes.requiere_senasa = 1'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        //'conditions'=>array(
        //    'Clientes.requiere_senasa'=>1
        //),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

How do you get the Git repository's name in some Git repository?

Unfortunately, it seems that Git has no such command built in. But you can easily add it yourself with Git aliases and some shell magic.

As pointed out by this answer, you can use git rev-parse --show-toplevel to show the root of your current Git folder.

If you want to use this regularly, it's probably more convenient to define it as an alias. For this, used git config alias.root '!echo "$(git rev-parse --show-toplevel)"'. After this, you can use git root to see the root folder of the repository you're currently in.

If you want to use another subcommand name than root, simply replace the second part of alias.root in the above command with whatever you want.

For details on aliases in Git, see also the git config man page.

How to create User/Database in script for Docker Postgres

EDIT - since Jul 23, 2015

The official postgres docker image will run .sql scripts found in the /docker-entrypoint-initdb.d/ folder.

So all you need is to create the following sql script:

init.sql

CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;

and add it in your Dockerfile:

Dockerfile

FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/

But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB environment variables:

docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres

or with a Dockerfile:

FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

for images older than Jul 23, 2015

From the documentation of the postgres Docker image, it is said that

[...] it will source any *.sh script found in that directory [/docker-entrypoint-initdb.d] to do further initialization before starting the service

What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".

After that there is another useful piece of information:

If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.

Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:

NOTE, this has changed recently in the following commit. This will work with the latest change:

export PGUSER=postgres
psql <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Previously, the use of --single mode was required:

gosu postgres postgres --single <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

JQuery .on() method with multiple event handlers to one selector

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});

What is the difference between 'java', 'javaw', and 'javaws'?

I have checked that the output redirection works with javaw:

javaw -cp ... mypath.MyClass ... arguments 1>log.txt 2>err.txt

It means, if the Java application prints out anything via System.out or System.err, it is written to those files, as also with using java (without w). Especially on starting java, the JRE may write starting errors (class not found) on the error output pipe. In this respect, it is essential to know about errors. I suggest to use the console redirection in any case if javaw is invoked.

In opposite if you use

start java .... 1>log.txt 2>err.txt

With the Windows console start command, the console output redirection does not work with java nor with javaw.

Explanation why it is so: I think that javaw opens an internal process in the OS (adequate using the java.lang.Process class), and transfers a known output redirection to this process. If no redirection is given on the command line, nothing is redirected and the internal started process for javaw doesn't have any console outputs. The behavior for java.lang.Process is similar. The virtual machine may use this internal feature for javaw too.

If you use 'start', the Windows console creates a new process for Windows to execute the command after start, but this mechanism does not use a given redirection for the started sub process, unfortunately.

How do I update a GitHub forked repository?

How to update your forked repo on your local machine?

First, check your remote/master

git remote -v

You should have origin and upstream. For example:

origin  https://github.com/your___name/kredis.git (fetch)
origin  https://github.com/your___name/kredis.git (push)
upstream    https://github.com/rails/kredis.git (fetch)
upstream    https://github.com/rails/kredis.git (push)

After that go to main:

git checkout main

and merge from upstream to main:

git merge upstream/main

./configure : /bin/sh^M : bad interpreter

Or if you want to do this with a script:

sed -i 's/\r//' filename

Why doesn't JavaScript support multithreading?

Multi-threading with javascript is clearly possible using webworkers bring by HTML5.

Main difference between webworkers and a standard multi-threading environment is memory resources are not shared with the main thread, a reference to an object is not visible from one thread to another. Threads communicate by exchanging messages, it is therefore possible to implement a synchronzization and concurrent method call algorithm following an event-driven design pattern.

Many frameworks exists allowing to structure programmation between threads, among them OODK-JS, an OOP js framework supporting concurrent programming https://github.com/GOMServices/oodk-js-oop-for-js

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

Nope, you have to open a browser atleast once to create your username on GitHub, once created, you can leverage GitHub API to create repositories from command line, following below command:

curl -u 'github-username' https://api.github.com/user/repos -d '{"name":"repo-name"}'

For example:

curl -u 'arpitaggarwal' https://api.github.com/user/repos -d '{"name":"command-line-repo"}'

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

How can I confirm a database is Oracle & what version it is using SQL?

SQL> SELECT version FROM v$instance;
VERSION
-----------------
11.2.0.3.0

How to trim leading and trailing white spaces of a string?

There's a bunch of functions to trim strings in go.

See them there : Trim

Here's an example, adapted from the documentation, removing leading and trailing white spaces :

fmt.Printf("[%q]", strings.Trim(" Achtung  ", " "))

Command to delete all pods in all kubernetes namespaces

kubectl delete po,ing,svc,pv,pvc,sc,ep,rc,deploy,replicaset,daemonset --all -A

Get content of a cell given the row and column numbers

Try =index(ARRAY, ROW, COLUMN)

where: Array: select the whole sheet Row, Column: Your row and column references

That should be easier to understand to those looking at the formula.

How to change options of <select> with jQuery?

I threw CMS's excellent answer into a quick jQuery extension:

(function($, window) {
  $.fn.replaceOptions = function(options) {
    var self, $option;

    this.empty();
    self = this;

    $.each(options, function(index, option) {
      $option = $("<option></option>")
        .attr("value", option.value)
        .text(option.text);
      self.append($option);
    });
  };
})(jQuery, window);

It expects an array of objects which contain "text" and "value" keys. So usage is as follows:

var options = [
  {text: "one", value: 1},
  {text: "two", value: 2}
];

$("#foo").replaceOptions(options);

Lua string to int

here is what you should put

local stringnumber = "10"
local a = tonumber(stringnumber)
print(a + 10)

output:

20

SCRIPT438: Object doesn't support property or method IE

I have added var for all the variables in the corrosponding javascript. That solved the problem in IE.

Previous Code

billableStatus = 1 ;
var classStr = $(this).attr("id").split("_");  
date = currentWeekDates[classStr[2]]; // Required    

activityNameId = "initialRows_" + classStr[1] + "_projectActivityName";
activityId = $("#"+activityNameId).val();        

var projectNameId = "initialRows_" + classStr[1] + "_projectName" ;
projectName = $("#"+projectNameId).val();        

var timeshitEntryId = "initialRows_"+classStr[1]+"_"+classStr[2];     
timeshitEntry = $("#"+timeshitEntryId).val();   

New Code

var billableStatus = 1 ;
var classStr = $(this).attr("id").split("_");  
var date = currentWeekDates[classStr[2]]; // Required    

var activityNameId = "initialRows_" + classStr[1] + "_projectActivityName";
var activityId = $("#"+activityNameId).val();        

var projectNameId = "initialRows_" + classStr[1] + "_projectName" ;
var projectName = $("#"+projectNameId).val();        

var timeshitEntryId = "initialRows_"+classStr[1]+"_"+classStr[2];     
var timeshitEntry = $("#"+timeshitEntryId).val();   

Spring MVC: Complex object as GET @RequestParam

You can absolutely do that, just remove the @RequestParam annotation, Spring will cleanly bind your request parameters to your class instance:

public @ResponseBody List<MyObject> myAction(
    @RequestParam(value = "page", required = false) int page,
    MyObject myObject)

"Application tried to present modally an active controller"?

The same problem error happened to me when I tried to present a child view controller instead of its UINavigationViewController parent

Using union and order by clause in mysql

Just use order by column number (don't use column name). Every query returns some columns, so you can order by any desired column using it's number.

current/duration time of html5 video?

This page might help you out. Everything you need to know about HTML5 video and audio

var video = document.createElement('video');
var curtime = video.currentTime;

If you already have the video element, .currentTime should work. If you need more details, that webpage should be able to help.

UTF-8 problems while reading CSV file with fgetcsv

Try putting this into the top of your file (before any other output):

<?php

header('Content-Type: text/html; charset=UTF-8');

?>

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

If you are using Auto mapper and facing the the issue following is the good solution, it work for me

https://www.codeproject.com/Articles/576393/Solutionplusto-aplus-Theplusoperationplusfailed

Since the problem is that we're mapping null navigation properties, and we actually don't need them to be updated on the Entity since they didn't changed on the Contract, we need to ignore them on the mapping definition:

ForMember(dest => dest.RefundType, opt => opt.Ignore())

So my code ended up like this:

Mapper.CreateMap<MyDataContract, MyEntity>
ForMember(dest => dest.NavigationProperty1, opt => opt.Ignore())
ForMember(dest => dest.NavigationProperty2, opt => opt.Ignore())
.IgnoreAllNonExisting();

Failed to build gem native extension — Rails install

mkmf is part of the ruby1.9.1-dev package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev package by doing:

sudo apt-get install ruby1.9.1-dev

Then you can install Rails as per normal.

Generally it's easier to just do:

sudo apt-get install ruby-dev

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

Ruby array to string conversion

I find this way readable and rubyish:

add_quotes =- > x{"'#{x}'"}

p  ['12','34','35','231'].map(&add_quotes).join(',') => "'12','34','35','231'"

uppercase first character in a variable with bash

This works too...

FooBar=baz

echo ${FooBar^^${FooBar:0:1}}

=> Baz
FooBar=baz

echo ${FooBar^^${FooBar:1:1}}

=> bAz
FooBar=baz

echo ${FooBar^^${FooBar:2:2}}

=> baZ

And so on.

Sources:

Inroductions/Tutorials:

How do I get the current GPS location programmatically in Android?

There are already many answers there but I want to show latest way to get location using Google API, so new programmers can use new method:

I have written detailed tutorial on current location in android at my blog demonuts.com You can also find full source code developed with android studio.

First of all, put this in gradle file

 compile 'com.google.android.gms:play-services:9.0.2'

then implement necessary interfaces

public class MainActivity  extends BaseActivitiy implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener

declare instances

  private GoogleApiClient mGoogleApiClient;
  private Location mLocation;
  private LocationManager locationManager;
  private LocationRequest mLocationRequest;

put this in onCreate()

 mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

At last, override necessary methods

 @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        } startLocationUpdates();
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLocation == null){
            startLocationUpdates();
        }
        if (mLocation != null) {
            double latitude = mLocation.getLatitude();
            double longitude = mLocation.getLongitude();
        } else {
            // Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
        }
    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL);
        // Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
        Log.d("reque", "--->>>>");
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
    }

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }
    @Override
    public void onLocationChanged(Location location) {

    }

Don't forget to start GPS in your device before running app.

Struct like objects in Java

As with most things, there's the general rule and then there are specific circumstances. If you are doing a closed, captured application so that you know how a given object is going to be used, then you can exercise more freedom to favor visibility and/or efficiency. If you're developing a class which is going to be used publicly by others beyond your control, then lean towards the getter/setter model. As with all things, just use common sense. It's often ok to do an initial round with publics and then change them to getter/setters later.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Cause for the error according to the Java [8] Platform, Standard Edition Troubleshooting Guide: (emphasis and line breaks added)

[...] "GC overhead limit exceeded" indicates that the garbage collector is running all the time and Java program is making very slow progress.

After a garbage collection, if the Java process is spending more than approximately 98% of its time doing garbage collection and if it is recovering less than 2% of the heap and has been doing so far the last 5 (compile time constant) consecutive garbage collections, then a java.lang.OutOfMemoryError is thrown. [...]

  1. Increase the heap size if current heap is not enough.
  2. If you still get this error after increasing heap memory, use memory profiling tools like MAT ( Memory analyzer tool), Visual VM etc and fix memory leaks.
  3. Upgrade JDK version to latest version ( 1.8.x) or at least 1.7.x and use G1GC algorithm. . The throughput goal for the G1 GC is 90 percent application time and 10 percent garbage collection time
  4. Apart from setting heap memory with -Xms1g -Xmx2g , try

    -XX:+UseG1GC -XX:G1HeapRegionSize=n -XX:MaxGCPauseMillis=m  
    -XX:ParallelGCThreads=n -XX:ConcGCThreads=n
    

Have a look at some more related questions regarding G1GC

Find if current time falls in a time range

Using Linq we can simplify this by this

 Enumerable.Range(0, (int)(to - from).TotalHours + 1)
            .Select(i => from.AddHours(i)).Where(date => date.TimeOfDay >= new TimeSpan(8, 0, 0) && date.TimeOfDay <= new TimeSpan(18, 0, 0))

need to test if sql query was successful

global $DB;
$status = $DB->query("UPDATE exp_members SET group_id = '$group_id' WHERE member_id = '$member_id'");

if($status == false)
{ 
    die("Didn't Update"); 
}

If you are using mysql_query in the backend (whatever $DB->query() uses to query the database), it will return a TRUE or FALSE for INSERT, UPDATE, and DELETE (and a few others), commands, based on their status.

Loop through a comma-separated shell variable

Not messing with IFS
Not calling external command

variable=abc,def,ghij
for i in ${variable//,/ }
do
    # call your procedure/other scripts here below
    echo "$i"
done

Using bash string manipulation http://www.tldp.org/LDP/abs/html/string-manipulation.html

What is the difference between '@' and '=' in directive scope in AngularJS?

@ local scope property is used to access string values that are defined outside the directive.

= In cases where you need to create a two-way binding between the outer scope and the directive’s isolate scope you can use the = character.

& local scope property allows the consumer of a directive to pass in a function that the directive can invoke.

Kindly check the below link which gives you clear understanding with examples.I found it really very useful so thought of sharing it.

http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

For me the solution was hidden in the Advanced Build Settings of the project properties: enter image description here

For an unknown reason it was set to none: setting it to full caused the breakpoints to be hit.

To get to this dialog, open the project properties, then go to Build, then select the Advanced... button at the bottom of the page.

Convert list or numpy array of single element to float in python

You may want to use the ndarray.item method, as in a.item(). This is also equivalent to (the now deprecated) np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,

>>> a = np.asarray(1).view()
>>> a.item()  # correct
1

>>> a[0]  # breaks
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array


>>> a = np.asarray([[2]])
>>> a.item()  # correct
2

>>> a[0]  # bad result
array([2])

This also has the benefit of throwing an exception if the array is not a singleton, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).

>>> a = np.asarray([1, 2])
>>> a[0]  # silently proceeds
1
>>> a.item()  # detects incorrect size
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p

hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1

How to convert a const char * to std::string

This page on string::string gives two potential constructors that would do what you want:

string ( const char * s, size_t n );
string ( const string& str, size_t pos, size_t n = npos );

Example:

#include<cstdlib>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;

int main(){

    char* p= (char*)calloc(30, sizeof(char));
    strcpy(p, "Hello world");

    string s(p, 15);
    cout << s.size() << ":[" << s << "]" << endl;
    string t(p, 0, 15);
    cout << t.size() << ":[" << t << "]" << endl;

    free(p);
    return 0;
}

Output:

15:[Hello world]
11:[Hello world]

The first form considers p to be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string with cout << .... Probably not what you're looking for.

The second form will implicitly convert the char* to a string, and then keep the maximum between its length and the n you specify. I think this is the simplest solution, in terms of what you have to write.

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Dictionary<string, int> dictionary = new Dictionary<string, int>();

Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);

Background service with location listener in android

First you need to create a Service. In that Service, create a class extending LocationListener. For this, use the following code snippet of Service:

public class LocationService extends Service {
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;

Intent intent;
int counter = 0;

@Override
public void onCreate() {
    super.onCreate();
    intent = new Intent(BROADCAST_ACTION);
}

@Override
public void onStart(Intent intent, int startId) {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, (LocationListener) listener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}

@Override
public IBinder onBind(Intent intent)
{
    return null;
}

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}



/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}



@Override
public void onDestroy() {
    // handler.removeCallbacks(sendUpdatesToUI);     
    super.onDestroy();
    Log.v("STOP_SERVICE", "DONE");
    locationManager.removeUpdates(listener);
}

public static Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        @Override
        public void run() {
            try {
                runnable.run();
            } finally {

            }
        }
    };
    t.start();
    return t;
}
public class MyLocationListener implements LocationListener
{

    public void onLocationChanged(final Location loc)
    {
        Log.i("*****", "Location changed");
        if(isBetterLocation(loc, previousBestLocation)) {
            loc.getLatitude();
            loc.getLongitude();
            intent.putExtra("Latitude", loc.getLatitude());
            intent.putExtra("Longitude", loc.getLongitude());
            intent.putExtra("Provider", loc.getProvider());
            sendBroadcast(intent);

        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void onProviderDisabled(String provider)
    {
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
    }


    public void onProviderEnabled(String provider)
    {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
    }
}

Add this Service any where in your project, the way you want! :)

Get the position of a spinner in Android

The way to get the selection of the spinner is:

  spinner1.getSelectedItemPosition();

Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()

However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.

So you could change that line to:

TestProjectActivity.this.number = position + 1;

If that does not fix the problem, please post the error message generated when your app crashes.

How to destroy JWT Tokens on logout?

On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.

But, What if you want to destroy the token on the Node server -

The problem with JWT package is that it doesn't provide any method or way to destroy the token.

So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

it works in this way :

1) Install jwt-redis from npm

2) To Create -

var redis = require('redis');
var JWTR =  require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);

jwtr.sign(payload, secret)
    .then((token)=>{
            // your code
    })
    .catch((error)=>{
            // error handling
    });

3) To verify -

jwtr.verify(token, secret);

4) To Destroy -

jwtr.destroy(token)

Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

Remove HTML tags from a String

To get formateed plain html text you can do that:

String BR_ESCAPED = "&lt;br/&gt;";
Element el=Jsoup.parse(html).select("body");
el.select("br").append(BR_ESCAPED);
el.select("p").append(BR_ESCAPED+BR_ESCAPED);
el.select("h1").append(BR_ESCAPED+BR_ESCAPED);
el.select("h2").append(BR_ESCAPED+BR_ESCAPED);
el.select("h3").append(BR_ESCAPED+BR_ESCAPED);
el.select("h4").append(BR_ESCAPED+BR_ESCAPED);
el.select("h5").append(BR_ESCAPED+BR_ESCAPED);
String nodeValue=el.text();
nodeValue=nodeValue.replaceAll(BR_ESCAPED, "<br/>");
nodeValue=nodeValue.replaceAll("(\\s*<br[^>]*>){3,}", "<br/><br/>");

To get formateed plain text change <br/> by \n and change last line by:

nodeValue=nodeValue.replaceAll("(\\s*\n){3,}", "<br/><br/>");

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

Appending a byte[] to the end of another byte[]

You need to declare out as a byte array with a length equal to the lengths of ciphertext and mac added together, and then copy ciphertext over the beginning of out and mac over the end, using arraycopy.

byte[] concatenateByteArrays(byte[] a, byte[] b) {
    byte[] result = new byte[a.length + b.length]; 
    System.arraycopy(a, 0, result, 0, a.length); 
    System.arraycopy(b, 0, result, a.length, b.length); 
    return result;
} 

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

This will work:

 >>>print(unicodedata.normalize('NFD', re.sub("[\(\[].*?[\)\]]", "", "bats\xc3\xa0")).encode('ascii', 'ignore'))

Output:

>>>bats

Commenting multiple lines in DOS batch file

You can use a goto to skip over code.

goto comment
...skip this...
:comment

How to deserialize a JObject to .NET object

From the documentation I found this

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

The class definition for Person should be compatible to the following:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

How to get current url in view in asp.net core 1.0

You can consider to use this extension method (from Microsoft.AspNetCore.Http.Extensions namespace:

@Context.Request.GetDisplayUrl()

For some my projects i prefer more flexible solution. There are two extensions methods.

1) First method creates Uri object from incoming request data (with some variants through optional parameters). 2) Second method receives Uri object and returns string in following format (with no trailing slash): Scheme_Host_Port

public static Uri GetUri(this HttpRequest request, bool addPath = true, bool addQuery = true)
    {
        var uriBuilder = new UriBuilder
        {
            Scheme = request.Scheme,
            Host = request.Host.Host,
            Port = request.Host.Port.GetValueOrDefault(80),
            Path = addPath ? request.Path.ToString() : default(string),
            Query = addQuery ? request.QueryString.ToString() : default(string)
        };
        return uriBuilder.Uri;
    }

    public static string HostWithNoSlash(this Uri uri)
    {
        return uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
    }

Usage:

//before >> https://localhost:44304/information/about?param1=a&param2=b
        Request.GetUri(addQuery: false);
        //after >> https://localhost:44304/information/about

        //before >> https://localhost:44304/information/about?param1=a&param2=b
        new Uri("https://localhost:44304/information/about?param1=a&param2=b").GetHostWithNoSlash();
        //after >> https://localhost:44304

Cannot connect to repo with TortoiseSVN

Once I faced the same issue. I was trying to take svn checkout using repository URL consisting of DOMAIN NAME. I tried to connect using IP address in place of DOMAIN NAME and I was able to take checkout

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

convert strtotime to date time format in php

$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);

Where

http://php.net/manual/en/function.date.php

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".

How to design RESTful search/filtering?

Don't fret too much if your initial API is fully RESTful or not (specially when you are just in the alpha stages). Get the back-end plumbing to work first. You can always do some sort of URL transformation/re-writing to map things out, refining iteratively until you get something stable enough for widespread testing ("beta").

You can define URIs whose parameters are encoded by position and convention on the URIs themselves, prefixed by a path you know you'll always map to something. I don't know PHP, but I would assume that such a facility exists (as it exists in other languages with web frameworks):

.ie. Do a "user" type of search with param[i]=value[i] for i=1..4 on store #1 (with value1,value2,value3,... as a shorthand for URI query parameters):

1) GET /store1/search/user/value1,value2,value3,value4

or

2) GET /store1/search/user,value1,value2,value3,value4

or as follows (though I would not recommend it, more on that later)

3) GET /search/store1,user,value1,value2,value3,value4

With option 1, you map all URIs prefixed with /store1/search/user to the search handler (or whichever the PHP designation) defaulting to do searches for resources under store1 (equivalent to /search?location=store1&type=user.

By convention documented and enforced by the API, parameters values 1 through 4 are separated by commas and presented in that order.

Option 2 adds the search type (in this case user) as positional parameter #1. Either option is just a cosmetic choice.

Option 3 is also possible, but I don't think I would like it. I think the ability of search within certain resources should be presented in the URI itself preceding the search itself (as if indicating clearly in the URI that the search is specific within the resource.)

The advantage of this over passing parameters on the URI is that the search is part of the URI (thus treating a search as a resource, a resource whose contents can - and will - change over time.) The disadvantage is that parameter order is mandatory.

Once you do something like this, you can use GET, and it would be a read-only resource (since you can't POST or PUT to it - it gets updated when it's GET'ed). It would also be a resource that only comes to exist when it is invoked.

One could also add more semantics to it by caching the results for a period of time or with a DELETE causing the cache to be deleted. This, however, might run counter to what people typically use DELETE for (and because people typically control caching with caching headers.)

How you go about it would be a design decision, but this would be the way I'd go about. It is not perfect, and I'm sure there will be cases where doing this is not the best thing to do (specially for very complex search criteria).

Insert Picture into SQL Server 2005 Image Field using only SQL

I achieved the goal where I have multiple images to insert in the DB as

INSERT INTO [dbo].[User]
           ([Name]
           ,[Image1]
           ,[Age]
           ,[Image2]
           ,[GroupId]
           ,[GroupName])
           VALUES
           ('Umar'
           , (SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image1)
           ,26
           ,(SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image2)
            ,'Group123'
           ,'GroupABC')

How do I enable MSDTC on SQL Server?

Do you even need MSDTC? The escalation you're experiencing is often caused by creating multiple connections within a single TransactionScope.

If you do need it then you need to enable it as outlined in the error message. On XP:

  • Go to Administrative Tools -> Component Services
  • Expand Component Services -> Computers ->
  • Right-click -> Properties -> MSDTC tab
  • Hit the Security Configuration button

Fatal error: Call to a member function fetch_assoc() on a non-object

Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.

Short rot13 function - Python

def rot13(s):
    lower_chars = ''.join(chr(c) for c in range (97,123)) #ASCII a-z
    upper_chars = ''.join(chr(c) for c in range (65,91)) #ASCII A-Z
    lower_encode = lower_chars[13:] + lower_chars[:13] #shift 13 bytes
    upper_encode = upper_chars[13:] + upper_chars[:13] #shift 13 bytes
    output = "" #outputstring
    for c in s:
        if c in lower_chars:
                output = output + lower_encode[lower_chars.find(c)]
        elif c in upper_chars:
            output = output + upper_encode[upper_chars.find(c)]
        else:
            output = output + c
    return output

Another solution with shifting. Maybe this code helps other people to understand rot13 better. Haven't tested it completely.

Load data from txt with pandas

If you want to load the txt file with specified column name, you can use the code below. It worked for me.

import pandas as pd    
data = pd.read_csv('file_name.txt', sep = "\t", names = ['column1_name','column2_name', 'column3_name'])

Stop form refreshing page on submit

This problem becomes more complex when you give the user 2 possibilities to submit the form:

  1. by clicking on an ad hoc button
  2. by hitting Enter key

In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.

And now comes the problem with IE (in any case version 11) Remark: This issue does not exist with Chrome nor with FireFox !

  • When you click the submit button the form is submitted once; fine.
  • When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.

Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks. This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)

The source code HTML & js are in the snippet. The principle is described there. Warning:

You can't test it in the snippet because the post action is not defined and hitting Enter key might interfer with stackoverflow.

If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.

_x000D_
_x000D_
/*_x000D_
 * inForm points to the form_x000D_
 */_x000D_
var inForm = document.getElementById('idGetUserFrm');_x000D_
/*_x000D_
 * IE submits the form twice_x000D_
 * To avoid this the boolean isSumbitted is:_x000D_
 *  1) initialized to false when the form is displayed 4 the first time_x000D_
 * Remark: it is not the same event as "body load"_x000D_
 */_x000D_
var isSumbitted = false;_x000D_
_x000D_
function checkEnter(e) {_x000D_
  if (e && e.keyCode == 13) {_x000D_
    inForm.submit();_x000D_
    /*_x000D_
      * 2) set to true after the form submission was invoked_x000D_
      */_x000D_
    isSumbitted = true;_x000D_
  }_x000D_
}_x000D_
function onSubmit () {_x000D_
  if (isSumbitted) {_x000D_
    /*_x000D_
    * 3) reset to false after the form submission executed_x000D_
    */_x000D_
    isSumbitted = false;_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">_x000D_
   First name:<br>_x000D_
   <input type="text" name="firstname" value="Mickey">_x000D_
   <input type="submit" value="Submit">_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SQL Greater than, Equal to AND Less Than

declare @starttime datetime = '2012-03-07 22:58:00'

SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, @starttime ) ) <= 60

MySQL Workbench Dark Theme

For Ubuntu Users, the code_editor.xml is in

/usr/share/mysql-workbench/data

edit as you need, In Ubuntu which is a must need, some default used colours lacks contrast and it is unable to read, For a quick workaround you can also use this solution.

Visit this repo to get the full XML file.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

Why use String.Format?

There's interesting stuff on the performance aspects in this question

However I personally would still recommend string.Format unless performance is critical for readability reasons.

string.Format("{0}: {1}", key, value);

Is more readable than

key + ": " + value

For instance. Also provides a nice separation of concerns. Means you can have

string.Format(GetConfigValue("KeyValueFormat"), key, value);

And then changing your key value format from "{0}: {1}" to "{0} - {1}" becomes a config change rather than a code change.

string.Format also has a bunch of format provision built into it, integers, date formatting, etc.

How to set delay in android?

Try this code:

import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 5s = 5000ms
        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    }
}, 5000);

How to send a POST request with BODY in swift

Alamofire ~5.2 and Swift 5

You can structure your parameter data

Work with fake json api

struct Parameter: Encodable {
     let token: String = "xxxxxxxxxx"
     let data: Dictionary = [
        "id": "personNickname",
        "email": "internetEmail",
        "gender": "personGender",
     ]
}

 let parameters = Parameter()

 AF.request("https://app.fakejson.com/q", method: .post, parameters: parameters).responseJSON { response in
            print(response)
        }

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

Why should C++ programmers minimize use of 'new'?

When you use new, objects are allocated to the heap. It is generally used when you anticipate expansion. When you declare an object such as,

Class var;

it is placed on the stack.

You will always have to call destroy on the object that you placed on the heap with new. This opens the potential for memory leaks. Objects placed on the stack are not prone to memory leaking!

How to Read from a Text File, Character by Character in C++

You could try something like:

char ch;
fstream fin("file", fstream::in);
while (fin >> noskipws >> ch) {
    cout << ch; // Or whatever
}

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

How can I convert a PFX certificate file for use with Apache on a linux server?

Additionally to

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key

I also generated Certificate Authority (CA) certificate:

openssl pkcs12 -in domain.pfx -out domain-ca.crt -nodes -nokeys -cacerts

And included it in Apache config file:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 SSLCACertificateFile /path/to/domain-ca.crt
 ...
</VirtualHost>

Dynamically add event listener

Renderer has been deprecated in Angular 4.0.0-rc.1, read the update below

The angular2 way is to use listen or listenGlobal from Renderer

For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement)

constructor(elementRef: ElementRef, renderer: Renderer) {

    // Listen to click events in the component
    renderer.listen(elementRef.nativeElement, 'click', (event) => {
      // Do something with 'event'
    })
);

You can use listenGlobal that will give you access to document, body, etc.

renderer.listenGlobal('document', 'click', (event) => {
  // Do something with 'event'
});

Note that since beta.2 both listen and listenGlobal return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).

So to remove the listener we added dynamically we must assign listen or listenGlobal to a variable that will hold the function returned, and then we execute it.

// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;

// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;

constructor(elementRef: ElementRef, renderer: Renderer) {
    
    // We cache the function "listen" returns
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
        // Do something with 'event'
    });
}

ngOnDestroy() {
    // We execute both functions to remove the respectives listeners

    // Removes "listen" listener
    this.listenFunc();
    
    // Removs "listenGlobal" listener
    this.globalListenFunc();
}

Here's a plnkr with an example working. The example contains the usage of listen and listenGlobal.

Using RendererV2 with Angular 4.0.0-rc.1+ (Renderer2 since 4.0.0-rc.3)

  • 25/02/2017: Renderer has been deprecated, now we should use RendererV2 (see line below). See the commit.

  • 10/03/2017: RendererV2 was renamed to Renderer2. See the breaking changes.

RendererV2 has no more listenGlobal function for global events (document, body, window). It only has a listen function which achieves both functionalities.

For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).

listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
      () => void {
    if (typeof target === 'string') {
      return <() => void>this.eventManager.addGlobalEventListener(
          target, event, decoratePreventDefault(callback));
    }
    return <() => void>this.eventManager.addEventListener(
               target, event, decoratePreventDefault(callback)) as() => void;
  }

As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener

To remove the listener it's the same as it was with Renderer in angular 2.x. listen returns a function, then call that function.

Example

// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
  console.log('Clicking the document', evt);
})

let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
  console.log('Clicking the button', evt);
});

// Remove listeners
global();
simple();

plnkr with Angular 4.0.0-rc.1 using RendererV2

plnkr with Angular 4.0.0-rc.3 using Renderer2

What is a View in Oracle?

A view is simply any SELECT query that has been given a name and saved in the database. For this reason, a view is sometimes called a named query or a stored query. To create a view, you use the SQL syntax:

     CREATE OR REPLACE VIEW <view_name> AS
     SELECT <any valid select query>;

Combine multiple results in a subquery into a single comma-separated value

You may need to provide some more details for a more precise response.

Since your dataset seems kind of narrow, you might consider just using a row per result and performing the post-processing at the client.

So if you are really looking to make the server do the work return a result set like

ID       Name       SomeColumn
1        ABC        X
1        ABC        Y
1        ABC        Z
2        MNO        R
2        MNO        S

which of course is a simple INNER JOIN on ID

Once you have the resultset back at the client, maintain a variable called CurrentName and use that as a trigger when to stop collecting SomeColumn into the useful thing you want it to do.

Matplotlib figure facecolor (background color)

savefig has its own parameter for facecolor. I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor() every time:

plt.rcParams['axes.facecolor']='red'
plt.rcParams['savefig.facecolor']='red'

How do I remove a specific element from a JSONArray?

In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove() method if you are targeting for Android API-18 or less. The remove() method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray to create a compatible override for the remove() method.

public class MJSONArray extends JSONArray {

    @Override
    public Object remove(int index) {

        JSONArray output = new JSONArray();     
        int len = this.length(); 
        for (int i = 0; i < len; i++)   {
            if (i != index) {
                try {
                    output.put(this.get(i));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        } 
        return output;
        //return this; If you need the input array in case of a failed attempt to remove an item.
     }
}

EDIT As Daniel pointed out, handling an error silently is bad style. Code improved.

Set the absolute position of a view

In general, you can add a View in a specific position using a FrameLayout as container by specifying the leftMargin and topMargin attributes.

The following example will place a 20x20px ImageView at position (100,200) using a FrameLayout as fullscreen container:

XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:background="#33AAFF"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

Activity / Fragment / Custom view

//...
FrameLayout root = (FrameLayout)findViewById(R.id.root);
ImageView img = new ImageView(this);
img.setBackgroundColor(Color.RED);
//..load something inside the ImageView, we just set the background color

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(20, 20);
params.leftMargin = 100;
params.topMargin  = 200;
root.addView(img, params);
//...

This will do the trick because margins can be used as absolute (X,Y) coordinates without a RelativeLayout:

enter image description here

How can I pop-up a print dialog box using Javascript?

window.print();  

unless you mean a custom looking popup.

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

fatal error LNK1104: cannot open file 'kernel32.lib'

Make sure you have in VC++ directories (Right click project, Click Property Page),

  • Include Directories: $(IncludePath)
  • List item Library Directories: $(LibraryPath)

How to construct a std::string from a std::vector<char>?

I like Stefan’s answer (Sep 11 ’13) but would like to make it a bit stronger:

If the vector ends with a null terminator, you should not use (v.begin(), v.end()): you should use v.data() (or &v[0] for those prior to C++17).

If v does not have a null terminator, you should use (v.begin(), v.end()).

If you use begin() and end() and the vector does have a terminating zero, you’ll end up with a string "abc\0" for example, that is of length 4, but should really be only "abc".

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

Get the current fragment object

Now at some point of time I need to identify which object is currently there

Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.frameTitle container.

If you are using the androidx edition of Fragment — as you should in modern apps — , use getSupportFragmentManager() on your FragmentActivity/AppCompatActivity instead of getFragmentManager()

SQL Server - INNER JOIN WITH DISTINCT

select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;

hope this helps

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Format a Go string without printing?

In your case, you need to use Sprintf() for format string.

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)

Your output will be :

Good Morning, This is John and I'm living here from last 20 years.

AJAX POST and Plus Sign ( + ) -- How to Encode?

my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:

my solution (not the better way, but it works):

javascript:

function replaceAll( text, busca, reemplaza ){
  while (text.toString().indexOf(busca) != -1)
  text = text.toString().replace(busca,reemplaza);return text;
}


function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas   
return code;
}

function to save:

function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();    
var result = null;
$.ajax({
datatype : "html",
data: myData,  
url: url,
success : function(result) {
    alert(result); // result ok                     
},
}); 
} // end function

function in php:

<?php
function save($pid,$code){
    $code= preg_replace("[\{1\}]","|",$code);
    $code= preg_replace("[\{0\}]","+",$code);
    mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>

How to rename uploaded file before saving it into a directory?

/* create new name file */
$filename   = uniqid() . "-" . time(); // 5dab1961e93a7-1571494241
$extension  = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION ); // jpg
$basename   = $filename . "." . $extension; // 5dab1961e93a7_1571494241.jpg

$source       = $_FILES["file"]["tmp_name"];
$destination  = "../img/imageDirectory/{$basename}";

/* move the file */
move_uploaded_file( $source, $destination );

echo "Stored in: {$destination}";

failed to find target with hash string 'android-22'

In sdk Manager download android 5.1.1, it worked for me

How do I get a computer's name and IP address using VB.NET?

IP Version 4 Only ...

Imports System.Net

Module MainLine
    Sub Main()
        Dim hostName As String = Dns.GetHostName
        Console.WriteLine("Host Name: " & hostName & vbNewLine)
        Console.WriteLine("IP Version 4 Address(es):")
        For Each address In Dns.GetHostEntry(hostName).AddressList().
            Where(Function(p) p.AddressFamily = Sockets.AddressFamily.InterNetwork)
            Console.WriteLine(vbTab & address.ToString)
        Next
        Console.ReadKey()
    End Sub
End Module

String comparison using '==' vs. 'strcmp()'

strcmp() and === are both case sensitive but === is much faster

sample code: http://snipplr.com/view/758/

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.

From Books Online, on MAXDOP:

Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.

See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.

Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.

Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.

What permission do I need to access Internet from an Android application?

Just Add these 2 permissions

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

in your app's AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.android.networkusage"
        ...>
    
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application 
            ...>
            ...
        </application>
    </manifest>

Happy Coding:)

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

How do you check "if not null" with Eloquent?

I see this question is a bit old but I ran across it looking for an answer. Although I did not have success with the answers here I think this might be because I'm on PHP 7.2 and Laravel 5.7. or possible because I was just playing around with some data on the CLI using Laravel Tinker.

I have some things I tried that worked for me and others that did not that I hope will help others out.


I did not have success running:

    MyModel::whereNotNull('deleted_by')->get()->all();             // []
    MyModel::where('deleted_by', '<>', null)->get()->all();        // []
    MyModel::where('deleted_by', '!=', null)->get()->all();        // []
    MyModel::where('deleted_by', '<>', '', 'and')->get()->all();   // []
    MyModel::where('deleted_by', '<>', null, 'and')->get()->all(); // []
    MyModel::where('deleted_by', 'IS NOT', null)->get()->all();    // []

All of the above returned an empty array for me


I did however have success running:

    DB::table('my_models')->whereNotNull('deleted_by')->get()->all(); // [ ... ]

This returned all the results in an array as I expected. Note: you can drop the all() and get back a Illuminate\Database\Eloquent\Collection instead of an array if you prefer.

Java decimal formatting using String.format?

Here is a small code snippet that does the job:

double a = 34.51234;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);

System.out.println(df.format(a));

Apply CSS Style to child elements

The > selector matches direct children only, not descendants.

You want

div.test th, td, caption {}

or more likely

div.test th, div.test td, div.test caption {}

Edit:

The first one says

  div.test th, /* any <th> underneath a <div class="test"> */
  td,          /* or any <td> anywhere at all */
  caption      /* or any <caption> */

Whereas the second says

  div.test th,     /* any <th> underneath a <div class="test"> */
  div.test td,     /* or any <td> underneath a <div class="test"> */
  div.test caption /* or any <caption> underneath a <div class="test">  */

In your original the div.test > th says any <th> which is a **direct** child of <div class="test">, which means it will match <div class="test"><th>this</th></div> but won't match <div class="test"><table><th>this</th></table></div>

What are the differences between type() and isinstance()?

According to python documentation here is a statement:

8.15. types — Names for built-in types

Starting in Python 2.2, built-in factory functions such as int() and str() are also names for the corresponding types.

So isinstance() should be preferred over type().

How do I disable TextBox using JavaScript?

Here was my solution:

Markup:

<div id="name" disabled="disabled">

Javascript:

document.getElementById("name").disabled = true;

This the best solution for my applications - hope this helps!

Using the star sign in grep

This may be the answer you're looking for:

grep abc MyFile | grep def

Only thing is... it will output lines were "def" is before OR after "abc"

asynchronous vs non-blocking

They differ in spelling only. There is no difference in what they refer to. To be technical you could say they differ in emphasis. Non blocking refers to control flow(it doesn't block.) Asynchronous refers to when the event\data is handled(not synchronously.)

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:

  • People in favor of cssSelector say that it is more readable and faster (especially when running against Internet Explorer).
  • While those in favor of XPath tout it's ability to transverse the page (while cssSelector cannot).
  • Traversing the DOM in older browsers like IE8 does not work with cssSelector but is fine with XPath.
  • XPath can walk up the DOM (e.g. from child to parent), whereas cssSelector can only traverse down the DOM (e.g. from parent to child)
  • However not being able to traverse the DOM with cssSelector in older browsers isn't necessarily a bad thing as it is more of an indicator that your page has poor design and could benefit from some helpful markup.
  • Ben Burton mentions you should use cssSelector because that's how applications are built. This makes the tests easier to write, talk about, and have others help maintain.
  • Adam Goucher says to adopt a more hybrid approach -- focusing first on IDs, then cssSelector, and leveraging XPath only when you need it (e.g. walking up the DOM) and that XPath will always be more powerful for advanced locators.

Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.

Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.


Test SetUp

To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark was used.


Test Code

require_relative 'base'
require 'benchmark'

class LargeDOM < Base

  LOCATORS = {
    nested_sibling_traversal: {
      css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
      xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
    },
    nested_sibling_traversal_by_class: {
      css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
      xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
    },
    table_header_id_and_class: {
      css: "table#large-table thead .column-50",
      xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
    },
    table_header_id_class_and_direct_desc: {
      css: "table#large-table > thead .column-50",
      xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
    },
    table_header_traversing: {
      css: "table#large-table thead tr th:nth-of-type(50)",
      xpath: "//table[@id='large-table']//thead//tr//th[50]"
    },
    table_header_traversing_and_direct_desc: {
      css: "table#large-table > thead > tr > th:nth-of-type(50)",
      xpath: "//table[@id='large-table']/thead/tr/th[50]"
    },
    table_cell_id_and_class: {
      css: "table#large-table tbody .column-50",
      xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
    },
    table_cell_id_class_and_direct_desc: {
      css: "table#large-table > tbody .column-50",
      xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
    },
    table_cell_traversing: {
      css: "table#large-table tbody tr td:nth-of-type(50)",
      xpath: "//table[@id='large-table']//tbody//tr//td[50]"
    },
    table_cell_traversing_and_direct_desc: {
      css: "table#large-table > tbody > tr > td:nth-of-type(50)",
      xpath: "//table[@id='large-table']/tbody/tr/td[50]"
    }
  }

  attr_reader :driver

  def initialize(driver)
    @driver = driver
    visit '/large'
    is_displayed?(id: 'siblings')
    super
  end

  # The benchmarking approach was borrowed from
  # http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
  def benchmark
    Benchmark.bmbm(27) do |bm|
      LOCATORS.each do |example, data|
    data.each do |strategy, locator|
      bm.report(example.to_s + " using " + strategy.to_s) do
        begin
          ENV['iterations'].to_i.times do |count|
         find(strategy => locator)
          end
        rescue Selenium::WebDriver::Error::NoSuchElementError => error
          puts "( 0.0 )"
        end
      end
    end
      end
    end
  end

end

Results

NOTE: The output is in seconds, and the results are for the total run time of 100 executions.

In Table Form:

css_xpath_under_microscopev2

In Chart Form:

  • Chrome:

chart-chrome

  • Firefox:

chart-firefox

  • Internet Explorer 8:

chart-ie8

  • Internet Explorer 9:

chart-ie9

  • Internet Explorer 10:

chart-ie10

  • Opera:

chart-opera


Analyzing the Results

  • Chrome and Firefox are clearly tuned for faster cssSelector performance.
  • Internet Explorer 8 is a grab bag of cssSelector that won't work, an out of control XPath traversal that takes ~65 seconds, and a 38 second table traversal with no cssSelector result to compare it against.
  • In IE 9 and 10, XPath is faster overall. In Safari, it's a toss up, except for a couple of slower traversal runs with XPath. And across almost all browsers, the nested sibling traversal and table cell traversal done with XPath are an expensive operation.
  • These shouldn't be that surprising since the locators are brittle and inefficient and we need to avoid them.

Summary

  • Overall there are two circumstances where XPath is markedly slower than cssSelector. But they are easily avoidable.
  • The performance difference is slightly in favor of for non-IE browsers and slightly in favor of for IE browsers.

Trivia

You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.

How to check if directory exist using C++ and winAPI

0.1 second Google search:

BOOL DirectoryExists(const char* dirName) {
  DWORD attribs = ::GetFileAttributesA(dirName);
  if (attribs == INVALID_FILE_ATTRIBUTES) {
    return false;
  }
  return (attribs & FILE_ATTRIBUTE_DIRECTORY);
}

Pandas every nth row

I'd use iloc, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row:

df.iloc[::5, :]

Split text with '\r\n'

I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.

the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r

var serials = model.List.Replace("\n","").Split('\r').ToList<string>();

I like this approach because you can do it in just one line.

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

How to compare two NSDates: Which is more recent?

In Swift, you can overload existing operators:

func > (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}

func < (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}

Then, you can compare NSDates directly with <, >, and == (already supported).

Fragment transaction animation: slide in and slide out

This is another solution which I use:

public class CustomAnimator {
    private static final String TAG = "com.example.CustomAnimator";

    private static Stack<AnimationEntry> animation_stack    = new Stack<>();

    public static final int                 DIRECTION_LEFT  = 1;
    public static final int                 DIRECTION_RIGHT = -1;
    public static final int                 DIRECTION_UP    = 2;
    public static final int                 DIRECTION_DOWN  = -2;

    static class AnimationEntry {
        View in;
        View    out;
        int     direction;
        long    duration;
    }

    public static boolean hasHistory() {
        return !animation_stack.empty();
    }

    public static void reversePrevious() {
        if (!animation_stack.empty()) {
            AnimationEntry entry = animation_stack.pop();
            slide(entry.out, entry.in, -entry.direction, entry.duration, false);
        }
    }

    public static void clearHistory() {
        animation_stack.clear();
    }

    public static void slide(final View in, View out, final int direction, long duration) {
        slide(in, out, direction, duration, true);
    }

    private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {

        ViewGroup in_parent = (ViewGroup) in.getParent();
        ViewGroup out_parent = (ViewGroup) out.getParent();

        if (!in_parent.equals(out_parent)) {
            return;
        }

        int parent_width = in_parent.getWidth();
        int parent_height = in_parent.getHeight();

        ObjectAnimator slide_out;
        ObjectAnimator slide_in;

        switch (direction) {
            case DIRECTION_LEFT:
            default:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
                break;
            case DIRECTION_RIGHT:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
                break;
            case DIRECTION_UP:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
                break;
            case DIRECTION_DOWN:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
                break;
        }

        AnimatorSet animations = new AnimatorSet();
        animations.setDuration(duration);
        animations.playTogether(slide_in, slide_out);
        animations.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationCancel(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                out.setVisibility(View.INVISIBLE);
                if (save) {
                    AnimationEntry ae = new AnimationEntry();
                    ae.in = in;
                    ae.out = out;
                    ae.direction = direction;
                    ae.duration = duration;
                    animation_stack.push(ae);
                }
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationStart(Animator arg0) {
                in.setVisibility(View.VISIBLE);
            }
        });
        animations.start();
    }
}

The usage of class. Let's say you have two fragments (list and details fragments)as shown below

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ui_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/list_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/details_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
</FrameLayout>

Usage

View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);

You can use the function CustomAnimator.reversePrevious();to get the previous view when the user pressed back.

Twitter API returns error 215, Bad Authentication Data

Here first every one need to use oauth2/token api then use followers/list api.
Other wise you will get this error. Because followers/list api requires Authentication.

In swift (for mobile app) me also got the same problem.

If you want to know the api's and it's parameters follow this link , Get twitter friends list in swift?

How to exclude a directory in find . command

Use the -prune option. So, something like:

find . -type d -name proc -prune -o -name '*.js'

The '-type d -name proc -prune' only look for directories named proc to exclude.
The '-o' is an 'OR' operator.

How do I parse JSON in Android?

I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:

try{
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions
    e.printStackTrace();
}

Once you have your JSONObject refer to the SDK for details on how to extract the data you require.

How do I concatenate a boolean to a string in Python?

answer = True
myvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

HTML for the Pause symbol in audio and video control

There are various symbols which could be considered adequate replacements, including:

  1. | | - two standard (bolded) vertical bars.

  2. ▋▋ - &#9611; and another&#9611;

  3. ▌▌ - &#9612; and another&#9612;

  4. ▍▍ - &#9613; and another&#9613;

  5. ▎▎ - &#9614; and another&#9614;

  6. ❚❚ - &#10074; and another &#10074;

I may have missed out one or two, but I think these are the better ones. Here's a list of symbols just in case.

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

Getting Error "Form submission canceled because the form is not connected"

I have found this problem in my React project.

The problem was,

  • I have set the button type 'submit'
  • I have set an onClick handler on the button

So, while clicking on the button, the onclick function is firing and the form is NOT submitting, and the console is printing -

Form submission canceled because the form is not connected

The simple fix is:

  • Use onSubmit handler on the form
  • Remove the onClick handler form the button itself, keep the type 'Submit'