Programs & Examples On #Handleerror

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

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

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

This problem is commonly related to compiler errors in the Java code. Sometimes Android Studio does not show these errors in the Project explorer. However, when a problematic .java file is opened, errors are shown. Try to resolve errors and rebuild the project.

What is pipe() function in Angular

RxJS Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections.

For example, RxJS defines operators such as map(), filter(), concat(), and flatMap().

You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.

How to add CORS request in header in Angular 5

Make the header looks like this for HttpClient in NG5:

let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'apikey': this.apikey,
        'appkey': this.appkey,
      }),
      params: new HttpParams().set('program_id', this.program_id)
    };

You will be able to make api call with your localhost url, it works for me ..

  • Please never forget your params columnd in the header: such as params: new HttpParams().set('program_id', this.program_id)

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

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

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

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

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

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

Angular 2 http post params and body

And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

Cannot find control with name: formControlName in angular reactive form

you're missing group nested controls with formGroupName directive

<div class="panel-body" formGroupName="address">
  <div class="form-group">
    <label for="address" class="col-sm-3 control-label">Business Address</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
    </div>
  </div>
  <div class="form-group">
    <label for="website" class="col-sm-3 control-label">Website</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="website" placeholder="website">
    </div>
  </div>
  <div class="form-group">
    <label for="telephone" class="col-sm-3 control-label">Telephone</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
    </div>
  </div>
  <div class="form-group">
    <label for="email" class="col-sm-3 control-label">Email</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="email" placeholder="email">
    </div>
  </div>
  <div class="form-group">
    <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
    </div>
  </div>
  <div class="form-group">
    <label for="about" class="col-sm-3  control-label"></label>
    <div class="col-sm-3">
      <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
    </div>
    <label for="about" class="col-sm-2  control-label"></label>
    <div class="col-sm-3">
      <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
    </div>
  </div>
</div>

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 I add Headers to http.get or http.post in Typescript and angular 2?

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
   var myFormData = { email: '[email protected]', password: '123' };
   const headers = new HttpHeaders();
   headers.append('Content-Type', 'application/json');
   //HTTP POST REQUEST
   this.httpClient
  .post(this.REST_API_SERVER, myFormData, {
    headers: headers,
   })
  .subscribe((data) => {
    console.log("i'm from service............", data, myFormData, headers);
    return data;
  });
}

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

I had the same issues and i had dialogComponent in EntryComponents and it still did not work. this is how I was able to solve the problem. the link is here to a previously answered post:

https://stackoverflow.com/a/64224799/14385758

How to correctly set Http Request Header in Angular 2

We can do it nicely using Interceptors. You dont have to set options in all your services neither manage all your error responses, just define 2 interceptors (one to do something before sending the request to server and one to do something before sending the server's response to your service)

  1. Define an AuthInterceptor class to do something before sending the request to the server. You can set the api token (retrieve it from localStorage, see step 4) and other options in this class.
  2. Define an responseInterceptor class to do something before sending the server response to your service (httpClient). You can manage your server response, the most comon use is to check if the user's token is valid (if not clear token from localStorage and redirect to login).
  3. In your app.module import HTTP_INTERCEPTORS from '@angular/common/http'. Then add to your providers the interceptors (AuthInterceptor and responseInterceptor). Doing this your app will consider the interceptors in all our httpClient calls.

  4. At login http response (use http service), save the token at localStorage.

  5. Then use httpClient for all your apirest services.

You can check some good practices on my github proyect here

enter image description here

Angular 1.6.0: "Possibly unhandled rejection" error

The code you show will handle a rejection that occurs before the call to .then. In such situation, the 2nd callback you pass to .then will be called, and the rejection will be handled.

However, when the promise on which you call .then is successful, it calls the 1st callback. If this callback throws an exception or returns a rejected promise, this resulting rejection will not be handled, because the 2nd callback does not handle rejections in cause by the 1st. This is just how promise implementations compliant with the Promises/A+ specification work, and Angular promises are compliant.

You can illustrate this with the following code:

function handle(p) {
    p.then(
        () => {
            // This is never caught.
            throw new Error("bar");
        },
        (err) => {
            console.log("rejected with", err);
        });
}

handle(Promise.resolve(1));
// We do catch this rejection.
handle(Promise.reject(new Error("foo")));

If you run it in Node, which also conforms to Promises/A+, you get:

rejected with Error: foo
    at Object.<anonymous> (/tmp/t10/test.js:12:23)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
(node:17426) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: bar

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 convert an object to JSON correctly in Angular 2 with TypeScript

You'll have to parse again if you want it in actual JSON:

JSON.parse(JSON.stringify(object))

Spring Resttemplate exception handling

You want to create a class that implements ResponseErrorHandler and then use an instance of it to set the error handling of your rest template:

public class MyErrorHandler implements ResponseErrorHandler {
  @Override
  public void handleError(ClientHttpResponse response) throws IOException {
    // your error handling here
  }

  @Override
  public boolean hasError(ClientHttpResponse response) throws IOException {
     ...
  }
}

[...]

public static void main(String args[]) {
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.setErrorHandler(new MyErrorHandler());
}

Also, Spring has the class DefaultResponseErrorHandler, which you can extend instead of implementing the interface, in case you only want to override the handleError method.

public class MyErrorHandler extends DefaultResponseErrorHandler {
  @Override
  public void handleError(ClientHttpResponse response) throws IOException {
    // your error handling here
  }
}

Take a look at its source code to have an idea of how Spring handles HTTP errors.

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

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

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

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

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

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

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

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

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

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

How to catch exception correctly from http.request()?

There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.

The first method is preferable, the second is a bit outdated, but so far it works too.

1) Solution 1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}

2) Solution 2. It is old way but still works.

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

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



// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
    getProducts(){
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                console.log(data);
                return data;
            }
        ).catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
        );
    }
}

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

My case, the server was encrypting with padding disabled. But the client was trying to decrypt with the padding enabled.

While using EVP_CIPHER*, by default the padding is enabled. To disable explicitly we need to do

EVP_CIPHER_CTX_set_padding(context, 0);

So non matching padding options can be one reason.

How get data from material-ui TextField, DropDownMenu components?

I don't know about y'all but for my own lazy purposes I just got the text fields from 'document' by ID and set the values as parameters to my back-end JS function:

_x000D_
_x000D_
//index.js_x000D_
_x000D_
      <TextField_x000D_
        id="field1"_x000D_
        ..._x000D_
      />_x000D_
_x000D_
      <TextField_x000D_
        id="field2"_x000D_
        ..._x000D_
      />_x000D_
_x000D_
      <Button_x000D_
      ..._x000D_
      onClick={() => { printIt(document.getElementById('field1').value,_x000D_
      document.getElementById('field2').value)    _x000D_
      }}>_x000D_
_x000D_
_x000D_
//printIt.js_x000D_
_x000D_
export function printIt(text1, text2) {_x000D_
console.log('on button clicked');_x000D_
alert(text1);_x000D_
alert(text2);_x000D_
};
_x000D_
_x000D_
_x000D_

It works just fine.

How can you remove all documents from a collection with Mongoose?

DateTime.remove({}, callback) The empty object will match all of them.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I faced similar error, tried all the suggestions above, but did not resolve. what worked for me is this:

Right-click your Global.asax file and click View Markup. You will see the attribute Inherits="nadeem.MvcApplication". This means that your Global.asax file is trying to inherit from the type nadeem.MvcApplication.

Now double click your Global.asax file and see what the class name specified in your Global.asax.cs file is. It should look something like this:

namespace nadeem
{

public class MvcApplication: System.Web.HttpApplication
    {
    ....

But if it doesn't look like above, you will receive that error, The value in the Inherits attribute of your Global.asax file must match a type that is derived from System.Web.HttpApplication.

Check below link for more info:

Parser Error: Server Error in '/' Application

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

I had this problem with only with redirectMode="ResponseRewrite" (redirectMode="ResponseRedirect" worked fine) and none of the above solutions helped my resolve the issue. However, once I changed the server's application pool's "Managed Pipeline Mode" from "Classic" to "Integrated" the custom error page appeared as expected.

How to make custom error pages work in ASP.NET MVC 4

My current setup (on MVC3, but I think it still applies) relies on having an ErrorController, so I use:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error">
      <error redirect="~/Error/NotFound" statusCode="404" />
    </customErrors>
</system.web>

And the controller contains the following:

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;  //you may want to set this to 200
        return View("NotFound");
    }
}

And the views just the way you implement them. I tend to add a bit of logic though, to show the stack trace and error information if the application is in debug mode. So Error.cshtml looks something like this:

@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = "_Layout.cshtml";
    ViewBag.Title = "Error";
}
<div class="list-header clearfix">
    <span>Error</span>
</div>
<div class="list-sfs-holder">
    <div class="alert alert-error">
        An unexpected error has occurred. Please contact the system administrator.
    </div>
    @if (Model != null && HttpContext.Current.IsDebuggingEnabled)
    {
        <div>
            <p>
                <b>Exception:</b> @Model.Exception.Message<br />
                <b>Controller:</b> @Model.ControllerName<br />
                <b>Action:</b> @Model.ActionName
            </p>
            <div style="overflow:scroll">
                <pre>
                    @Model.Exception.StackTrace
                </pre>
            </div>
        </div>
    }
</div>

How to use google maps without api key

source

In June 2016 Google announced that they would stop supporting keyless usage, meaning any request that doesn’t include an API key or Client ID. This will go into effect on June 11 2018, and keyless access will no longer be supported

What does the ??!??! operator do in C?

Well, why this exists in general is probably different than why it exists in your example.

It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.

This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:

{ | } ~ 

The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.

Your example is actually two of ??!, each meaning |, so the result is ||.

However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.

It sure worked, it led to a wildly popular SO question.

ASR-33 Teletype

                                            ASR-33 Teletype


1. For that matter, the trigraphs were invented by the ANSI committee, which first met after C become a runaway success, so none of the original C code or coders would have used them.

The remote host closed the connection. The error code is 0x800704CD

As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).

There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:

http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm

The following stack-overflow post might also be of interest:

"The remote host closed the connection" in Response.OutputStream.Write

Check if process returns 0 with batch file

You can use below command to check if it returns 0 or 1 :

In below example, I am checking for the string in the one particular file which will give you 1 if that particular word "Error" is not present in the file and if present then 0

find /i "| ERROR1 |" C:\myfile.txt
echo %errorlevel%

if %errorlevel% equ 1 goto notfound
goto found
:notfound
exit 1
:found
echo we found the text.

how to play video from url

please check this link : http://developer.android.com/guide/appendix/media-formats.html

videoview can't support some codec .

i suggested you to use mediaplayer , when get "sorry , can't play video"

Server cannot set status after HTTP headers have been sent IIS7.5

I apologize, but I'm adding my 2 cents to the thread just in case anyone has the same problem.

  • I used Forms Authentication in my MVC app
  • But some controller-actions were "anonymous" i.e. allowed to non-authenticated users
  • Sometimes in those actions I would still want users to be redirected to the login form under some condition
  • to do that - I have this in my action method: return new HttpStatusCodeResult(401) - and ASP.NET is super nice to detect this, and it redirects the user to the login page! Magic, right? It even has the proper ReturnUrl parameter etc.

But you see where I'm getting here? I return 401. And ASP.NET redirects the user. Which is essentially returns 302. One status code is replaced with another.

And some IIS servers (just some!) throw this exception. Some don't. - I don't have it on my test serevr, only on my production server (ain't it always the case right o_O)

I know my answer is essentially repeating what's already said here, but sometimes it's just hard to figure out where this overwriting happens exactly.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

I try to get in the habit of using HostingEnvironment instead of Server as it works within the context of WCF services too.

 HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

I'm new in ASP.NET MVC. I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log)

@ModelType System.Web.Mvc.HandleErrorInfo

    @Code
        ViewData("Title") = "Error"
        Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
        //To log error with Elmah
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
    End Code

<h2>
    Sorry, an error occurred while processing your request.<br />

    @item.ActionName<br />
    @item.ControllerName<br />
    @item.Exception.Message
</h2> 

It is simply!

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

This error message can be thrown in the application logs when the actual issue is that the oracle database server ran out of space.

After correcting the space issue, this particular error message disappeared.

Show ImageView programmatically

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

You can also get a direct link to a view within a folder by using "TreeValue", "TreeField" and "RootFolder".

Example:

http://sharepoint/Docs/YourLibrary/Forms/YourView.aspx?RootFolder=MyFolder&TreeField=Folders&TreeValue=MyFolder

To further explain: I have a SharePoint site, with a docs library called YourLibrary. I have a folder called MyFolder. I created a view that can be used at any level of that Library structure with a URL path of YourView.aspx Using that link, it will take me to the view I created, with all the filters and styles, but only show the results that would occur in the contents of that folder in RootFolder and TreeValue.

Angular 5 ngHide ngShow [hidden] not working

There is two way for hide a element

  1. Use the "hidden" html attribute But in angular you can bind it with one or more fields like this :

    <input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">

2.Better way of doing this is to use " *ngIf " directive like this :

<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">

Now why this is a better way because it doesn't just hide the element, it will removes it from the html code so this will help your page to render.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

A different take with a simple jQuery plugin

Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.

This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.

You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.

All you have to do is to use this plugin on the client side. An Ajax request would look like this:

$.ajax({
    type: "POST",
    url: "SomeURL",
    data: $.toDictionary(yourComplexJSONobject),
    success: function() { ... },
    error: function() { ... }
});

But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.

Groovy built-in REST/HTTP client?

import groovyx.net.http.HTTPBuilder;

public class HttpclassgetrRoles {
     static void main(String[] args){
         def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')

         HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
         connection.addRequestProperty("Accept", "application/json")
         connection.with {
           doOutput = true
           requestMethod = 'GET'
           println content.text
         }

     }
}

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

How to check date of last change in stored procedure or function in SQL server

Try this for stored procedures:

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = 'myProc'

RESTful Authentication

It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST. Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.

The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in RFC 2617.

NumPy first and last element from array

I ended here, because I googled for "python first and last element of array", and found everything else but this. So here's the answer to the title question:

a = [1,2,3]
a[0] # first element (returns 1)
a[-1] # last element (returns 3)

How can I make a time delay in Python?

If you would like to put a time delay in a Python script:

Use time.sleep or Event().wait like this:

from threading import Event
from time import sleep

delay_in_sec = 2

# Use time.sleep like this
sleep(delay_in_sec)         # Returns None
print(f'slept for {delay_in_sec} seconds')

# Or use Event().wait like this
Event().wait(delay_in_sec)  # Returns False
print(f'waited for {delay_in_sec} seconds')

However, if you want to delay the execution of a function do this:

Use threading.Timer like this:

from threading import Timer

delay_in_sec = 2

def hello(delay_in_sec):
    print(f'function called after {delay_in_sec} seconds')

t = Timer(delay_in_sec, hello, [delay_in_sec])  # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start()  # Returns None
print("Started")

Outputs:

Started
function called after 2 seconds

Why use the later approach?

  • It does not stop execution of the whole script (except for the function you pass it).
  • After starting the timer you can also stop it by doing timer_obj.cancel().

Create a function with optional call variables

Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."

By default, all parameters are optional. The most basic approach is to simply check each one for $null, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.

If you want to learn about all of the special support that Powershell can give you, check out these links:

about_Functions

about_Functions_Advanced

about_Functions_Advanced_Parameters

What does git rev-parse do?

Just to elaborate on the etymology of the command name rev-parse, Git consistently uses the term rev in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list for example prints a list of 40-char commit hashes for a branch or whatever.

In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.

I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)

Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.

Rails :include vs. :joins

'joins' just used to join tables and when you called associations on joins then it will again fire query (it mean many query will fire)

lets suppose you have tow model, User and Organisation
User has_many organisations
suppose you have 10 organisation for a user 
@records= User.joins(:organisations).where("organisations.user_id = 1")
QUERY will be 
 select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1

it will return all records of organisation related to user
and @records.map{|u|u.organisation.name}
it run QUERY like 
select * from organisations where organisations.id = x then time(hwo many organisation you have)

total number of SQL is 11 in this case

But with 'includes' will eager load the included associations and add them in memory(load all associations on first load) and not fire query again

when you get records with includes like @records= User.includes(:organisations).where("organisations.user_id = 1") then query will be

select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
and 


 select * from organisations where organisations.id IN(IDS of organisation(1, to 10)) if 10 organisation
and when you run this 

@records.map{|u|u.organisation.name} no query will fire

Show / hide div on click with CSS

For a CSS-only solution, try using the checkbox hack. Basically, the idea is to use a checkbox and assign different styles based on whether the box is checked or not used the :checked pseudo selector. The checkbox can be hidden, if need be, by attaching it to a label.

link to dabblet (not mine): http://dabblet.com/gist/1506530

link to CSS Tricks article: http://css-tricks.com/the-checkbox-hack/

How do I get a list of files in a directory in C++?

I've just asked a similar question and here's my solution based on answer received (using boost::filesystem library):

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main()
{
    path p("D:/AnyFolder");
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {
        if (!is_directory(i->path())) //we eliminate directories in a list
        {
            cout << i->path().filename().string() << endl;
        }
        else
            continue;
    }
}

Output is like:

file1.txt
file2.dat

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

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

You should verify following things if the two way binding does not work.

In html the ngModel should be called this way. There is no dependency on other attribute of the input element

<input [(ngModel)]="inputText">

Make Sure FormsModule is imported into the modules file app.modules.ts

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

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent // suppose, this is the component in which you are trying to use two ay binding
    ],
    imports: [
        BrowserModule,
        FormsModule,
        // other modules
],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Make sure the component in which you are trying to use ngModel for two way binding is added in the declarations of the. Code added in the previous point #2

This is everything that you need to do to make the two way binding using ngModel work, this is validated up to angular 9

Pass array to ajax request in $.ajax()

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});

How to run bootRun with spring profile via gradle task

Spring Boot v2 Gradle plugin docs provide an answer:

6.1. Passing arguments to your application

Like all JavaExec tasks, arguments can be passed into bootRun from the command line using --args='<arguments>' when using Gradle 4.9 or later.

To run server with active profile set to dev:

$ ./gradlew bootRun --args='--spring.profiles.active=dev'

How can I do DNS lookups in Python, including referring to /etc/hosts?

The answer above was meant for Python 2. If you're using Python 3, here is the code.

>>> import socket
>>> print(socket.gethostbyname('google.com'))
8.8.8.8
>>>

Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

_x000D_
_x000D_
#container :nth-last-child(-n+2) {
  background-color: cyan;
}
_x000D_
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
_x000D_
_x000D_
_x000D_

Excel column number from column name

While you were looking for a VBA solution, this was my top result on google when looking for a formula solution, so I'll add this for anyone who came here for that like I did:

Excel formula to return the number from a column letter (From @A. Klomp's comment above), where cell A1 holds your column letter(s):

=column(indirect(A1&"1"))

As the indirect function is volatile, it recalculates whenever any cell is changed, so if you have a lot of these it could slow down your workbook. Consider another solution, such as the 'code' function, which gives you the number for an ASCII character, starting with 'A' at 65. Note that to do this you would need to check how many digits are in the column name, and alter the result depending on 'A', 'BB', or 'CCC'.

Excel formula to return the column letter from a number (From this previous question How to convert a column number (eg. 127) into an excel column (eg. AA), answered by @Ian), where A1 holds your column number:

=substitute(address(1,A1,4),"1","")

Note that both of these methods work regardless of how many letters are in the column name.

Hope this helps someone else.

How do you convert a jQuery object into a string?

No need to clone and add to the DOM to use .html(), you can do:

$('#item-of-interest').wrap('<div></div>').html()

How to search through all Git and Mercurial commits in the repository for a certain string?

Building on rq's answer, I found this line does what I want:

git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")

Which will report the commit ID, filename, and display the matching line, like this:

91ba969:testFile:this is a test

... Does anyone agree that this would be a nice option to be included in the standard git grep command?

How to create a collapsing tree table in html/css/js?

In modern browsers, you need only very little to code to create a collapsible tree :

_x000D_
_x000D_
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');_x000D_
for(var i = 0; i < tree.length; i++){_x000D_
    tree[i].addEventListener('click', function(e) {_x000D_
        var parent = e.target.parentElement;_x000D_
        var classList = parent.classList;_x000D_
        if(classList.contains("open")) {_x000D_
            classList.remove('open');_x000D_
            var opensubs = parent.querySelectorAll(':scope .open');_x000D_
            for(var i = 0; i < opensubs.length; i++){_x000D_
                opensubs[i].classList.remove('open');_x000D_
            }_x000D_
        } else {_x000D_
            classList.add('open');_x000D_
        }_x000D_
        e.preventDefault();_x000D_
    });_x000D_
}
_x000D_
body {_x000D_
    font-family: Arial;_x000D_
}_x000D_
_x000D_
ul.tree li {_x000D_
    list-style-type: none;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
ul.tree li ul {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
ul.tree li.open > ul {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
ul.tree li a {_x000D_
    color: black;_x000D_
    text-decoration: none;_x000D_
}_x000D_
_x000D_
ul.tree li a:before {_x000D_
    height: 1em;_x000D_
    padding:0 .1em;_x000D_
    font-size: .8em;_x000D_
    display: block;_x000D_
    position: absolute;_x000D_
    left: -1.3em;_x000D_
    top: .2em;_x000D_
}_x000D_
_x000D_
ul.tree li > a:not(:last-child):before {_x000D_
    content: '+';_x000D_
}_x000D_
_x000D_
ul.tree li.open > a:not(:last-child):before {_x000D_
    content: '-';_x000D_
}
_x000D_
<ul class="tree">_x000D_
  <li><a href="#">Part 1</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 2</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 3</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

PNG transparency issue in IE8

I put this into a jQuery plugin to make it more modular (you supply the transparent gif):

$.fn.pngFix = function() {
  if (!$.browser.msie || $.browser.version >= 9) { return $(this); }

  return $(this).each(function() {
    var img = $(this),
        src = img.attr('src');

    img.attr('src', '/images/general/transparent.gif')
        .css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + src + "')");
  });
};

Usage:

$('.my-selector').pngFix();

Note: It works also if your images are background images. Just apply the function on the div.

connecting to phpMyAdmin database with PHP/MySQL

$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');

How do you debug React Native?

If you use Nuclide in Atom editor for React Native App Development then you can also "Element Inspector" which helps in observing props and state values changes when app is running on device in development phase.

Know more about it here

enter image description here

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

To get AM/PM, Check if the hour portion is less than 12, then it is AM, else PM.

To get the hour, do (hour % 12) || 12.

This should do it:

var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;

http://jsfiddle.net/Skwt7/4/

That assumes that AM times are formatted as, eg, 08:00:00. If they are formatted without the leading zero, you would have to test the position of the first colon:

var hourEnd = timeString.indexOf(":");
var H = +timeString.substr(0, hourEnd);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(hourEnd, 3) + ampm;

http://jsfiddle.net/Skwt7/3/

Angular2: custom pipe could not be found

If you are declaring your pipe in another module, make sure to add it to that module Declarations and Exports array, then import that module in whatever module is consuming that pipe.

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

Index of Currently Selected Row in DataGridView

Use the Index property in your DGV's SelectedRows collection:

int index = yourDGV.SelectedRows[0].Index;

How to load a controller from another controller in codeigniter?

I was having session file not found error while tried various ways, finally achieved like this. Made the function as static (which I want to call in the another controller), and called like

require_once('Welcome.php');
Welcome::hello();

Push origin master error on new repository

This is very old question but for all new people who will end up here like me. This solution is only for

error: src refspec master does not match any.

error for new repo created

You need to add your

git config user.email "your email"
git config user.name "name"

Only after adding email and name add files to git and commit

git add .
git commit -m "message"

It will work like charm

Chrome says my extension's manifest file is missing or unreadable

Mine also was funny. While copypasting " manifest.json" from the tutorial, i also managed to copy a leading space. Couldn't get why it's not finding it.

XPath - Difference between node() and text()

Select the text of all items under produce:

//produce/item/text()

Select all the manager nodes in all departments:

//department/*

How do I call paint event?

Call control.invalidate and the paint event will be raised.

Redirecting to authentication dialog - "An error occurred. Please try again later"

Make sure your app is configured to use the appropriate URL & domain of your site. That may be it.

How do you make sure email you send programmatically is not automatically marked as spam?

Confirm that you have the correct email address before sending out emails. If someone gives the wrong email address on sign-up, beat them over the head about it ASAP.

Always include clear "how to unsubscribe" information in EVERY email. Do not require the user to login to unsubscribe, it should be a unique url for 1-click unsubscribe.

This will prevent people from marking your mails as spam because "unsubscribing" is too hard.

Listing all permutations of a string/integer

    /// <summary>
    /// Print All the Permutations.
    /// </summary>
    /// <param name="inputStr">input string</param>
    /// <param name="strLength">length of the string</param>
    /// <param name="outputStr">output string</param>
    private void PrintAllPermutations(string inputStr, int strLength,string outputStr, int NumberOfChars)
    {
        //Means you have completed a permutation.
        if (outputStr.Length == NumberOfChars)
        {
            Console.WriteLine(outputStr);                
            return;
        }

        //For loop is used to print permutations starting with every character. first print all the permutations starting with a,then b, etc.
        for(int i=0 ; i< strLength; i++)
        {
            // Recursive call : for a string abc = a + perm(bc). b+ perm(ac) etc.
            PrintAllPermutations(inputStr.Remove(i, 1), strLength - 1, outputStr + inputStr.Substring(i, 1), 4);
        }
    }        

How can I set the aspect ratio in matplotlib?

A simple option using plt.gca() to get current axes and set aspect

        plt.gca().set_aspect('equal')

in place of your last line

How do you run multiple programs in parallel from a bash script?

Your script should look like:

prog1 &
prog2 &
.
.
progn &
wait
progn+1 &
progn+2 &
.
.

Assuming your system can take n jobs at a time. use wait to run only n jobs at a time.

How do I add items to an array in jQuery?

You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.

The only way of achieving what you want is changing the ajax call to be synchronous. You can do this by using the .ajax and passing in asynch : false however this is not recommended as it locks the UI up until the call has returned, if it fails to return the user has to crash out of the browser.

Shortcut to create properties in Visual Studio?

Type P + Tab + Tab.

Change the datatype, press TAB, change the property name, and press End + Enter.

Get selected item value from Bootstrap DropDown with specific ID

The selector would be #demolist.dropdown-menu li a note no space between id and class. However i would suggest a more generic approach:

<div class="input-group">                                            
    <input type="TextBox" Class="form-control datebox"></input>
    <div class="input-group-btn">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>
    </ul>
</div>


$(document).on('click', '.dropdown-menu li a', function() {
    $(this).parent().parent().parent().find('.datebox').val($(this).html());
}); 

by using a class rather than id, and using parent().find(), you can have as many of these on a page as you like, with no duplicated js

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.

Programmatically set the initial view controller using Storyboards

Found simple solution - no need to remove "initial view controller check" from storyboard and editing project Info tab and use makeKeyAndVisible, just place

self.window.rootViewController = rootVC;

in

- (BOOL) application:didFinishLaunchingWithOptions:

How to run a SQL query on an Excel table?

You can experiment with the native DB driver for Excel in language/platform of your choice. In Java world, you can try with http://code.google.com/p/sqlsheet/ which provides a JDBC driver for working with Excel sheets directly. Similarly, you can get drivers for the DB technology for other platforms.

However, I can guarantee that you will soon hit a wall with the number of features these wrapper libraries provide. Better way will be to use Apache HSSF/POI or similar level of library but it will need more coding effort.

How to pass a URI to an intent?

you can store the uri as string

intent.putExtra("imageUri", imageUri.toString());

and then just convert the string back to uri like this

Uri myUri = Uri.parse(extras.getString("imageUri"));

How to enable explicit_defaults_for_timestamp?

I'm Using Windows 8.1 and I use this command

c:\wamp\bin\mysql\mysql5.6.12\bin\mysql.exe

instead of

 c:\wamp\bin\mysql\mysql5.6.12\bin\mysqld

and it works fine..

How do detect Android Tablets in general. Useragent?

The 51Degrees beta, 1.0.1.6 and the latest stable release 1.0.2.2 (4/28/2011) now have the ability to sniff for tablet. Basically along the lines of:

string capability = Request.Browser["is_tablet"];

Hope this helps you.

How do I get the full path of the current file's directory?

import os
print os.path.dirname(__file__)

Rollback to an old Git commit in a public repo

Try this:

git checkout [revision] .

where [revision] is the commit hash (for example: 12345678901234567890123456789012345678ab).

Don't forget the . at the end, very important. This will apply changes to the whole tree. You should execute this command in the git project root. If you are in any sub directory, then this command only changes the files in the current directory. Then commit and you should be good.

You can undo this by

git reset --hard 

that will delete all modifications from the working directory and staging area.

Have log4net use application config file for configuration data

Add a line to your app.config in the configSections element

<configSections>
 <section name="log4net" 
   type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, 
         Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>

Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...

<log4net configSource="Config\Log4Net.config" />

In your application code, when you create the log, write

private static ILog GetLog(string logName)
{
    ILog log = LogManager.GetLogger(logName);
    return log;
}

How to represent matrices in python

If you are not going to use the NumPy library, you can use the nested list. This is code to implement the dynamic nested list (2-dimensional lists).

Let r is the number of rows

let r=3

m=[]
for i in range(r):
    m.append([int(x) for x in raw_input().split()])

Any time you can append a row using

m.append([int(x) for x in raw_input().split()])

Above, you have to enter the matrix row-wise. To insert a column:

for i in m:
    i.append(x) # x is the value to be added in column

To print the matrix:

print m       # all in single row

for i in m:
    print i   # each row in a different line

How do I use cx_freeze?

I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:

from cx_Freeze import setup, Executable
import sys

productName = "ProductName"
if 'bdist_msi' in sys.argv:
    sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
    sys.argv += ['--install-script', 'install.py']

exe = Executable(
      script="main.py",
      base="Win32GUI",
      targetName="Product.exe"
     )
setup(
      name="Product.exe",
      version="1.0",
      author="Me",
      description="Copyright 2012",
      executables=[exe],
      scripts=[
               'install.py'
               ]
      ) 

Linq on DataTable: select specific column into datatable, not whole table

Here I get only three specific columns from mainDataTable and use the filter

DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");

How to get the difference between two dictionaries in Python?

def flatten_it(d):
    if isinstance(d, list) or isinstance(d, tuple):
        return tuple([flatten_it(item) for item in d])
    elif isinstance(d, dict):
        return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
    else:
        return d

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}

print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or 
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])

Define css class in django Forms

If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from forms.ModelForm, and then inherit from it

class BaseForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BaseForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'someClass'


class WhateverForm(BaseForm):
    class Meta:
        model = SomeModel

This helped me to add the 'form-control' class to all of the fields on all of the forms of my application automatically, without adding replication of code.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

Another way is to check the results of

sp_help 'TableName'

(or just highlight the quoted TableName and pres ALT+F1)

With time passing, I just decided to refine my answer. Below is a screenshot of the results that sp_help provides. A have used the AdventureWorksDW2012 DB for this example. There is numerous good information there, and what we are looking for is at the very end - highlighted in green:

enter image description here

Java Loop every minute

Use Thread.sleep(long millis).

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.


For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

Browser: Identifier X has already been declared

Remember that window is the global namespace. These two lines attempt to declare the same variable:

window.APP = { ... }
const APP = window.APP

The second definition is not allowed in strict mode (enabled with 'use strict' at the top of your file).

To fix the problem, simply remove the const APP = declaration. The variable will still be accessible, as it belongs to the global namespace.

Java : Cannot format given Object as a Date

This worked for me:

String dat="02/08/2017";
long date=new SimpleDateFormat("dd/MM/yyyy").parse(dat,newParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(date);
System.out.println(dbDate);

How to correctly dismiss a DialogFragment?

Kotlin Version of Terel answer

(fragmentManager.findFragmentByTag(TAG) as? DialogFragment)?.dismiss()

How to pass List<String> in post method using Spring MVC?

I had the same use case, You can change your method defination in the following way :

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody Map<String,List<String>> fruits) {
    ..
}

The only problem is it accepts any key in place of "fruits" but You can easily get rid of a wrapper if it is not big functionality.

How to read/write a boolean when implementing the Parcelable interface?

out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read

ModalPopupExtender OK Button click event not firing?

I was just searching for a solution for this :)

it appears that you can't have OkControlID assign to a control if you want to that control fires an event, just removing this property I got everything working again.

my code (working):

<asp:Panel ID="pnlResetPanelsView" CssClass="modalPopup" runat="server" Style="display:none;">
    <h2>
        Warning</h2>
    <p>
        Do you really want to reset the panels to the default view?</p>
    <div style="text-align: center;">
        <asp:Button ID="btnResetPanelsViewOK" Width="60" runat="server" Text="Yes" 
            CssClass="buttonSuperOfficeLayout" OnClick="btnResetPanelsViewOK_Click" />&nbsp;
        <asp:Button ID="btnResetPanelsViewCancel" Width="60" runat="server" Text="No" CssClass="buttonSuperOfficeLayout" />
    </div>
</asp:Panel>
<ajax:ModalPopupExtender ID="mpeResetPanelsView" runat="server" TargetControlID="btnResetView"
    PopupControlID="pnlResetPanelsView" BackgroundCssClass="modalBackground" DropShadow="true"
    CancelControlID="btnResetPanelsViewCancel" />

php exec command (or similar) to not wait for result

You can run the command in the background by adding a & at the end of it as:

exec('run_baby_run &');

But doing this alone will hang your script because:

If a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So you can redirect the stdout of the command to a file, if you want to see it later or to /dev/null if you want to discard it as:

exec('run_baby_run > /dev/null &');

How can I get dictionary key as variable directly in Python (not by searching from value)?

if you just need to get a key-value from a simple dictionary like e.g:

os_type = {'ubuntu': '20.04'}

use popitem() method:

os, version = os_type.popitem()
print(os) # 'ubuntu'
print(version) # '20.04'

How to "scan" a website (or page) for info, and bring it into my program?

My answer won't probably be useful to the writer of this question (I am 8 months late so not the right timing I guess) but I think it will probably be useful for many other developers that might come across this answer.

Today, I just released (in the name of my company) an HTML to POJO complete framework that you can use to map HTML to any POJO class with simply some annotations. The library itself is quite handy and features many other things all the while being very pluggable. You can have a look to it right here : https://github.com/whimtrip/jwht-htmltopojo

How to use : Basics

Imagine we need to parse the following html page :

<html>
    <head>
        <title>A Simple HTML Document</title>
    </head>
    <body>
        <div class="restaurant">
            <h1>A la bonne Franquette</h1>
            <p>French cuisine restaurant for gourmet of fellow french people</p>
            <div class="location">
                <p>in <span>London</span></p>
            </div>
            <p>Restaurant n*18,190. Ranked 113 out of 1,550 restaurants</p>  
            <div class="meals">
                <div class="meal">
                    <p>Veal Cutlet</p>
                    <p rating-color="green">4.5/5 stars</p>
                    <p>Chef Mr. Frenchie</p>
                </div>

                <div class="meal">
                    <p>Ratatouille</p>
                    <p rating-color="orange">3.6/5 stars</p>
                    <p>Chef Mr. Frenchie and Mme. French-Cuisine</p>
                </div>

            </div> 
        </div>    
    </body>
</html>

Let's create the POJOs we want to map it to :

public class Restaurant {

    @Selector( value = "div.restaurant > h1")
    private String name;

    @Selector( value = "div.restaurant > p:nth-child(2)")
    private String description;

    @Selector( value = "div.restaurant > div:nth-child(3) > p > span")    
    private String location;    

    @Selector( 
        value = "div.restaurant > p:nth-child(4)"
        format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
        indexForRegexPattern = 1,
        useDeserializer = true,
        deserializer = ReplacerDeserializer.class,
        preConvert = true,
        postConvert = false
    )
    // so that the number becomes a valid number as they are shown in this format : 18,190
    @ReplaceWith(value = ",", with = "")
    private Long id;

    @Selector( 
        value = "div.restaurant > p:nth-child(4)"
        format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
        // This time, we want the second regex group and not the first one anymore
        indexForRegexPattern = 2,
        useDeserializer = true,
        deserializer = ReplacerDeserializer.class,
        preConvert = true,
        postConvert = false
    )
    // so that the number becomes a valid number as they are shown in this format : 18,190
    @ReplaceWith(value = ",", with = "")
    private Integer rank;

    @Selector(value = ".meal")    
    private List<Meal> meals;

    // getters and setters

}

And now the Meal class as well :

public class Meal {

    @Selector(value = "p:nth-child(1)")
    private String name;

    @Selector(
        value = "p:nth-child(2)",
        format = "^([0-9.]+)\/5 stars$",
        indexForRegexPattern = 1
    )
    private Float stars;

    @Selector(
        value = "p:nth-child(2)",
        // rating-color custom attribute can be used as well
        attr = "rating-color"
    )
    private String ratingColor;

    @Selector(
        value = "p:nth-child(3)"
    )
    private String chefs;

    // getters and setters.
}

We provided some more explanations on the above code on our github page.

For the moment, let's see how to scrap this.

private static final String MY_HTML_FILE = "my-html-file.html";

public static void main(String[] args) {


    HtmlToPojoEngine htmlToPojoEngine = HtmlToPojoEngine.create();

    HtmlAdapter<Restaurant> adapter = htmlToPojoEngine.adapter(Restaurant.class);

    // If they were several restaurants in the same page, 
    // you would need to create a parent POJO containing
    // a list of Restaurants as shown with the meals here
    Restaurant restaurant = adapter.fromHtml(getHtmlBody());

    // That's it, do some magic now!

}


private static String getHtmlBody() throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(MY_HTML_FILE));
    return new String(encoded, Charset.forName("UTF-8"));

}

Another short example can be found here

Hope this will help someone out there!

What is the recommended way to delete a large number of items from DynamoDB?

My approach to delete all rows from a table i DynamoDb is just to pull all rows out from the table, using DynamoDbs ScanAsync and then feed the result list to DynamoDbs AddDeleteItems. Below code in C# works fine for me.

        public async Task DeleteAllReadModelEntitiesInTable()
    {
        List<ReadModelEntity> readModels;

        var conditions = new List<ScanCondition>();
        readModels = await _context.ScanAsync<ReadModelEntity>(conditions).GetRemainingAsync();

        var batchWork = _context.CreateBatchWrite<ReadModelEntity>();
        batchWork.AddDeleteItems(readModels);
        await batchWork.ExecuteAsync();
    }

Note: Deleting the table and then recreating it again from the web console may cause problems if using YAML/CloudFormation to create the table.

An Authentication object was not found in the SecurityContext - Spring 3.2.2

I had the same problem when and I solved it by using the following annotation :

@EnableAutoConfiguration(exclude = {
        SecurityAutoConfiguration.class
})
public class Application {...}

I think the behavior is the same as what Abhishek explained

Simplest way to do a recursive self-join?

Check following to help the understand the concept of CTE recursion

DECLARE
@startDate DATETIME,
@endDate DATETIME

SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'

; WITH CTE AS (
    SELECT
        YEAR(@startDate) AS 'yr',
        MONTH(@startDate) AS 'mm',
        DATENAME(mm, @startDate) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        @startDate 'new_date'
    UNION ALL
    SELECT
        YEAR(new_date) AS 'yr',
        MONTH(new_date) AS 'mm',
        DATENAME(mm, new_date) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        DATEADD(d,1,new_date) 'new_date'
    FROM CTE
    WHERE new_date < @endDate
    )
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)

Call async/await functions in parallel

I've created a gist testing some different ways of resolving promises, with results. It may be helpful to see the options that work.

How to get the version of ionic framework?

ionic info

This will give you the ionic version,node, npm and os.

If you need only ionic version use ionic -v.

If your project's development ionic version and your global versions are different then check them by using the below commands.

To check the globally installed ionic version ionic -g and to check the project's ionic version use ionic -g.

To check the project's ionic version use ionic -v in your project path or else ionic info to get the details of ionic and its dependencies.

using javascript to detect whether the url exists before display in iframe

I found this worked in my scenario.

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

$.get("urlToCheck.com").done(function () {
  alert("success");
}).fail(function () {
   alert("failed.");
});

Convert float to std::string in C++

If you're worried about performance, check out the Boost::lexical_cast library.

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

Java switch statement multiple cases

This is possible with switch enhancements in Java 14. Following is a fairly intuitive example of how the same can be achieved.

switch (month) {
    case 1, 3, 5, 7, 8, 10, 12 -> System.out.println("this month has 31 days");
    case 4, 6, 9 -> System.out.println("this month has 30 days");
    case 2 -> System.out.println("February can have 28 or 29 days");
    default -> System.out.println("invalid month");
}

Twitter Bootstrap dropdown menu

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- core CSS -->
    <link href="http://webdesign9.in/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://webdesign9.in/css/font-awesome.min.css" rel="stylesheet">
    <link href="http://webdesign9.in/css/responsive.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
    <![endif]-->       
</head><!--/head-->
<body class="homepage">
    <header id="header">
        <nav class="navbar navbar-inverse" role="banner">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" title="Web Design Company in Mumbai" href="index.php"><img src="images/logo.png" alt="The Best Web Design Company in Mumbai" /></a>
                </div>
                <div class="collapse navbar-collapse navbar-right">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="index.php">Home</a></li>
                        <li><a href="about.php">About Us</a></li>
                        <li><a href="services.php">Services</a></li>
                        <li><a href="term-condition.php">Terms &amp; Condition</a></li></li>
                        <li><a href="contact.php">Contact</a></li>                        
                    </ul>
                </div>
            </div><!--/.container-->
        </nav><!--/nav-->
    </header><!--/header-->
    <script src="http://webdesign9.in/js/jquery.js"></script>
    <script src="http://webdesign9.in/js/bootstrap.min.js"></script>
</body>
</html>

How do I encrypt and decrypt a string in python?

I had troubles compiling all the most commonly mentioned cryptography libraries on my Windows 7 system and for Python 3.5.

This is the solution that finally worked for me.

from cryptography.fernet import Fernet
key = Fernet.generate_key() #this is your "password"
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(b"Hello stackoverflow!")
decoded_text = cipher_suite.decrypt(encoded_text)

Capturing standard out and error with Start-Process

To get both stdout and stderr, I use:

Function GetProgramOutput([string]$exe, [string]$arguments)
{
    $process = New-Object -TypeName System.Diagnostics.Process
    $process.StartInfo.FileName = $exe
    $process.StartInfo.Arguments = $arguments

    $process.StartInfo.UseShellExecute = $false
    $process.StartInfo.RedirectStandardOutput = $true
    $process.StartInfo.RedirectStandardError = $true
    $process.Start()

    $output = $process.StandardOutput.ReadToEnd()   
    $err = $process.StandardError.ReadToEnd()

    $process.WaitForExit()

    $output
    $err
}

$exe = "cmd"
$arguments = '/c echo hello 1>&2'   #this writes 'hello' to stderr

$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]

[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)

How to query as GROUP BY in django?

The following module allows you to group Django models and still work with a QuerySet in the result: https://github.com/kako-nawao/django-group-by

For example:

from django_group_by import GroupByMixin

class BookQuerySet(QuerySet, GroupByMixin):
    pass

class Book(Model):
    title = TextField(...)
    author = ForeignKey(User, ...)
    shop = ForeignKey(Shop, ...)
    price = DecimalField(...)

class GroupedBookListView(PaginationMixin, ListView):
    template_name = 'book/books.html'
    model = Book
    paginate_by = 100

    def get_queryset(self):
        return Book.objects.group_by('title', 'author').annotate(
            shop_count=Count('shop'), price_avg=Avg('price')).order_by(
            'name', 'author').distinct()

    def get_context_data(self, **kwargs):
        return super().get_context_data(total_count=self.get_queryset().count(), **kwargs)

'book/books.html'

<ul>
{% for book in object_list %}
    <li>
        <h2>{{ book.title }}</td>
        <p>{{ book.author.last_name }}, {{ book.author.first_name }}</p>
        <p>{{ book.shop_count }}</p>
        <p>{{ book.price_avg }}</p>
    </li>
{% endfor %}
</ul>

The difference to the annotate/aggregate basic Django queries is the use of the attributes of a related field, e.g. book.author.last_name.

If you need the PKs of the instances that have been grouped together, add the following annotation:

.annotate(pks=ArrayAgg('id'))

NOTE: ArrayAgg is a Postgres specific function, available from Django 1.9 onwards: https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg

Disable asp.net button after click to prevent double clicking

You can use the client-side onclick event to do that:

yourButton.Attributes.Add("onclick", "this.disabled=true;");

Trigger Change event when the Input value changed programmatically?

If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));

Swift performSelector:withObject:afterDelay: is unavailable

Swift is statically typed so the performSelector: methods are to fall by the wayside.

Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.

EDIT: the relevant performSelector: is also notably missing from the Swift version of the NSRunLoop documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject I'd argue it's pretty clear what Apple is thinking here.

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

VBA using ubound on a multidimensional array

Looping D3 ways;

Sub SearchArray()
    Dim arr(3, 2) As Variant
    arr(0, 0) = "A"
    arr(0, 1) = "1"
    arr(0, 2) = "w"

    arr(1, 0) = "B"
    arr(1, 1) = "2"
    arr(1, 2) = "x"

    arr(2, 0) = "C"
    arr(2, 1) = "3"
    arr(2, 2) = "y"

    arr(3, 0) = "D"
    arr(3, 1) = "4"
    arr(3, 2) = "z"

    Debug.Print "Loop Dimension 1"
    For i = 0 To UBound(arr, 1)
        Debug.Print "arr(" & i & ", 0) is " & arr(i, 0)
    Next i
    Debug.Print ""

    Debug.Print "Loop Dimension 2"
    For j = 0 To UBound(arr, 2)
        Debug.Print "arr(0, " & j & ") is " & arr(0, j)
    Next j
    Debug.Print ""

    Debug.Print "Loop Dimension 1 and 2"
    For i = 0 To UBound(arr, 1)
        For j = 0 To UBound(arr, 2)
            Debug.Print "arr(" & i & ", " & j & ") is " & arr(i, j)
        Next j
    Next i
    Debug.Print ""

End Sub

What does file:///android_asset/www/index.html mean?

It took me more than 4 hours to fix this problem. I followed the guide from http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

I'm using Android Studio (Eclipse with ADT could not work properly because of the build problem).

Solution that worked for me:

  1. I put the /assets/www/index.html under app/src/main/assets directory. (take care AndroidStudio has different perspectives like Project or Android)

  2. use super.loadUrl("file:///android_asset/www/index.html"); instead of super.loadUrl("file:///android_assets/www/index.html"); (no s)

How to "test" NoneType in python?

As pointed out by Aaron Hall's comment:

Since you can't subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.


Original Answer:

The simplest way however, without the extra line in addition to cardamom's answer is probably:
isinstance(x, type(None))

So how can I question a variable that is a NoneType? I need to use if method

Using isinstance() does not require an is within the if-statement:

if isinstance(x, type(None)): 
    #do stuff

Additional information
You can also check for multiple types in one isinstance() statement as mentioned in the documentation. Just write the types as a tuple.

isinstance(x, (type(None), bytes))

How to use log4net in Asp.net core 2.0

Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log folder and also to the console. Note the log4net.config must exist in the solution root (whereas in my case, my app root is a subfolder).

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger - %message%newline" />
      </layout>
  </appender>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="logs/" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>
    </root>
</log4net>

Another note, the traditional way of setting the XML up within app.config did not work:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net> ...

For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"].

Highlight Bash/shell code in Markdown files

I found a good description at Markdown Cheatsheet:

Code blocks are part of the Markdown spec, but syntax highlighting isn't.

However, many renderers -- like GitHub's and Markdown Here -- support syntax highlighting. Which languages are supported and how those language names should be written will vary from renderer to renderer. Markdown Here supports highlighting for dozens of languages (and not-really-languages, like diffs and HTTP headers); to see the complete list, and how to write the language names, see the highlight.js demo page.

Although I could not find any official GitHub documentation about using highlight.js, I've tested lots of languages and seemed to be working

To see list of languages I used https://github.com/highlightjs/highlight.js/blob/master/SUPPORTED_LANGUAGES.md

Some shell samples:

Shell:      console, shell
Bash:       bash, sh, zsh
PowerShell: powershell, ps
DOS:        dos, bat, cmd

Example:

```bat
cd \
copy a b
ping 192.168.0.1
```

How do I add a library path in cmake?

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

Maven compile with multiple src directories

This worked for me

<build>
    <sourceDirectory>.</sourceDirectory>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
        <includes>
            <include>src/main/java/**/*.java</include>
            <include>src/main2/java/**/*.java</include>
        </includes>
        </configuration>
        </plugin>
    </plugins>
</build>

Is it possible to disable the network in iOS Simulator?

One probably crazy idea or patch :

Just toggle the flag of network reachability

This is code which I use to toggle my flag runtime by triggering 'Simulator Memory Warning' and its COMPLETELY SAFE, just make sure code should be in DEBUG Mode only

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application 
{
#ifdef DEBUG
    isInternetAvailable = !isInternetAvailable;
#endif 
}

Dynamically changing font size of UILabel

It's 2015. I had to go to find a blog post that would explain how to do it for the latest version of iOS and XCode with Swift so that it would work with multiple lines.

  1. set “Autoshrink” to “Minimum font size.”
  2. set the font to the largest desirable font size (I chose 20)
  3. Change “Line Breaks” from “Word Wrap” to “Truncate Tail.”

Source: http://beckyhansmeyer.com/2015/04/09/autoshrinking-text-in-a-multiline-uilabel/

How to select rows from a DataFrame based on column values

To select rows whose column value equals a scalar, some_value, use ==:

df.loc[df['column_name'] == some_value]

To select rows whose column value is in an iterable, some_values, use isin:

df.loc[df['column_name'].isin(some_values)]

Combine multiple conditions with &:

df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]

Note the parentheses. Due to Python's operator precedence rules, & binds more tightly than <= and >=. Thus, the parentheses in the last example are necessary. Without the parentheses

df['column_name'] >= A & df['column_name'] <= B

is parsed as

df['column_name'] >= (A & df['column_name']) <= B

which results in a Truth value of a Series is ambiguous error.


To select rows whose column value does not equal some_value, use !=:

df.loc[df['column_name'] != some_value]

isin returns a boolean Series, so to select rows whose value is not in some_values, negate the boolean Series using ~:

df.loc[~df['column_name'].isin(some_values)]

For example,

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  bar    two  5  10
# 6  foo    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

yields

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

If you have multiple values you want to include, put them in a list (or more generally, any iterable) and use isin:

print(df.loc[df['B'].isin(['one','three'])])

yields

     A      B  C   D
0  foo    one  0   0
1  bar    one  1   2
3  bar  three  3   6
6  foo    one  6  12
7  foo  three  7  14

Note, however, that if you wish to do this many times, it is more efficient to make an index first, and then use df.loc:

df = df.set_index(['B'])
print(df.loc['one'])

yields

       A  C   D
B              
one  foo  0   0
one  bar  1   2
one  foo  6  12

or, to include multiple values from the index use df.index.isin:

df.loc[df.index.isin(['one','two'])]

yields

       A  C   D
B              
one  foo  0   0
one  bar  1   2
two  foo  2   4
two  foo  4   8
two  bar  5  10
one  foo  6  12

Jackson with JSON: Unrecognized field, not marked as ignorable

This just perfectly worked for me

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(
    DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

@JsonIgnoreProperties(ignoreUnknown = true) annotation did not.

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

The target principal name is incorrect. Cannot generate SSPI context

I had this problem and it grabbed my around 4-5 hours to find the root cause of this error message. Only difference is, i was getting this error while connecting DB from Visual Studio only, not direct via SQL Server Management Studio.

Reason behind error is, my application was hosted on local IIS and I had changed my system password one day ago, but didn't update it to IIS Application Pool of my hosted application.

I went to IIS, clicked on application pools, in pool list right click on appropriate app pool, go to "Advanced Settings", select "Identity" and changed its value (Domain\AccountName & New Password) under "Custom Account" and it solved my problem.

Thanks

How can I read the contents of an URL with Python?

# retrieving data from url
# only for python 3

import urllib.request

def main():
  url = "http://docs.python.org"

# retrieving data from URL
  webUrl = urllib.request.urlopen(url)
  print("Result code: " + str(webUrl.getcode()))

# print data from URL 
  print("Returned data: -----------------")
  data = webUrl.read().decode("utf-8")
  print(data)

if __name__ == "__main__":
  main()

Can't use WAMP , port 80 is used by IIS 7.5

Google search of "remove iis from port 80" leads here currently. Instead of removing IIS, here are the steps to just stop IIS from listening on port 80:

STEP 1: Open IIS Window. You can do this by, simply hitting the ‘Windows’ key and typing in ‘IIS’ or ‘Internet Information Services’. The result will be shown up there. Click it, you will get the window opened for you.

STEP 2: On the ‘Connections’ pane, click the default one to expand it. Usually (PC-NAME(PC-NAME\user), where ‘PC-NAME’ is your PC name, and ‘user’ is the username.

STEP 3: Click ‘Sites’ and expand it. Now select ‘Default Web Site’. On the ‘Actions’ pane, click ‘Bindings’ under the ‘Edit Site’.

STEP 4: Now a window named ‘Site Binding Opens. Click ‘http’ and then click edit. Change the port to another number, say 8000 and click ‘Ok’.

How to convert from []byte to int in Go Programming

var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

In my case, i had deleted the original branch from which my current branch derived from. So in the .git/config file i had:

[branch "simil2.1.12"]
    remote = origin
    merge = refs/heads/simil2.0.5
    rebase = false

the simil2.0.5 was deleted. I replaced it with the same branch name:

[branch "simil2.1.12"]
    remote = origin
    merge = refs/heads/simil2.1.12
    rebase = false

and it worked

How to color System.out.println output?

I created a jar library called JCDP (Java Colored Debug Printer).

For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive.

For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.

This library is licensed under the MIT License so feel free to use it.

Have a look at JCDP's github repository.

Run R script from command line

How to run Rmd in command with knitr and rmarkdown by multiple commands and then Upload an HTML file to RPubs

Here is a example: load two libraries and run a R command

R -e 'library("rmarkdown");library("knitr");rmarkdown::render("NormalDevconJuly.Rmd")'

R -e 'library("markdown");rpubsUpload("normalDev","NormalDevconJuly.html")'

How do I change an HTML selected option using JavaScript?

mySelect.value = myValue;

Where mySelect is your selection box, and myValue is the value you want to change it to.

How do I create a user account for basic authentication?

Right click on Computer and choose "Manage" (or go to Control Panel > Administrative Tools > Computer Management) and under "Local Users and Groups" you can add a new user. Then, give that user permission to read the directory where the site is hosted.

Note: After creating the user, be sure to edit the user and remove all roles.

Where is SQL Server Management Studio 2012?

Run PowerShell and type:

gci -Path "C:\Program Files*\Microsoft SQL Server" -Recurse -Include "Ssms.exe" | Select -ExpandProperty FullName

What do "branch", "tag" and "trunk" mean in Subversion repositories?

Trunk : After the completion of every sprint in agile we come out with a partially shippable product. These releases are kept in trunk.

Branches : All parallel developments codes for each ongoing sprint are kept in branches.

Tags : Every time we release a partially shippable product kind of beta version, we make a tag for it. This gives us the code that was available at that point of time, allowing us to go back at that state if required at some point during development.

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

What finally worked for me (Grails now works smoothly) is doing almost like Steve B. has pointed out:

JAVA_HOME=/usr/lib/jvm/default-java

This way if the user changes the default JDK for the system, JAVA_HOME still works.

default-java is a symlink to the current JVM.

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

To kill the puma process first run

    lsof -wni tcp:3000 

to show what is using port 3000. Then use the PID that comes with the result to run the kill process.

For example after running lsof -wni tcp:3000 you might get something like

    COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
    ruby    3366 dummy    8u  IPv4  16901      0t0  TCP 127.0.0.1:3000 (LISTEN)

Now run the following to kill the process. (where 3366 is the PID)

kill -9 3366

Should resolve the issue

How to import local packages in go?

Local package is a annoying problem in go.

For some projects in our company we decide not use sub packages at all.

  • $ glide install
  • $ go get
  • $ go install

All work.

For some projects we use sub packages, and import local packages with full path:

import "xxxx.gitlab.xx/xxgroup/xxproject/xxsubpackage

But if we fork this project, then the subpackages still refer the original one.

Check if a varchar is a number (TSQL)

I ran into the need to allow decimal values, so I used not Value like '%[^0-9.]%'

How do I get list of all tables in a database using TSQL?

SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017 or 2019:

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

To show only tables from a particular database

SELECT TABLE_NAME 
FROM [<DATABASE_NAME>].INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE'

Or,

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE' 
    AND TABLE_CATALOG='dbName' --(for MySql, use: TABLE_SCHEMA='dbName' )

PS: For SQL Server 2000:

SELECT * FROM sysobjects WHERE xtype='U' 

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

How do I use FileSystemObject in VBA?

These guys have excellent examples of how to use the filesystem object http://www.w3schools.com/asp/asp_ref_filesystem.asp

<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%> 

Temporary tables in stored procedures

Use @temp tables whenever possible--that is, you only need one primary key and you do not need to access the data from a subordinate stored proc.

Use #temp tables if you need to access the data from a subordinate stored proc (it is an evil global variable to the stored proc call chain) and you have no other clean way to pass the data between stored procs. Also use it if you need a secondary index (although, really ask yourself if it is a #temp table if you need more than one index)

If you do this, always declare your #temp table at the top of the function. SQL will force a recompile of your stored proc when it sees the create table statement....so if you have the #temp table declaration in the middle of the stored proc, you stored proc must stop processing and recompile.

How to pass parameter to a promise function

You can use .bind() to pass the param(this) to the function.

var someFunction =function(resolve, reject) {
  /* get username, password*/
  var username=this.username;
  var password=this.password;
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));

How to change letter spacing in a Textview?

This answer is based on Pedro's answer but adjusted so it also works if text attribute is already set:

package nl.raakict.android.spc.widget;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ScaleXSpan;
import android.util.AttributeSet;
import android.widget.TextView;


public class LetterSpacingTextView extends TextView {
    private float letterSpacing = LetterSpacing.BIGGEST;
    private CharSequence originalText = "";


    public LetterSpacingTextView(Context context) {
        super(context);
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs){
        super(context, attrs);
        originalText = super.getText();
        applyLetterSpacing();
        this.invalidate();
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
    }

    public float getLetterSpacing() {
        return letterSpacing;
    }

    public void setLetterSpacing(float letterSpacing) {
        this.letterSpacing = letterSpacing;
        applyLetterSpacing();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        applyLetterSpacing();
    }

    @Override
    public CharSequence getText() {
        return originalText;
    }

    private void applyLetterSpacing() {
        if (this == null || this.originalText == null) return;
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < originalText.length(); i++) {
            String c = ""+ originalText.charAt(i);
            builder.append(c.toLowerCase());
            if(i+1 < originalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());
        if(builder.toString().length() > 1) {
            for(int i = 1; i < builder.toString().length(); i+=2) {
                finalText.setSpan(new ScaleXSpan((letterSpacing+1)/10), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        super.setText(finalText, BufferType.SPANNABLE);
    }

    public class LetterSpacing {
        public final static float NORMAL = 0;
        public final static float NORMALBIG = (float)0.025;
        public final static float BIG = (float)0.05;
        public final static float BIGGEST = (float)0.2;
    }
}

If you want to use it programatically:

LetterSpacingTextView textView = new LetterSpacingTextView(context);
textView.setSpacing(10); //Or any float. To reset to normal, use 0 or LetterSpacingTextView.Spacing.NORMAL
textView.setText("My text");
//Add the textView in a layout, for instance:
((LinearLayout) findViewById(R.id.myLinearLayout)).addView(textView);

What is the size limit of a post request?

It depends on a server configuration. If you're working with PHP under Linux or similar, you can control it using .htaccess configuration file, like so:

#set max post size
php_value post_max_size 20M

And, yes, I can personally attest to the fact that this works :)

If you're using IIS, I don't have any idea how you'd set this particular value.

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.

SELECT 
a.[CUSTOMER ID], 
a.[NAME], 
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a

What is the proper way to URL encode Unicode characters?

IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.

Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

We see this a lot with OAuth2 integrations. We provide API services to our Customers, and they'll naively try to put their private key into an AJAX call. This is really poor security. And well-coded API Gateways, backends for frontend, and other such proxies, do not allow this. You should get this error.

I will quote @aspillers comment and change a single word: "Access-Control-Allow-Origin is a header sent in a server response which indicates IF the client is allowed to see the contents of a result".

ISSUE: The problem is that a developer is trying to include their private key inside a client-side (browser) JavaScript request. They will get an error, and this is because they are exposing their client secret.

SOLUTION: Have the JavaScript web application talk to a backend service that holds the client secret securely. That backend service can authenticate the web app to the OAuth2 provider, and get an access token. Then the web application can make the AJAX call.

Is it possible to get all arguments of a function as single object inside that function?

As many other pointed out, arguments contains all the arguments passed to a function.

If you want to call another function with the same args, use apply

Example:

var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);
  }
}

debug("message", "another argument")

Multipart forms from C# client

Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)

To send the data:

HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://you.url.here");
oRequest.ContentType = "multipart/form-data; boundary=" + PostData.boundary;
oRequest.Method = "POST";
PostData pData = new PostData();
Encoding encoding = Encoding.UTF8;
Stream oStream = null;

/* ... set the parameters, read files, etc. IE:
   pData.Params.Add(new PostDataParam("email", "[email protected]", PostDataParamType.Field));
   pData.Params.Add(new PostDataParam("fileupload", "filename.txt", "filecontents" PostDataParamType.File));
*/

byte[] buffer = encoding.GetBytes(pData.GetPostData());

oRequest.ContentLength = buffer.Length;

oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();

HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();

The PostData class should look like:

public class PostData
{
    // Change this if you need to, not necessary
    public static string boundary = "AaB03x";

    private List<PostDataParam> m_Params;

    public List<PostDataParam> Params
    {
        get { return m_Params; }
        set { m_Params = value; }
    }

    public PostData()
    {
        m_Params = new List<PostDataParam>();
    }

    /// <summary>
    /// Returns the parameters array formatted for multi-part/form data
    /// </summary>
    /// <returns></returns>
    public string GetPostData()
    {
        StringBuilder sb = new StringBuilder();
        foreach (PostDataParam p in m_Params)
        {
            sb.AppendLine("--" + boundary);

            if (p.Type == PostDataParamType.File)
            {
                sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
                sb.AppendLine("Content-Type: application/octet-stream");
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
            else
            {
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
        }

        sb.AppendLine("--" + boundary + "--");

        return sb.ToString();
    }
}

public enum PostDataParamType
{
    Field,
    File
}

public class PostDataParam
{
    public PostDataParam(string name, string value, PostDataParamType type)
    {
        Name = name;
        Value = value;
        Type = type;
    }

    public PostDataParam(string name, string filename, string value, PostDataParamType type)
    {
        Name = name;
        Value = value;
        FileName = filename;
        Type = type;
    }

    public string Name;
    public string FileName;
    public string Value;
    public PostDataParamType Type;
}

New og:image size for Facebook share?

EDIT: The current best practices regarding Open Graph image sizes are officially outlined here: https://developers.facebook.com/docs/sharing/best-practices#images


There was a post in the Facebook developers group today, where one of the FB guys uploaded a PDF containing their new rules about image sizes – since that seems to be available only if you’re a member of the group, I uploaded it here: http://www.sendspace.com/file/ghqwhr

And they also said they will post about it in the developer blog in the coming days, so keep checking there as well

To summarize the linked document:

  • Minimum size in pixels is 600x315
  • Recommended size is 1200x630 - Images this size will get a larger display treatment.
  • Aspect ratio should be 1.91:1

Java check if boolean is null

The only thing that can be a null is a non-primivite.

A boolean which can only hold TRUE or FALSE is a primitive. The TRUE/FALSE in memory are actually numbers (0 and 1)

0 = FALSE

1 = TRUE

So when you instantiate an object it will be null String str; // will equal null

On the other hand if you instaniate a primitive it will be assigned to 0 default.

boolean isTrue; // will be 0

int i; // will be 0

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

IE9 jQuery AJAX with CORS returns "Access is denied"

This is a known bug with jQuery. The jQuery team has "no plans to support this in core and is better suited as a plugin." (See this comment). IE does not use the XMLHttpRequest, but an alternative object named XDomainRequest.

There is a plugin available to support this in jQuery, which can be found here: https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js

EDIT The function $.ajaxTransport registers a transporter factory. A transporter is used internally by $.ajax to perform requests. Therefore, I assume you should be able to call $.ajax as usual. Information on transporters and extending $.ajax can be found here.

Also, a perhaps better version of this plugin can be found here.

Two other notes:

  1. The object XDomainRequest was introduced from IE8 and will not work in versions below.
  2. From IE10 CORS will be supported using a normal XMLHttpRequest.

Edit 2: http to https problem

Requests must be targeted to the same scheme as the hosting page

This restriction means that if your AJAX page is at http://example.com, then your target URL must also begin with HTTP. Similarly, if your AJAX page is at https://example.com, then your target URL must also begin with HTTPS.

Source: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

Export and import table dump (.sql) using pgAdmin

An another way, you can do it easily with CMD on Windows

Put your installed version (mine is 11).

cd C:\Program Files\PostgreSQL\11\bin\

and run simple query

psql -U <postgre_username> -d <db_name> < <C:\path\data_dump.sql>

enter password then wait the final console message.

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

How to convert an entire MySQL database characterset and collation to UTF-8?

In case the data is not in the same character set you might consider this snippet from http://dev.mysql.com/doc/refman/5.0/en/charset-conversion.html

If the column has a nonbinary data type (CHAR, VARCHAR, TEXT), its contents should be encoded in the column character set, not some other character set. If the contents are encoded in a different character set, you can convert the column to use a binary data type first, and then to a nonbinary column with the desired character set.

Here is an example:

 ALTER TABLE t1 CHANGE c1 c1 BLOB;
 ALTER TABLE t1 CHANGE c1 c1 VARCHAR(100) CHARACTER SET utf8;

Make sure to choose the right collation, or you might get unique key conflicts. e.g. Éleanore and Eleanore might be considered the same in some collations.

Aside:

I had a situation where certain characters "broke" in emails even though they were stored as UTF-8 in the database. If you are sending emails using utf8 data, you might want to also convert your emails to send in UTF8.

In PHPMailer, just update this line: public $CharSet = 'utf-8';

How can I sort an ArrayList of Strings in Java?

Take a look at the Collections.sort(List<T> list).

You can simply remove the first element, sort the list and then add it back again.

How to use font-awesome icons from node-modules

Install as npm install font-awesome --save-dev

In your development less file, you can either import the whole font awesome less using @import "node_modules/font-awesome/less/font-awesome.less", or look in that file and import just the components that you need. I think this is the minimum for basic icons:

/* adjust path as needed */
@fa_path: "../node_modules/font-awesome/less";
@import "@{fa_path}/variables.less";
@import "@{fa_path}/mixins.less";
@import "@{fa_path}/path.less";
@import "@{fa_path}/core.less";
@import "@{fa_path}/icons.less";

As a note, you still aren't going to save that many bytes by doing this. Either way, you're going to end up including between 2-3k lines of unminified CSS.

You'll also need to serve the fonts themselves from a folder called/fonts/ in your public directory. You could just copy them there with a simple gulp task, for example:

gulp.task('fonts', function() {
  return gulp.src('node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('public/fonts'))
})

Why can I ping a server but not connect via SSH?

On the server, try:

netstat -an 

and look to see if tcp port 22 is opened (use findstr in Windows or grep in Unix).

How do I block comment in Jupyter notebook?

Quick Addition to Top Answer: CTRL + / is nice because it toggles back and forth between adding and removing # at beginning of all selected lines. Didn't see that exact nuance mentioned so just wanted to add it here. (This worked in Firefox Developer Edition 54.0b12 on Windows 7).

How do I add a linker or compile flag in a CMake file?

Try setting the variable CMAKE_CXX_FLAGS instead of CMAKE_C_FLAGS:

set (CMAKE_CXX_FLAGS "-fexceptions")

The variable CMAKE_C_FLAGS only affects the C compiler, but you are compiling C++ code.

Adding the flag to CMAKE_EXE_LINKER_FLAGS is redundant.

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

Remove Datepicker Function dynamically

You can try the enable/disable methods instead of using the option method:

$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");

This disables the entire textbox. So may be you can use datepicker.destroy() instead:

$(document).ready(function() {
    $("#ddlSearchType").change(function() {
        if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
            $("#txtSearch").datepicker();
        }
        else {
            $("#txtSearch").datepicker("destroy");
        }
    }).change();
});

Demo here.

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

$scope.popoverPostion = function(event){
    $scope.pos = '';

       if(event.x <= 207 && event.x >= 140){
           $scope.pos = 'top';
           event.x = '';
       }
       else if(event.x < 140){
           $scope.pos = 'top-left';
           event.x = '';
       }
       else if(event.x > 207){
           $scope.pos = 'top-right';
           event.x = '';
       }

};

Accessing Session Using ASP.NET Web API

Why to avoid using Session in WebAPI?

Performance, performance, performance!

There's a very good, and often overlooked reason why you shouldn't be using Session in WebAPI at all.

The way ASP.NET works when Session is in use is to serialize all requests received from a single client. Now I'm not talking about object serialization - but running them in the order received and waiting for each to complete before running the next. This is to avoid nasty thread / race conditions if two requests each try to access Session simultaneously.

Concurrent Requests and Session State

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

So what does this mean for Web API? If you have an application running many AJAX requests then only ONE is going to be able to run at a time. If you have a slower request then it will block all others from that client until it is complete. In some applications this could lead to very noticeably sluggish performance.

So you should probably use an MVC controller if you absolutely need something from the users session and avoid the unncesessary performance penalty of enabling it for WebApi.

You can easily test this out for yourself by just putting Thread.Sleep(5000) in a WebAPI method and enable Session. Run 5 requests to it and they will take a total of 25 seconds to complete. Without Session they'll take a total of just over 5 seconds.

(This same reasoning applies to SignalR).

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Using print statements only to debug

Use the logging built-in library module instead of printing.

You create a Logger object (say logger), and then after that, whenever you insert a debug print, you just put:

logger.debug("Some string")

You can use logger.setLevel at the start of the program to set the output level. If you set it to DEBUG, it will print all the debugs. Set it to INFO or higher and immediately all of the debugs will disappear.

You can also use it to log more serious things, at different levels (INFO, WARNING and ERROR).

How do I POST JSON data with cURL?

Use -d option to add payload

curl -X POST \
http://<host>:<port>/<path> \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"foo": "bar",
"lorem": "ipsum"
}'

In addition:

use -X POST to use POST method

use -H 'Accept: application/json' to add accept type header

use -H 'Content-Type: application/json' to add content type header

Colorized grep -- viewing the entire file with highlighted matches

I'd like to recommend ack -- better than grep, a power search tool for programmers.

$ ack --color --passthru --pager="${PAGER:-less -R}" pattern files
$ ack --color --passthru pattern files | less -R
$ export ACK_PAGER_COLOR="${PAGER:-less -R}"
$ ack --passthru pattern files

I love it because it defaults to recursive searching of directories (and does so much smarter than grep -r), supports full Perl regular expressions (rather than the POSIXish regex(3)), and has a much nicer context display when searching many files.

Android - Start service on boot

Following should work. I have verified. May be your problem is somewhere else.

Receiver:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
            Log.d("TAG", "MyReceiver");
            Intent serviceIntent = new Intent(context, Test1Service.class);
            context.startService(serviceIntent);
        }
    }
}

Service:

public class Test1Service extends Service {
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "Service created.");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "Service started.");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "Service started.");
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>

How do I add multiple conditions to "ng-disabled"?

There is maybe a bit of a gotcha in the phrasing of the original question:

I need to check that two conditions are both true before enabling a button

The first thing to remember that the ng-disabled directive is evaluating a condition under which the button should be, well, disabled, but the original question is referring to the conditions under which it should en enabled. It will be enabled under any circumstances where the ng-disabled expression is not "truthy".

So, the first consideration is how to rephrase the logic of the question to be closer to the logical requirements of ng-disabled. The logical inverse of checking that two conditions are true in order to enable a button is that if either condition is false then the button should be disabled.

Thus, in the case of the original question, the pseudo-expression for ng-disabled is "disable the button if condition1 is false or condition2 is false". Translating into the Javascript-like code snippet required by Angular (https://docs.angularjs.org/guide/expression), we get:

!condition1 || !condition2

Zoomlar has it right!

How to get main window handle from process id?

Here, I would like to add that if you are reading window handle that is HWND of a process then that process should not be running in a debugging otherwise it will not find the window handle by using FindWindowEx.

Google Play app description formatting

Currently (July 2015), HTML escape sequences (&bull; &#8226;) do not work in browser version of Play Store, they're displayed as text. Though, Play Store app handles them as expected.

So, if you're after the unicode bullet point in your app/update description [that's what's got you here, most likely], just copy-paste the bullet character

PS You can also use unicode input combo to get the character

Linux: CtrlShiftu 2022 Enter or Space

Mac: Hold ? 2022 release ?

Windows: Hold Alt 2022 release Alt

Mac and Windows require some setup, read on Wikipedia

PPS If you're feeling creative, here's a good link with more copypastable symbols, but don't go too crazy, nobody likes clutter in what they read.

How do I get SUM function in MySQL to return '0' if no values are found?

Use IFNULL or COALESCE:

SELECT IFNULL(SUM(Column1), 0) AS total FROM...

SELECT COALESCE(SUM(Column1), 0) AS total FROM...

The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.

How to write MySQL query where A contains ( "a" or "b" )

You can write your query like so:

SELECT * FROM MyTable WHERE (A LIKE '%text1%' OR A LIKE '%text2%')

The % is a wildcard, meaning that it searches for all rows where column A contains either text1 or text2

Variable might not have been initialized error

If they were declared as fields of the class then they would be really initialized with 0.

You're a bit confused because if you write:

class Clazz {
  int a;
  int b;

  Clazz () {
     super ();
     b = 0;
  }

  public void printA () {
     sout (a + b);
  }

  public static void main (String[] args) {
     new Clazz ().printA ();
  }
}

Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first super () will be called, then field a will be initialized implicitly, and then line b = 0 will be executed.

Effective way to find any file's Encoding

The following code works fine for me, using the StreamReader class:

  using (var reader = new StreamReader(fileName, defaultEncodingIfNoBom, true))
  {
      reader.Peek(); // you need this!
      var encoding = reader.CurrentEncoding;
  }

The trick is to use the Peek call, otherwise, .NET has not done anything (and it hasn't read the preamble, the BOM). Of course, if you use any other ReadXXX call before checking the encoding, it works too.

If the file has no BOM, then the defaultEncodingIfNoBom encoding will be used. There is also a StreamReader without this overload method (in this case, the Default (ANSI) encoding will be used as defaultEncodingIfNoBom), but I recommand to define what you consider the default encoding in your context.

I have tested this successfully with files with BOM for UTF8, UTF16/Unicode (LE & BE) and UTF32 (LE & BE). It does not work for UTF7.

Does the Java &= operator apply & or &&?

It's the last one:

a = a & b;

ASP.Net which user account running Web Service on IIS 7?

Server 2008

Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.

In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity

Here's the info from Microsoft on setting up Application Pool Identites:

http://learn.iis.net/page.aspx/624/application-pool-identities/

String comparison using '==' vs. 'strcmp()'

Always remember, when comparing strings, you should use === operator (strict comparison) and not == operator (loose comparison).

How to deny access to a file in .htaccess

I don't believe the currently accepted answer is correct. For example, I have the following .htaccess file in the root of a virtual server (apache 2.4):

<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>

This prevents external access to reminder.php which is in a subdirectory. I have a similar .htaccess file on my Apache 2.2 server with the same effect:

<Files "reminder.php">
        Order Deny,Allow
        Deny from all
        Allow from localhost
        Allow from 127.0.0.1
     Allow from xxx.yyy.zzz.aaa
</Files>

I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess file, viz <Files ./inscription/log.txt> which is causing it to fail. It would be simpler to put the .htaccess file in the same directory as log.txt i.e. in the inscription directory and it will work there.

Java BigDecimal: Round to the nearest whole value

I don't think you can round it like that in a single command. Try

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
    }

Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

function checkCharType (charToCheck) {
    // body... 
    var returnValue = "O";
    var charCode = charToCheck.charCodeAt(0);

    if(charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)){

        returnValue = "U";

    }else if (charCode >= "a".charCodeAt(0) &&
                charCode <= "z".charCodeAt(0) ){
        returnValue = "L";
    }else if (charCode >= "0".charCodeAt(0) &&
            charCode <= "9".charCodeAt(0)  ) {
        returnValue = "N";
    }
    return returnValue;
}

var myString = prompt("Enter Some text: ", "Hello world !");

switch (checkCharType(myString)) {
    case "U":
        // statements_1
        document.write("First character was upper case");
        break;

    case "L":
        document.write("First character was a lower case");
        break;
    case "N":
        document.write("First character was a number");
        break
    default:
        // statements_def
        document.write("First character was not a character or a number");
        break;
}
  1. Define a Function checkCharType().By declaring the variable returnValue and initialising it to the Character "O" to indicate it's Some other value.

  2. U for uppercase; L for Lowercase ; N for number

  3. Use the charCodeAt() method to get the character code of the first character.

  4. Using if Statement , which check within what range of values the character code falls.

  5. If it falls between the character codes for A and Z, Its Uppercase, character code between a and z ,Its Lowercase. and so on.

  6. "A".charCode(0)

    var myChar = new String("A"); myChar.charCodeAt(0); "A" : number code "65“

  7. Check the String

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

How do you align left / right a div without using float?

you could use things like display: inline-block but I think you would need to set up another div to move it over, if there is nothing going to the left of the button you could use margins to move it into place.

Alternatively but not a good solution, you could position tags; put the encompassing div as position: relative and then the div of the button as position: absolute; right: 0, but like I said this is probably not the best solution

HTML

<div class="parent">
  <div>Left Div</div>
  <div class="right">Right Div</div>
</div>

CSS

.parent {
  position: relative;
}
.right {
    position: absolute;
    right: 0;
}

Get connection string from App.config

Try this out

string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;

CSS Border Not Working

Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Remote branch is not showing up in "git branch -r"

Update your remote if you still haven't done so:

$ git remote update
$ git branch -r

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

Prevent cell numbers from incrementing in a formula in Excel

There is something called 'locked reference' in excel which you can use for this, and you use $ symbols to lock a range. For your example, you would use:

=IF(B4<>"",B4/B$1,"")

This locks the 1 in B1 so that when you copy it to rows below, 1 will remain the same.

If you use $B$1, the range will not change when you copy it down a row or across a column.

jQuery vs document.querySelectorAll

jQuery's Sizzle selector engine can use querySelectorAll if it's available. It also smooths out inconsistencies between browsers to achieve uniform results. If you don't want to use all of jQuery, you could just use Sizzle separately. This is a pretty fundamental wheel to invent.

Here's some cherry-pickings from the source that show the kind of things jQuery(w/ Sizzle) sorts out for you:

Safari quirks mode:

if ( document.querySelectorAll ) {
  (function(){
    var oldSizzle = Sizzle,
      div = document.createElement("div"),
      id = "__sizzle__";

    div.innerHTML = "<p class='TEST'></p>";

    // Safari can't handle uppercase or unicode characters when
    // in quirks mode.
    if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
      return;
    }

If that guard fails it uses it's a version of Sizzle that isn't enhanced with querySelectorAll. Further down there are specific handles for inconsistencies in IE, Opera, and the Blackberry browser.

  // Check parentNode to catch when Blackberry 4.6 returns
  // nodes that are no longer in the document #6963
  if ( elem && elem.parentNode ) {
    // Handle the case where IE and Opera return items
    // by name instead of ID
    if ( elem.id === match[3] ) {
      return makeArray( [ elem ], extra );
    }

  } else {
    return makeArray( [], extra );
  }

And if all else fails it will return the result of oldSizzle(query, context, extra, seed).

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

How to change default Anaconda python environment

For Jupyter and Windows users, you can change the Target path in your Jupyter Notebook (anaconda3) shortcut from C:\Users\<YourUserName>\anaconda3 to C:\Users\<YourUserName>\anaconda3\envs\<YourEnvironmentName>

you could do the same thing for the Anaconda Prompt..etc.

After changing the path you can check your active environment by opening a terminal in Jupyter and run conda info --envs.

enter image description here

With Spring can I make an optional path variable?

Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false now:

  @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
  public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
    if (type != null) {
      // ...
    }
    return new TestBean();
  }

The thread has exited with code 0 (0x0) with no unhandled exception

Stop this error you have to follow this simple steps

  1. Open Visual Studio
  2. Select option debug from the top
  3. Select Options
  4. In Option Select debugging under debugging select General
  5. In General Select check box "Automatically close the console when debugging stop"
  6. Save it

Then Run the code by using Shortcut key Ctrl+f5

**Other wise it still show error when you run it direct

Setting Django up to use MySQL

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

You also need to create the /path/to/my.cnf file with similar settings from above

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.


If you are just testing your application on your local machine, you can use

python manage.py runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle's MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',

Note that you will first need to install mysql on your OS.

brew install mysql (MacOS)

Also, the mysql client package has changed for python 3 (MySQL-Client works only for python 2)

pip3 install mysqlclient

Invoke a second script with arguments from a script

Much simpler actually:

Method 1:

Invoke-Expression $scriptPath $argumentList

Method 2:

& $scriptPath $argumentList

Method 3:

$scriptPath $argumentList

If you have spaces in your scriptPath, don't forget to escape them `"$scriptPath`"

How do I test which class an object is in Objective-C?

You also can use

NSString *className = [[myObject class] description]; 

on any NSObject

SQL Server query to find all current database names

Here is a query for showing all databases in one Sql engine

Select * from Sys.Databases

How to obtain the chat_id of a private Telegram channel?

No need to convert the channel to public then make it private.

  1. find the id of your private channel. (There are numerous methods to do this, for example see this SO answer)

  2. curl -X POST "https://api.telegram.org/botxxxxxx:yyyyyyyyyyy/sendMessage" -d "chat_id=-100CHAT_ID&text=my sample text"

    replace xxxxxx:yyyyyyyyyyy with your bot id, and replace CHAT_ID with the channel id found in step 1. So if channel id is 1234 it would be chat_id=-1001234.

All done!

How to get the current loop index when using Iterator?

This would be the simplest solution!

std::vector<double> v (5);

for(auto itr = v.begin();itr != v.end();++itr){

 auto current_loop_index = itr - v.begin();

  std::cout << current_loop_index << std::endl;

}

Tested on gcc-9 with -std=c++11 flag

Output:

0
1
2
3
4

What's the most concise way to read query parameters in AngularJS?

It's a bit late, but I think your problem was your URL. If instead of

http://127.0.0.1:8080/test.html?target=bob

you had

http://127.0.0.1:8080/test.html#/?target=bob

I'm pretty sure it would have worked. Angular is really picky about its #/

What is the difference between SQL and MySQL?

SQL - Structured Query Language. It is declarative computer language aimed at querying relational databases.

MySQL is a relational database - a piece of software optimized for data storage and retrieval. There are many such databases - Oracle, Microsoft SQL Server, SQLite and many others are examples of such.

Factorial using Recursion in Java

The key point that you missing here is that the variable "result" is a stack variable, and as such it does not get "replaced". To elaborate, every time fact is called, a NEW variable called "result" is created internally in the interpreter and linked to that invocation of the methods. This is in contrast of object fields which linked to the instance of the object and not a specific method call

Current date without time

As mentioned in several answers already that have been already given, you can use ToShorDateString():

DateTime.Now.ToShortDateString();

However, you may be a bit blocked if you also want to use the culture as a parameter. In this case you can use the ToString() method with the "d" format:

DateTime.Now.ToString("d", CultureInfo.GetCultureInfo("en-US"))

No module named _sqlite3

I found lots of people meet this problem because the Multi-version Python, on my own vps (cent os 7 x64), I solved it in this way:

  1. Find the file "_sqlite3.so"

    find / -name _sqlite3.so
    

    out: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. Find the dir of python Standard library you want to use,

    for me /usr/local/lib/python3.6/lib-dynload

  3. Copy the file:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload
    

Finally, everything will be ok.

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

(SC) DeleteService FAILED 1072

Logging-out and logging-in again close all blocking apps thus resolves the problem.

in a "using" block is a SqlConnection closed on return or exception?

In your first example, the C# compiler will actually translate the using statement to the following:

SqlConnection connection = new SqlConnection(connectionString));

try
{
    connection.Open();

    string storedProc = "GetData";
    SqlCommand command = new SqlCommand(storedProc, connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

    return (byte[])command.ExecuteScalar();
}
finally
{
    connection.Dispose();
}

Finally statements will always get called before a function returns and so the connection will be always closed/disposed.

So, in your second example the code will be compiled to the following:

try
{
    try
    {
        connection.Open();

        string storedProc = "GetData";
        SqlCommand command = new SqlCommand(storedProc, connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

        return (byte[])command.ExecuteScalar();
    }
    finally
    {
        connection.Dispose();
    }
}
catch (Exception)
{
}

The exception will be caught in the finally statement and the connection closed. The exception will not be seen by the outer catch clause.

Changing width property of a :before css selector using JQuery

As Boltclock states in his answer to Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, and thus you can't select and manipulate them with jQuery.

Might just be best to set the style with jQuery instead of using the pseudo CSS selector.

ImportError: Couldn't import Django

If you are working on a machine where it doesn't have permissions to all the files and moreover you have two versions such as default 2.7 & latest 3.6 then while running the command use the python version with the command. If the latest python is installed with sudo then run the command with sudo.

exp:

sudo python3.6 manage.py runserver

Android 'Unable to add window -- token null is not for an application' exception

I got the same exception. what i do to fix this is to pass instance of the dialog as parameter into function and use it instead of pass only context then using getContext(). this solution solve my problem, hope it can help

Finding the handle to a WPF window

If you want window handles for ALL of your application's Windows for some reason, you can use the Application.Windows property to get at all the Windows and then use WindowInteropHandler to get at their handles as you have already demonstrated.

In MySQL, can I copy one row to insert into the same table?

Sorry for the necropost but this is what I turned up with google and since I found this helpful but problematic I wanted to contribute an important modification for anyone else who digs this up.

First off, I'm using SQL Server, not MySQL, but I think it should work similarly. I used Leonard Challis' solution because it was simplest and met the need, however there's a problem with this - if you simply take the PK and increment it by 1 then what happens if you've added other records since the row in question was added. I decided it was best to just let the system handle the autoincrementing of the PK, so I did the following:

SELECT * INTO #tmpTable FROM Table WHERE primarykey = 1
--Optionally you can modify one or more fields here like this: 
--UPDATE #tmpTable SET somefield = newData
ALTER TABLE #tmpTable DROP COLUMN TicketUpdateID
INSERT INTO Tickets SELECT * FROM #tmpTable
DROP TABLE #tmpTable

I believe this would work similarly in MySQL, but I can't test this, sorry

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How to kill/stop a long SQL query immediately?

This is kind of a silly answer, but it works reliably at least in my case: In management studio, when the "Cancel Executing Query" doesn't stop the query I just click to close the current sql document. it asks me if I want to cancel the query, I say yes, and lo and behold in a few seconds it stops executing. After that it asks me if I want to save the document before closing. At this point I can click Cancel to keep the document open and continue working. No idea what's going on behind the scenes, but it seems to work.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

Install Windows Service created in Visual Studio

Here is an alternate way to make the installer and get rid of that error message. Also it seems that VS2015 express does not have the "Add Installer" menu item.

You simply need to create a class and add the below code and add the reference System.Configuration.Install.dll.

using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;


namespace SAS
{
    [RunInstaller(true)]
    public class MyProjectInstaller : Installer
    {
        private ServiceInstaller serviceInstaller1;
        private ServiceProcessInstaller processInstaller;

        public MyProjectInstaller()
        {
            // Instantiate installer for process and service.
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller1 = new ServiceInstaller();

            // The service runs under the system account.
            processInstaller.Account = ServiceAccount.LocalSystem;

            // The service is started manually.
            serviceInstaller1.StartType = ServiceStartMode.Manual;

            // ServiceName must equal those on ServiceBase derived classes.
            serviceInstaller1.ServiceName = "SAS Service";

            // Add installer to collection. Order is not important if more than one service.
            Installers.Add(serviceInstaller1);
            Installers.Add(processInstaller);
        }
    }
}