Programs & Examples On #M4v

HTML5 video won't play in Chrome only

To all of you who got here and did not found the right solution, i found out that the mp4 video needs to fit a specific format.

My Problem was that i got an 1920x1080 video which wont load under Chrome (under Firefox it worked like a charm). After hours of searching i finaly managed to get hang of the problem, the first few streams where 1912x1088 so Chrome wont play it ( i got the exact stream size from the tool MediaInfo). So to fix it i just resized it to 1920x1080 and it worked.

Javascript to stop HTML5 video playback on modal window close

For anyone struggling with this issue with videos embedded using the <object> tag, the function you want is Quicktime's element.Stop(); For example, to stop any and all playing movies, use:

var videos = $("object");

for (var i=0; i < videos.length; i++)
{
    if (videos[i].Stop) { videos[i].Stop(); }
}

Note the non-standard capital "S" on Stop();

Can I have a video with transparent background using HTML5 video tag?

Mp4 files can be playable with transparent background using seeThrou Js library. All you need to combine actual video and alpha channel in the single video. Also make sure to keep video height dimension below 1400 px as some of the old iphone devices wont play videos with dimension more than 2000. This is pretty useful in safari desktop and mobile devices which doesnt support webm at this time.

more details can be found in the below link https://github.com/m90/seeThru

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

I see in the documentation page an example like this:

<source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">

Maybe you should enclose the codec information with &quot; entities instead of actual quotes and the type attribute with quotes instead of apostrophes.

You can also try removing the codec info altogether.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

As of the 3.2 SDK you can access the view property of MPMoviePlayerController, modify its frame and add it to your view hierarchy.

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
player.view.frame = CGRectMake(184, 200, 400, 300);
[self.view addSubview:player.view];
[player play];

There's an example here: http://www.devx.com/wireless/Article/44642/1954

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

Why should C++ programmers minimize use of 'new'?

I see that a few important reasons for doing as few new's as possible are missed:

Operator new has a non-deterministic execution time

Calling new may or may not cause the OS to allocate a new physical page to your process this can be quite slow if you do it often. Or it may already have a suitable memory location ready, we don't know. If your program needs to have consistent and predictable execution time (like in a real-time system or game/physics simulation) you need to avoid new in your time critical loops.

Operator new is an implicit thread synchronization

Yes you heard me, your OS needs to make sure your page tables are consistent and as such calling new will cause your thread to acquire an implicit mutex lock. If you are consistently calling new from many threads you are actually serialising your threads (I've done this with 32 CPUs, each hitting on new to get a few hundred bytes each, ouch! that was a royal p.i.t.a. to debug)

The rest such as slow, fragmentation, error prone, etc have already been mentioned by other answers.

Looping from 1 to infinity in Python

If you're doing that in C, then your judgement there is as cloudy as it would be in Python :-)

For a loop that exits on a simple condition check at the start of each iteration, it's more usual (and clearer, in my opinion) to just do that in the looping construct itself. In other words, something like (if you need i after loop end):

int i = 0;
while (! thereIsAReasonToBreak(i)) {
    // do something
    i++;
}

or (if i can be scoped to just the loop):

for (int i = 0; ! thereIsAReasonToBreak(i); ++i) {
    // do something
}

That would translate to the Python equivalent:

i = 0
while not there_is_a_reason_to_break(i):
    # do something
    i += 1

Only if you need to exit in the middle of the loop somewhere (or if your condition is complex enough that it would render your looping statement far less readable) would you need to worry about breaking.

When your potential exit is a simple one at the start of the loop (as it appears to be here), it's usually better to encode the exit into the loop itself.

Why is the Android emulator so slow? How can we speed up the Android emulator?

If you can, switch to using Ubuntu for Android development. I switched to Ubuntu 14.04 LTS for Android development, and I am glad that I took the jump. All of the steps mentioned made little or no difference in the lag on Windows. Linux is the correct answer to all the problems you are facing

Count the number of occurrences of a character in a string in Javascript

The function takes string str as parameter and counts occurrence of each unique characters in the string. The result comes in key - value pair for each character.

var charFoundMap = {};//object defined
    for (var i = 0; i < str.length; i++) {

       if(!charFoundMap[ str[i] ])  {
        charFoundMap[ str[i] ]=1;
       } 
       else
       charFoundMap[ str[i] ] +=1;
       //if object does not contain this 
    }
    return charFoundMap;

} 

When to use CouchDB over MongoDB and vice versa

Be aware of an issue with sparse unique indexes in MongoDB. I've hit it and it is extremely cumbersome to workaround.

The problem is this - you have a field, which is unique if present and you wish to find all the objects where the field is absent. The way sparse unique indexes are implemented in Mongo is that objects where that field is missing are not in the index at all - they cannot be retrieved by a query on that field - {$exists: false} just does not work.

The only workaround I have come up with is having a special null family of values, where an empty value is translated to a special prefix (like null:) concatenated to a uuid. This is a real headache, because one has to take care of transforming to/from the empty values when writing/quering/reading. A major nuisance.

I have never used server side javascript execution in MongoDB (it is not advised anyway) and their map/reduce has awful performance when there is just one Mongo node. Because of all these reasons I am now considering to check out CouchDB, maybe it fits more to my particular scenario.

BTW, if anyone knows the link to the respective Mongo issue describing the sparse unique index problem - please share.

Space between Column's children in Flutter

For some kinda simple things like that You can easily use Wrap look at that example

    Wrap(
       crossAxisAlignment: WrapCrossAlignment.start,
       alignment: WrapAlignment.center,
       direction: Axis.vertical,
       spacing: 30, // to apply margin in the main axis of the wrap
       runSpacing: 30, // to apply margin in the cross axis of the wrap
       children: <Widget>[
        Text('Text 1'),
        Text('Text 2')
  ]
)

How to break out of jQuery each Loop

I use this way (for example):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

if cont isn't false runs commands block

Get the current user, within an ApiController action, without passing the userID as a parameter

Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext() to Request.GetOwinContext() and make sure you have added the following 2 using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

What does %s and %d mean in printf in the C language?

%s is for string %d is for decimal (or int) %c is for character

It appears to be chewing through an array of characters, and printing out whatever string exists starting at each subsequent position. The strings will stop at the first null in each case.

The commas are just separating the arguments to a function that takes a variable number of args; this number corresponds to the number of % args in the format descriptor at the front.

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

Switch case with conditions

This should work with this :

var cnt = $("#div1 p").length;

            switch (true) {
                case (cnt >= 10 && cnt <= 20):
                    alert('10');
                    break;
                case (cnt >= 21 && cnt <= 30):
                   alert('21');
                    break;
                case (cnt >= 31 && cnt <= 40):
                    break;
                default:
                    alert('>41');
            }

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

What is function overloading and overriding in php?

Strictly speaking, there's no difference, since you cannot do either :)

Function overriding could have been done with a PHP extension like APD, but it's deprecated and afaik last version was unusable.

Function overloading in PHP cannot be done due to dynamic typing, ie, in PHP you don't "define" variables to be a particular type. Example:

$a=1;
$a='1';
$a=true;
$a=doSomething();

Each variable is of a different type, yet you can know the type before execution (see the 4th one). As a comparison, other languages use:

int a=1;
String s="1";
bool a=true;
something a=doSomething();

In the last example, you must forcefully set the variable's type (as an example, I used data type "something").


Another "issue" why function overloading is not possible in PHP: PHP has a function called func_get_args(), which returns an array of current arguments, now consider the following code:

function hello($a){
  print_r(func_get_args());
}

function hello($a,$a){
  print_r(func_get_args());
}

hello('a');
hello('a','b');

Considering both functions accept any amount of arguments, which one should the compiler choose?


Finally, I'd like to point out why the above replies are partially wrong; function overloading/overriding is NOT equal to method overloading/overriding.

Where a method is like a function but specific to a class, in which case, PHP does allow overriding in classes, but again no overloading, due to language semantics.

To conclude, languages like Javascript allow overriding (but again, no overloading), however they may also show the difference between overriding a user function and a method:

/// Function Overriding ///

function a(){
   alert('a');
}
a=function(){
   alert('b');
}

a(); // shows popup with 'b'


/// Method Overriding ///

var a={
  "a":function(){
    alert('a');
  }
}
a.a=function(){
   alert('b');
}

a.a(); // shows popup with 'b'

Update React component every second

class ShowDateTime extends React.Component {
   constructor() {
      super();
      this.state = {
        curTime : null
      }
    }
    componentDidMount() {
      setInterval( () => {
        this.setState({
          curTime : new Date().toLocaleString()
        })
      },1000)
    }
   render() {
        return(
          <div>
            <h2>{this.state.curTime}</h2>
          </div>
        );
      }
    }

Change color and appearance of drop down arrow

No, you can't do it by using an actual <select>, but there are techniques that allow you to "replace" them with javascript solutions that look better.

Here's a good article on the topic: <select> Something New

How to export all collections in MongoDB?

#mongodump using sh script 
#!/bin/bash
TIMESTAMP=`date +%F-%H%M`
APP_NAME="folder_name"
BACKUPS_DIR="/xxxx/tst_file_bcup/$APP_NAME"
BACKUP_NAME="$APP_NAME-$TIMESTAMP"
/usr/bin/mongodump -h 127.0.0.1 -d <dbname> -o $BACKUPS_DIR/$APP_NAME/$BACKUP_NAME
tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUPS_DIR/$APP_NAME/$BACKUP_NAME
rm -rf /home/wowza_analytics_bcup/wowza_analytics/wowza_analytics
### 7 days old backup delete automaticaly using given command

find /home/wowza_analytics_bcup/wowza_analytics/ -mindepth 1 -mtime +7 -delete

What are enums and why are they useful?

enum means enumeration i.e. mention (a number of things) one by one.

An enum is a data type that contains fixed set of constants.

OR

An enum is just like a class, with a fixed set of instances known at compile time.

For example:

public class EnumExample {
    interface SeasonInt {
        String seasonDuration();
    }

    private enum Season implements SeasonInt {
        // except the enum constants remaining code looks same as class
        // enum constants are implicitly public static final we have used all caps to specify them like Constants in Java
        WINTER(88, "DEC - FEB"), SPRING(92, "MAR - JUN"), SUMMER(91, "JUN - AUG"), FALL(90, "SEP - NOV");

        private int days;
        private String months;

        Season(int days, String months) { // note: constructor is by default private 
            this.days = days;
            this.months = months;
        }

        @Override
        public String seasonDuration() {
            return this+" -> "+this.days + "days,   " + this.months+" months";
        }

    }
    public static void main(String[] args) {
        System.out.println(Season.SPRING.seasonDuration());
        for (Season season : Season.values()){
            System.out.println(season.seasonDuration());
        }

    }
}

Advantages of enum:

  • enum improves type safety at compile-time checking to avoid errors at run-time.
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

for more

Selecting only first-level elements in jquery

Once you have the initial ul, you can use the children() method, which will only consider the immediate children of the element. As @activa points out, one way to easily select the root element is to give it a class or an id. The following assumes you have a root ul with id root.

$('ul#root').children('li');

DECODE( ) function in SQL Server

Create a function in SQL Server as below and replace the DECODE with dbo.DECODE

CREATE FUNCTION DECODE(@CondField as nvarchar(100),@Criteria as nvarchar(100), 
                       @True Value as nvarchar(100), @FalseValue as nvarchar(100))
returns nvarchar(100)
begin
       return case when @CondField = @Criteria then @TrueValue 
                   else @FalseValue end
end

What is the difference between declarations, providers, and import in NgModule?

Angular @NgModule constructs:

  1. import { x } from 'y';: This is standard typescript syntax (ES2015/ES6 module syntax) for importing code from other files. This is not Angular specific. Also this is technically not part of the module, it is just necessary to get the needed code within scope of this file.
  2. imports: [FormsModule]: You import other modules in here. For example we import FormsModule in the example below. Now we can use the functionality which the FormsModule has to offer throughout this module.
  3. declarations: [OnlineHeaderComponent, ReCaptcha2Directive]: You put your components, directives, and pipes here. Once declared here you now can use them throughout the whole module. For example we can now use the OnlineHeaderComponent in the AppComponent view (html file). Angular knows where to find this OnlineHeaderComponent because it is declared in the @NgModule.
  4. providers: [RegisterService]: Here our services of this specific module are defined. You can use the services in your components by injecting with dependency injection.

Example module:

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

// Components
import { AppComponent } from './app.component';
import { OfflineHeaderComponent } from './offline/offline-header/offline-header.component';
import { OnlineHeaderComponent } from './online/online-header/online-header.component';

// Services
import { RegisterService } from './services/register.service';

// Directives
import { ReCaptcha2Directive } from './directives/re-captcha2.directive';

@NgModule({
  declarations: [
    OfflineHeaderComponent,,
    OnlineHeaderComponent,
    ReCaptcha2Directive,
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [
    RegisterService,
  ],
  entryComponents: [
    ChangePasswordComponent,
    TestamentComponent,
    FriendsListComponent,
    TravelConfirmComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Running Jupyter via command line on Windows

Problem for me was that I was running the jupyter command from the wrong directory.

Once I navigated to the path containing the script, everything worked.

Path- C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Scripts

What is the difference between synchronous and asynchronous programming (in node.js)

The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.

Installing Apache Maven Plugin for Eclipse

I found Maven Integration for Eclipse here.

http://download.eclipse.org/technology/m2e/releases

After installing restart eclipse. Worked for me running Eclipse Juno.

What's the actual use of 'fail' in JUnit test case?

Let's say you are writing a test case for a negative flow where the code being tested should raise an exception.

try{
   bizMethod(badData);
   fail(); // FAIL when no exception is thrown
} catch (BizException e) {
   assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}

How do I remove version tracking from a project cloned from git?

From root folder run

find . | grep .git

Review the matches and confirm it only contains those files you want to delete and adjust to suit. Once satisfied, run

find . | grep .git | xargs rm -rf

Java: Add elements to arraylist with FOR loop where element name has increasing number

Put the answers into an array and iterate over it:

List<Answer> answers = new ArrayList<Answer>(3);

for (Answer answer : new Answer[] {answer1, answer2, answer3}) {
    list.add(answer);
}

EDIT

See João's answer for a much better solution. I'm still leaving my answer here as another option.

Javascript foreach loop on associative array object

Here is a simple way to use an associative array as a generic Object type:

_x000D_
_x000D_
Object.prototype.forEach = function(cb){_x000D_
   if(this instanceof Array) return this.forEach(cb);_x000D_
   let self = this;_x000D_
   Object.getOwnPropertyNames(this).forEach(_x000D_
      (k)=>{ cb.call(self, self[k], k); }_x000D_
   );_x000D_
};_x000D_
_x000D_
Object({a:1,b:2,c:3}).forEach((value, key)=>{ _x000D_
    console.log(`key/value pair: ${key}/${value}`);_x000D_
});
_x000D_
_x000D_
_x000D_

type object 'datetime.datetime' has no attribute 'datetime'

You should really import the module into its own alias.

import datetime as dt
my_datetime = dt.datetime(year, month, day)

The above has the following benefits over the other solutions:

  • Calling the variable my_datetime instead of date reduces confusion since there is already a date in the datetime module (datetime.date).
  • The module and the class (both called datetime) do not shadow each other.

grep from tar.gz without extracting [faster one]

I know this question is 4 years old, but I have a couple different options:

Option 1: Using tar --to-command grep

The following line will look in example.tgz for PATTERN. This is similar to @Jester's example, but I couldn't get his pattern matching to work.

tar xzf example.tgz --to-command 'grep --label="$TAR_FILENAME" -H PATTERN ; true'

Option 2: Using tar -tzf

The second option is using tar -tzf to list the files, then go through them with grep. You can create a function to use it over and over:

targrep () {
    for i in $(tar -tzf "$1"); do
        results=$(tar -Oxzf "$1" "$i" | grep --label="$i" -H "$2")
        echo "$results"
    done
}

Usage:

targrep example.tar.gz "pattern"

How to find if an array contains a string

I'm afraid I don't think there's a shortcut to do this - if only someone would write a linq wrapper for VB6!

You could write a function that does it by looping through the array and checking each entry - I don't think you'll get cleaner than that.

There's an example article that provides some details here: http://www.vb6.us/tutorials/searching-arrays-visual-basic-6

How to get values and keys from HashMap?

To get all the values from a map:

for (Tab tab : hash.values()) {
    // do something with tab
}

To get all the entries from a map:

for ( Map.Entry<String, Tab> entry : hash.entrySet()) {
    String key = entry.getKey();
    Tab tab = entry.getValue();
    // do something with key and/or tab
}

Java 8 update:

To process all values:

hash.values().forEach(tab -> /* do something with tab */);

To process all entries:

hash.forEach((key, tab) -> /* do something with key and tab */);

Firefox Add-on RESTclient - How to input POST parameters?

Here is a step by step guide (I think this should come pre-loaded with the add-on):

  1. In the top menu of RESTClient -> Headers -> Custom Header
  2. In the pop-up box, enter Name: Content-Type and Value: application/x-www-form-urlencoded
  3. Check the "Save to favorite" box and click Okay.
    Now you will see a "Headers" section with your newly added data.
  4. Then in the Body section, you can enter your data to post like:

    username=test&name=Firstname+Lastname
    
  5. Whenever you want to make a post request, from the Headers main menu, select the Content-Type:application/x-www-form-urlencoded item that you added and it should work.

After MySQL install via Brew, I get the error - The server quit without updating PID file

I had this problem on Linux, but the cause is relevant to any mysql installation. In my case, the server was crashing before startup was complete and the pid file updated. The error messages were seen when starting up mysqld directly instead of via "service mysql start".

In my case, the cause was the partition where the log files were located being full. Removing log files permitted mysql to start again. To test for this issue, go to the location of your mysql activity logs, and do df ..

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

Access iframe elements in JavaScript

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

not working for me but I found another solution. Use:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

I checked it on Firefox and Chrome.

tsc is not recognized as internal or external command

For windows

After installing typescript globally

npm install typescript -g 

just search for "node.js command prompt"

type in command promt

tsc -v 

Here we can see tsc command works, now navigate to your folder and type

tsc filename.ts 

its complies ts to js file.

Submit two forms with one button

You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

If you want to do a real test extract of a tar file without extracting to disk, use the -O option. This spews the extract to standard output instead of the filesystem. If the tar file is corrupt, the process will abort with an error.

Example of failed tar ball test...

$ echo "this will not pass the test" > hello.tgz
$ tar -xvzf hello.tgz -O > /dev/null
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error exit delayed from previous errors
$ rm hello.*

Working Example...

$ ls hello*
ls: hello*: No such file or directory
$ echo "hello1" > hello1.txt
$ echo "hello2" > hello2.txt
$ tar -cvzf hello.tgz hello[12].txt
hello1.txt
hello2.txt
$ rm hello[12].txt
$ ls hello*
hello.tgz
$ tar -xvzf hello.tgz -O
hello1.txt
hello1
hello2.txt
hello2
$ ls hello*
hello.tgz
$ tar -xvzf hello.tgz
hello1.txt
hello2.txt
$ ls hello*
hello1.txt  hello2.txt  hello.tgz
$ rm hello*

How can I get the current user directory?

Environment.GetEnvironmentVariable("userprofile")

Trying to navigate up from a named SpecialFolder is prone for problems. There are plenty of reasons that the folders won't be where you expect them - users can move them on their own, GPO can move them, folder redirection to UNC paths, etc.

Using the environment variable for the userprofile should reflect any of those possible issues.

Handling click events on a drawable within an EditText

Kotlin is a great language where each class could be extended with new methods. Lets introduce new method for EditText class which will catch clicks to right drawable.

fun EditText.onRightDrawableClicked(onClicked: (view: EditText) -> Unit) {
this.setOnTouchListener { v, event ->
    var hasConsumed = false
    if (v is EditText) {
        if (event.x >= v.width - v.totalPaddingRight) {
            if (event.action == MotionEvent.ACTION_UP) {
                onClicked(this)
            }
            hasConsumed = true
        }
    }
    hasConsumed
}
}

You can see it takes callback function as argument which is called when user clicks to right drawable.

val username = findViewById<EditText>(R.id.username_text)
    username.onRightDrawableClicked {
        it.text.clear()
    }

Can I set a TTL for @Cacheable

Since Spring-boot 1.3.3, you may set expire time in CacheManager by using RedisCacheManager.setExpires or RedisCacheManager.setDefaultExpiration in CacheManagerCustomizer call-back bean.

After installing SQL Server 2014 Express can't find local db

Also, if you just installed localDB, you won't see the instance in the configuration manager. You would need to initiate it first, and then connect to it using server name (localdb)\mssqllocaldb. Source

Output ("echo") a variable to a text file

After some trial and error, I found that

$computername = $env:computername

works to get a computer name, but sending $computername to a file via Add-Content doesn't work.

I also tried $computername.Value.

Instead, if I use

$computername = get-content env:computername

I can send it to a text file using

$computername | Out-File $file

Open a URL without using a browser from a batch file

Not sure whether you have already gotten your owner solution. I have been using the following powshell command to achieve it:

powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://your_url"

How to use function srand() with time.h?

You need to call srand() once, to randomize the seed, and then call rand() in your loop:

#include <stdlib.h>
#include <time.h>

#define size 10

srand(time(NULL)); // randomize seed

for(i=0;i<size;i++)
    Arr[i] = rand()%size;

Best way to check if object exists in Entity Framework?

Why not do it?

var result= ctx.table.Where(x => x.UserName == "Value").FirstOrDefault();

if(result?.field == value)
{
  // Match!
}

MVC DateTime binding with incorrect date format

It is also worth noting that even without creating your own model binder multiple different formats may be parsable.

For instance in the US all the following strings are equivalent and automatically get bound to the same DateTime value:

/company/press/may%2001%202008

/company/press/2008-05-01

/company/press/05-01-2008

I'd strongly suggest using yyyy-mm-dd because its a lot more portable. You really dont want to deal with handling multiple localized formats. If someone books a flight on 1st May instead of 5th January you're going to have big issues!

NB: I'm not clear exaclty if yyyy-mm-dd is universally parsed in all cultures so maybe someone who knows can add a comment.

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I had a similar issue:

  1. On my ASP.NET MVC project, I've added a Sql Server Compact database (sdf) to my App_Data folder. VS added a reference to EntityFramework.dll, version 4.* . The web.config file was updated appropriately with the 4.* configuration.

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

  2. I've added a new project to my solution (a Data Access Layer project). Here I've added an EDMX file. VS added a reference to EntityFramework.dll, version 5.0. The App.config file was updated appropriately with the 5.0 configuration

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

On execution, when reading from the database the app always thrown the exception Could not load file or assembly 'EntityFramework, Version=5.0.0.0 ....

The issue was fixed by removing the EntityFramework.dll v4.0 from my MVC project. I've also updated the web.config file with the correct 5.0 version. Then everything worked as expected.

Running Python on Windows for Node.js dependencies

gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.

Not necessary to reinstall, this exception throw by node-gyp script, then try to rebuild. It's enough setup environment variable like in my case I did:

SET PYTHON=C:\work\_env\Python27\python.exe

Rest-assured. Is it possible to extract value from request json?

To serialize the response into a class, define the target class

public class Result {
    public Long user_id;
}

And map response to it:

Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);

You must have Jackson or Gson in the classpath as the documentation states: http://rest-assured.googlecode.com/svn/tags/2.3.1/apidocs/com/jayway/restassured/response/ResponseBodyExtractionOptions.html#as(java.lang.Class)

Correct format specifier for double in printf

Given the C99 standard (namely, the N1256 draft), the rules depend on the function kind: fprintf (printf, sprintf, ...) or scanf.

Here are relevant parts extracted:

Foreword

This second edition cancels and replaces the first edition, ISO/IEC 9899:1990, as amended and corrected by ISO/IEC 9899/COR1:1994, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996. Major changes from the previous edition include:

  • %lf conversion specifier allowed in printf

7.19.6.1 The fprintf function

7 The length modifiers and their meanings are:

l (ell) Specifies that (...) has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.

The same rules specified for fprintf apply for printf, sprintf and similar functions.

7.19.6.2 The fscanf function

11 The length modifiers and their meanings are:

l (ell) Specifies that (...) that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double;

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.

12 The conversion specifiers and their meanings are: a,e,f,g Matches an optionally signed floating-point number, (...)

14 The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

The long story short, for fprintf the following specifiers and corresponding types are specified:

  • %f -> double
  • %Lf -> long double.

and for fscanf it is:

  • %f -> float
  • %lf -> double
  • %Lf -> long double.

Java Error: "Your security settings have blocked a local application from running"

If you have no Medium security level, then you should add your application to the Exception Site List (Java Control Panel ? Security tab).

  1. Open your applet in a browser and copy the contents of your address bar. screenshot of applet's address in the address bar
  2. Go to Control Panel ? Java Control Panel ? Security tab and press the Edit Site List... button. screenshot of Java Control Panel's Security tab

  3. Press the Add button, insert your path and press Enter. screenshot of Exception Site List

  4. Press Continue on the security warning that appears. screenshot of Security Warning - FILE Location alert prompt

  5. Open the applet again and don't forget to press Run on the pop-up window. screenshot of Security Warning

Converting a Uniform Distribution to a Normal Distribution

Where R1, R2 are random uniform numbers:

NORMAL DISTRIBUTION, with SD of 1:

sqrt(-2*log(R1))*cos(2*pi*R2)

This is exact... no need to do all those slow loops!

Reference: dspguide.com/ch2/6.htm

Git Cherry-pick vs Merge Workflow

In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").

Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).

Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.

HTH.

gdb fails with "Unable to find Mach task port for process-id" error

The problem is that you are not logged in as a root user (which you don't want). You need to create a certificate for gdb to be allowed access. Follow this tutorial and you should be good to go...

http://sourceware.org/gdb/wiki/BuildingOnDarwin

If all else fails, just use: sudo gdb executableFileName

If (Array.Length == 0)

If array is null, trying to derefrence array.Length will throw a NullReferenceException. If your code considers null to be an invalid value for array, you should reject it and blame the caller. One such pattern is to throw ArgumentNullException:

void MyMethod(string[] array)
{
    if (array == null) throw new ArgumentNullException(nameof(array));

    if (array.Length > 0)
    {
        // Do something with array…
    }
}

If you want to accept a null array as an indication to not do something or as an optional parameter, you may simply not access it if it is null:

void MyMethod(string[] array)
{
    if (array != null)
    {
        // Do something with array here…
    }
}

If you want to avoid touching array when it is either null or has zero length, then you can check for both at the same time with C#-6’s null coalescing operator.

void MyMethod(string[] array)
{
    if (array?.Length > 0)
    {
        // Do something with array…
    }
}

Superfluous Length Check

It seems strange that you are treating the empty array as a special case. In many cases, if you, e.g., would just loop over the array anyway, there’s no need to treat the empty array as a special case. foreach (var elem in array) {«body»} will simply never execute «body» when array.Length is 0. If you are treating array == null || array.Length == 0 specially to, e.g., improve performance, you might consider leaving a comment for posterity. Otherwise, the check for Length == 0 appears superfluous.

Superfluous code makes understanding a program harder because people reading the code likely assume that each line is necessary to solve some problem or achieve correctness. If you include unnecessary code, the readers are going to spend forever trying to figure out why that line is or was necessary before deleting it ;-).

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

It's just common stuff for making cin input work faster.

For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.

The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).

Using getopts to process long and short command line options

The built-in getopts command is still, AFAIK, limited to single-character options only.

There is (or used to be) an external program getopt that would reorganize a set of options such that it was easier to parse. You could adapt that design to handle long options too. Example usage:

aflag=no
bflag=no
flist=""
set -- $(getopt abf: "$@")
while [ $# -gt 0 ]
do
    case "$1" in
    (-a) aflag=yes;;
    (-b) bflag=yes;;
    (-f) flist="$flist $2"; shift;;
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
    (*)  break;;
    esac
    shift
done

# Process remaining non-option arguments
...

You could use a similar scheme with a getoptlong command.

Note that the fundamental weakness with the external getopt program is the difficulty of handling arguments with spaces in them, and in preserving those spaces accurately. This is why the built-in getopts is superior, albeit limited by the fact it only handles single-letter options.

In a unix shell, how to get yesterday's date into a variable?

On Linux, you can use

date -d "-1 days" +"%a %d/%m/%Y"

e.printStackTrace equivalent in python

e.printStackTrace equivalent in python

In Java, this does the following (docs):

public void printStackTrace()

Prints this throwable and its backtrace to the standard error stream...

This is used like this:

try
{ 
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}

In Java, the Standard Error stream is unbuffered so that output arrives immediately.

The same semantics in Python 2 are:

import traceback
import sys
try: # code that may raise an error
    pass 
except IOError as e: # exception handling
    # in Python 2, stderr is also unbuffered
    print >> sys.stderr, traceback.format_exc()
    # in Python 2, you can also from __future__ import print_function
    print(traceback.format_exc(), file=sys.stderr)
    # or as the top answer here demonstrates, use:
    traceback.print_exc()
    # which also uses stderr.

Python 3

In Python 3, we can get the traceback directly from the exception object (which likely behaves better for threaded code). Also, stderr is line-buffered, but the print function gets a flush argument, so this would be immediately printed to stderr:

    print(traceback.format_exception(None, # <- type(e) by docs, but ignored 
                                     e, e.__traceback__),
          file=sys.stderr, flush=True)

Conclusion:

In Python 3, therefore, traceback.print_exc(), although it uses sys.stderr by default, would buffer the output, and you may possibly lose it. So to get as equivalent semantics as possible, in Python 3, use print with flush=True.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

The provider is bundled with PowerShell>=6.0.

If all you need is a way to install a package from a file, just grab the .msi installer for the latest version from the github releases page, copy it over to the machine, install it and use it.

Firebase: how to generate a unique numeric ID for key?

I'd suggest reading through the Firebase documentation. Specifically, see the Saving Data portion of the Firebase JavaScript Web Guide.

From the guide:

Getting the Unique ID Generated by push()

Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it. The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated

// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push({
 author: "gracehop",
 title: "Announcing COBOL, a New Programming Language"
});

// Get the unique ID generated by push() by accessing its key
var postID = newPostRef.key;

Source: https://firebase.google.com/docs/database/admin/save-data#section-ways-to-save

  • A push generates a new data path, with a server timestamp as its key. These keys look like -JiGh_31GA20JabpZBfa, so not numeric.
  • If you wanted to make a numeric only ID, you would make that a parameter of the object to avoid overwriting the generated key.
    • The keys (the paths of the new data) are guaranteed to be unique, so there's no point in overwriting them with a numeric key.
    • You can instead set the numeric ID as a child of the object.
    • You can then query objects by that ID child using Firebase Queries.

From the guide:

In JavaScript, the pattern of calling push() and then immediately calling set() is so common that we let you combine them by just passing the data to be set directly to push() as follows. Both of the following write operations will result in the same data being saved to Firebase:

// These two methods are equivalent:
postsRef.push().set({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});
postsRef.push({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});

Source: https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push

Finding smallest value in an array most efficiently

You need too loop through the array, remembering the smallest value you've seen so far. Like this:

int smallest = INT_MAX;
for (int i = 0; i < array_length; i++) {
    if (array[i] < smallest) {
        smallest = array[i];
    }
}

Is there any way to prevent input type="number" getting negative values?

The answer to this is not helpful. as its only works when you use up/down keys, but if you type -11 it will not work. So here is a small fix that I use

this one for integers

  $(".integer").live("keypress keyup", function (event) {
    //    console.log('int = '+$(this).val());
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if (event.which != 8 && (event.which < 48 || event.which > 57))
    {
        event.preventDefault();
    }
   });

this one when you have numbers of price

        $(".numeric, .price").live("keypress keyup", function (event) {
     //    console.log('numeric = '+$(this).val());
    $(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));

    if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
   });

Ternary operator ?: vs if...else

I think that there are situations where the inline if can yield "faster" code because of the scope it works at. Object creation and destruction can be costly so consider the follow scenario :

class A{
    public:
    A() : value(0) {
        cout << "Default ctor" << endl;
    }
    A(int myInt) : value(myInt)
    {
        cout << "Overloaded ctor" << endl;
    }

    A& operator=(const A& other){
        cout << "= operator" << endl;
        value = other.value; 
    }

    ~A(){
        cout << "destroyed" << std::endl;
    }

    int value;

};


int main()
{
   {
       A a;
       if(true){
           a = A(5);
       }else{
           a = A(10);
       }
   }

   cout << "Next test" << endl;
   {
        A b = true? A(5) : A(10);
   }
   return 0;
}

With this code, the output will be :

Default ctor                                                                                                                                                                                                                      
Overloaded ctor                                                                                                                                                                                                                   
= operator                                                                                                                                                                                                                        
destroyed                                                                                                                                                                                                                         
destroyed                                                                                                                                                                                                                         
Next test                                                                                                                                                                                                                         
Overloaded ctor                                                                                                                                                                                                                   
destroyed  

So by inlining the if, we save a bunch of operation needed to keep a alive at the same scope as b. While it is highly probable that the condition evaluation speed is pretty equal in both scenarios, changing scope forces you to take other factors into consideration that the inline if allows you to avoid.

How to use SVG markers in Google Maps API v3

OK! I done this soon in my web,I try two ways to create the custom google map marker, this run code use canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.

_x000D_
_x000D_
var marker;_x000D_
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];_x000D_
_x000D_
function initMap() {_x000D_
  var map = new google.maps.Map(document.getElementById('map'), {_x000D_
    zoom: 13,_x000D_
    center: {_x000D_
      lat: 59.325,_x000D_
      lng: 18.070_x000D_
    }_x000D_
  });_x000D_
  var markerOption = {_x000D_
    latitude: 59.327,_x000D_
    longitude: 18.067,_x000D_
    color: "#" + "000",_x000D_
    text: "ha"_x000D_
  };_x000D_
  marker = createMarker(markerOption);_x000D_
  marker.setMap(map);_x000D_
  marker.addListener('click', changeColorAndText);_x000D_
};_x000D_
_x000D_
function changeColorAndText() {_x000D_
  var iconTmpObj = createSvgIcon( "#c00", "ok" );_x000D_
  marker.setOptions( {_x000D_
                icon: iconTmpObj_x000D_
            } );_x000D_
};_x000D_
_x000D_
function createMarker(options) {_x000D_
  //IE MarkerShape has problem_x000D_
  var markerObj = new google.maps.Marker({_x000D_
    icon: createSvgIcon(options.color, options.text),_x000D_
    position: {_x000D_
      lat: parseFloat(options.latitude),_x000D_
      lng: parseFloat(options.longitude)_x000D_
    },_x000D_
    draggable: false,_x000D_
    visible: true,_x000D_
    zIndex: 10,_x000D_
    shape: {_x000D_
      coords: CustomShapeCoords,_x000D_
      type: 'poly'_x000D_
    }_x000D_
  });_x000D_
_x000D_
  return markerObj;_x000D_
};_x000D_
_x000D_
function createSvgIcon(color, text) {_x000D_
  var div = $("<div></div>");_x000D_
_x000D_
  var svg = $(_x000D_
    '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +_x000D_
    '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +_x000D_
    '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +_x000D_
    '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +_x000D_
    '</svg>'_x000D_
  );_x000D_
  div.append(svg);_x000D_
_x000D_
  var dd = $("<canvas height='50px' width='50px'></cancas>");_x000D_
_x000D_
  var svgHtml = div[0].innerHTML;_x000D_
_x000D_
  canvg(dd[0], svgHtml);_x000D_
_x000D_
  var imgSrc = dd[0].toDataURL("image/png");_x000D_
  //"scaledSize" and "optimized: false" together seems did the tricky ---IE11  &&  viewBox influent IE scaledSize_x000D_
  //var svg = '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'_x000D_
  //    + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'_x000D_
  //    + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'_x000D_
  //    + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'_x000D_
  //    + '</svg>';_x000D_
  //var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);_x000D_
_x000D_
  var iconObj = {_x000D_
    size: new google.maps.Size(32, 43),_x000D_
    url: imgSrc,_x000D_
    scaledSize: new google.maps.Size(32, 43)_x000D_
  };_x000D_
_x000D_
  return iconObj;_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Your Custom Marker </title>_x000D_
  <style>_x000D_
    /* Always set the map height explicitly to define the size of the div_x000D_
       * element that contains the map. */_x000D_
    #map {_x000D_
      height: 100%;_x000D_
    }_x000D_
    /* Optional: Makes the sample page fill the window. */_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="map"></div>_x000D_
    <script src="https://canvg.github.io/canvg/canvg.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

I had this error and solved by this solution.

--> Right click on the project

--> and select "Properties"

--> then set "Output Type" to "Class Library".

Using NSLog for debugging

NSLog(@"%@", digit);

what is shown in console?

Detect browser or tab closing

<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">

var myclose = false;

function ConfirmClose()
{
    if (event.clientY < 0)
    {
        event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
        setTimeout('myclose=false',10);
        myclose=true;
    }
}

function HandleOnClose()
{
    if (myclose==true) 
    {
        //the url of your logout page which invalidate session on logout 
        location.replace('/contextpath/j_spring_security_logout') ;
    }   
}

//This is working in IE7, if you are closing tab or browser with only one tab

Creating random numbers with no duplicates

It really all depends on exactly WHAT you need the random generation for, but here's my take.

First, create a standalone method for generating the random number. Be sure to allow for limits.

public static int newRandom(int limit){
    return generatedRandom.nextInt(limit);  }

Next, you will want to create a very simple decision structure that compares values. This can be done in one of two ways. If you have a very limited amount of numbers to verify, a simple IF statement will suffice:

public static int testDuplicates(int int1, int int2, int int3, int int4, int int5){
    boolean loopFlag = true;
    while(loopFlag == true){
        if(int1 == int2 || int1 == int3 || int1 == int4 || int1 == int5 || int1 == 0){
            int1 = newRandom(75);
            loopFlag = true;    }
        else{
            loopFlag = false;   }}
    return int1;    }

The above compares int1 to int2 through int5, as well as making sure that there are no zeroes in the randoms.

With these two methods in place, we can do the following:

    num1 = newRandom(limit1);
    num2 = newRandom(limit1);
    num3 = newRandom(limit1);
    num4 = newRandom(limit1);
    num5 = newRandom(limit1);

Followed By:

        num1 = testDuplicates(num1, num2, num3, num4, num5);
        num2 = testDuplicates(num2, num1, num3, num4, num5);
        num3 = testDuplicates(num3, num1, num2, num4, num5);
        num4 = testDuplicates(num4, num1, num2, num3, num5);
        num5 = testDuplicates(num5, num1, num2, num3, num5);

If you have a longer list to verify, then a more complex method will yield better results both in clarity of code and in processing resources.

Hope this helps. This site has helped me so much, I felt obliged to at least TRY to help as well.

int object is not iterable?

First, lose that call to int - you're converting a string of characters to an integer, which isn't what you want (you want to treat each character as its own number). Change:

inp = int(input("Enter a number:"))

to:

inp = input("Enter a number:")

Now that inp is a string of digits, you can loop over it, digit by digit.

Next, assign some initial value to n -- as you code stands right now, you'll get a NameError since you never initialize it. Presumably you want n = 0 before the for loop.

Next, consider the difference between a character and an integer again. You now have:

n = n + i;

which, besides the unnecessary semicolon (Python is an indentation-based syntax), is trying to sum the character i to the integer n -- that won't work! So, this becomes

n = n + int(i)

to turn character '7' into integer 7, and so forth.

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

Splitting a Java String by the pipe symbol using split("|")

the split() method takes a regular expression as an argument

Query based on multiple where clauses in Firebase

Frank's answer is good but Firestore introduced array-contains recently that makes it easier to do AND queries.

You can create a filters field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson but if you also you want to by comedy and 2014 you can add the value comedy_2014 without creating more fields.

{
  "movies": {
    "movie1": {
      "genre": "comedy",
      "name": "As good as it gets",
      "lead": "Jack Nicholson",
      "year": 2014,
      "filters": [
        "comedy_Jack Nicholson",
        "comedy_2014"
      ]
    }
  }
}

Getting only 1 decimal place

>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997

Python: CSV write by column rather than row

Read it in by row and then transpose it in the command line. If you're using Unix, install csvtool and follow the directions in: https://unix.stackexchange.com/a/314482/186237

Duplicate Symbols for Architecture arm64

In my case reason was too stupid :

I had a Constant.h file where I had macros defined. I thought of doing NSString there. and did this :

NSString const *kGreenColor = @"#00C34E";

this caused the problem of Duplicate Symbols for Architecture arm64 and Linker command failed with exit code 1. Removing const NSString line worked for me.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

Most Developers log-in to server(I assume you r having user-name and password for mysql database) then from Bash they switch to mysql> prompt then use the command below(which doesn’t work

mysql -h localhost -u root -p

What needs to be done is use the above command in the bash prompt--> on doing so it will ask for password if given it will take directly to mysql prompt and

then database, table can be created one by one

I faced similar deadlock so sharing the experience

Protect .NET code from reverse engineering?

  • Use online update to block those unlicensed copies.

  • Verify serial number from different modules of your application and do not use a single function call to do the verification (so that crackers cannot bypass the verification easily).

  • Not only check serial number at startup, do the verification while saving data, do it every Friday evening, do it when user is idle ...

  • Verify application file check sum, store your security check sum in different places.

  • Don't go too far on these kind of tricks, make sure your application never crash/get into malfunction while verifying registration code.

  • Build a useful app for users is much more important than make a
    unbreakable binary for crackers.

Apache VirtualHost 403 Forbidden

For apache Ubuntu 2.4.7 , I finally found you need to white list your virtual host in apache2.conf

# access here, or in any related virtual host.
<Directory /home/gav/public_html/>
    Options FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Cross domain POST request is not sending cookie Ajax Jquery

There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.

To have a cookie sent by the browser to another site during a request the following criteria must be met:

A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.

How can I catch a ctrl-c event?

Yeah, this is a platform dependent question.

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

In a WIN32 GUI application you should handle the WM_KEYDOWN message.

JavaScript dictionary with names

I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:

var myMappings = {
    "Name": 0.1,
    "Phone": 0.1,
    "Address": 0.5,
    "Zip": 0.1,
    "Comments": 0.2
};

for (var col in myMappings) {
    alert((myMappings[col] * 100) + "%");
}

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

How to get the PID of a process by giving the process name in Mac OS X ?

This solution matches the process name more strictly:

ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'

This solution has the following advantages:

  • it ignores command line arguments like tail -f ~/Dropbox
  • it ignores processes inside a directory like ~/Dropbox/foo.sh
  • it ignores processes with names like ~/DropboxUID.sh

Convert Set to List without creating new List

Map<String, List> mainMap = new HashMap<String, List>();

for(int i=0; i<something.size(); i++){
  Set set = getSet(...); //return different result each time
  mainMap.put(differentKeyName, new ArrayList(set));
}

Trigger 404 in Spring-MVC controller?

This is a bit late, but if you are using Spring Data REST then there is already org.springframework.data.rest.webmvc.ResourceNotFoundException It also uses @ResponseStatus annotation. There is no need to create a custom runtime exception anymore.

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

Query Mongodb on month, day, year... of a datetime

You can use MongoDB_DataObject wrapper to perform such query like below:

$model = new MongoDB_DataObject('orders');

$model->whereAdd('MONTH(created) = 4 AND YEAR(created) = 2016');

$model->find();

while ($model->fetch()) {
    var_dump($model);
}

OR, similarly, using direct query string:

$model = new MongoDB_DataObject();

$model->query('SELECT * FROM orders WHERE MONTH(created) = 4 AND YEAR(created) = 2016');

while ($model->fetch()) {
    var_dump($model);
}

Websocket connections with Postman

You can use Socket.io tester, this app lets you connect to a socket.io server and subscribe to a certain topic and/or lets you send socket messages to the server

Remove all files except some from a directory

If you're using zsh which I highly recommend.

rm -rf ^file/folder pattern to avoid

With extended_glob

setopt extended_glob
rm -- ^*.txt
rm -- ^*.(sql|txt)

How to return PDF to browser in MVC?

if you return var-binary data from DB to display PDF on popup or browser means follow this code:-

View page:

@using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post))
    {
        <a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a>
    }

Scan controller:

public ActionResult DisplayPDF()
        {
            byte[] byteArray = GetPdfFromDB(4);
            MemoryStream pdfStream = new MemoryStream();
            pdfStream.Write(byteArray, 0, byteArray.Length);
            pdfStream.Position = 0;
            return new FileStreamResult(pdfStream, "application/pdf");
        }

        private byte[] GetPdfFromDB(int id)
        {
            #region
            byte[] bytes = { };
            string constr = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=@Id and Enabled = 1";
                    cmd.Parameters.AddWithValue("@Id", id);
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        if (sdr.HasRows == true)
                        {
                            sdr.Read();
                            bytes = (byte[])sdr["Scan_Pdf_File"];
                        }
                    }
                    con.Close();
                }
            }

            return bytes;
            #endregion
        }

How to unblock with mysqladmin flush hosts

You should put it into command line in windows.

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

For network login use the following command:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How to run a jar file in a linux commandline

For example to execute from terminal (Ubuntu Linux) or even (Windows console) a java file called filex.jar use this command:

java -jar filex.jar

The file will execute in terminal.

Limit file format when using <input type="file">?

You could actually do it with javascript but remember js is client side, so you would actually be "warning users" what type of files they can upload, if you want to AVOID (restrict or limit as you said) certain type of files you MUST do it server side.

Look at this basic tut if you would like to get started with server side validation. For the whole tutorial visit this page.

Good luck!

Dynamically display a CSV file as an HTML table on a web page

XmlGrid.net has tool to convert csv to html table. Here is the link: http://xmlgrid.net/csvToHtml.html

I used your sample data, and got the following html table:

<table>
<!--Created with XmlGrid Free Online XML Editor (http://xmlgrid.net)-->
<tr>
  <td>Name</td>
  <td> Age</td>
  <td> Sex</td>
</tr>
<tr>
  <td>Cantor, Georg</td>
  <td> 163</td>
  <td> M</td>
</tr>
</table>

How should I use Outlook to send code snippets?

Here's what works for me, and is quickest and causes the least amount of pain / annoyance:

1) Paste you code snippet into sublime; make sure your syntax is looking good.

2) Right click and choose 'Copy as RTF'

3) Paste into your email

4) Done

UITableView example for Swift

In Swift 4.1 and Xcode 9.4.1

  1. Add UITableViewDataSource, UITableViewDelegate delegated to your class.

  2. Create table view variable and array.

  3. In viewDidLoad create table view.

  4. Call table view delegates

  5. Call table view delegate functions based on your requirement.

import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { 

// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]

override func viewDidLoad() {
    super.viewDidLoad()

    // 3
    yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
    self.view.addSubview(yourTableView)

    // 4
    yourTableView.dataSource = self
    yourTableView.delegate = self

}

// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }
    if self. myArray.count > 0 {
        cell?.textLabel!.text = self. myArray[indexPath.row]
    }
    cell?.textLabel?.numberOfLines = 0

    return cell!
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50.0
}

If you are using storyboard, no need for Step 3.

But you need to create IBOutlet for your table view before Step 4.

In php, is 0 treated as empty?

From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.


To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */
}

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */
}

jsFiddle demo


1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Map over object preserving keys

You can use _.mapValues(users, function(o) { return o.age; }); in Lodash and _.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; }); in Underscore.

Check out the cross-documentation here: http://jonathanpchen.com/underdash-api/#mapvalues-object-iteratee-identity

Formatting a float to 2 decimal places

string outString= number.ToString("####0.00");

Set variable value to array of strings

You're trying to assign three separate string literals to a single string variable. A valid string variable would be 'John, Sarah, George'. If you want embedded single quotes between the double quotes, you have to escape them.

Also, your actual SELECT won't work, because SQL databases won't parse the string variable out into individual literal values. You need to use dynamic SQL instead, and then execute that dynamic SQL statement. (Search this site for dynamic SQL, with the database engine you're using as the topic (as in [sqlserver] dynamic SQL), and you should get several examples.)

Spring Boot application as a Service

What follows is the easiest way to install a Java application as system service in Linux.

Let's assume you are using systemd (which any modern distro nowadays does):

Firstly, create a service file in /etc/systemd/system named e.g. javaservice.service with this content:

[Unit]
Description=Java Service

[Service]
User=nobody
# The configuration file application.properties should be here:
WorkingDirectory=/data 
ExecStart=/usr/bin/java -Xmx256m -jar application.jar --server.port=8081
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Secondly, notify systemd of the new service file:

systemctl daemon-reload

and enable it, so it runs on boot:

systemctl enable javaservice.service

Eventually, you can use the following commands to start/stop your new service:

systemctl start javaservice
systemctl stop javaservice
systemctl restart javaservice
systemctl status javaservice

Provided you are using systemd, this is the most non-intrusive and clean way to set up a Java application as system-service.

What I like especially about this solution is the fact that you don't need to install and configure any other software. The shipped systemd does all the work for you, and your service behaves like any other system service. I use it in production for a while now, on different distros, and it just works as you would expect.

Another plus is that, by using /usr/bin/java, you can easily add jvm paramters such as -Xmx256m.

Also read the systemd part in the official Spring Boot documentation: http://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

Array initializing in Scala

To initialize an array filled with zeros, you can use:

> Array.fill[Byte](5)(0)
Array(0, 0, 0, 0, 0)

This is equivalent to Java's new byte[5].

How to change value of object which is inside an array using JavaScript or jQuery?

This is my response to the problem. My underscore version was 1.7 hence I could not use .findIndex.

So I manually got the index of item and replaced it. Here is the code for the same.

 var students = [ 
{id:1,fName:"Ajay", lName:"Singh", age:20, sex:"M" },
{id:2,fName:"Raj", lName:"Sharma", age:21, sex:"M" },
{id:3,fName:"Amar", lName:"Verma", age:22, sex:"M" },
{id:4,fName:"Shiv", lName:"Singh", age:22, sex:"M" }
               ]

Below method will replace the student with id:4 with more attributes in the object

function updateStudent(id) {
 var indexOfRequiredStudent = -1;
    _.each(students,function(student,index) {                    
      if(student.id === id) {                        
           indexOfRequiredStudent = index; return;      
      }});
 students[indexOfRequiredStudent] = _.extend(students[indexOfRequiredStudent],{class:"First Year",branch:"CSE"});           

}

With underscore 1.8 it will be simplified as we have methods _.findIndexOf.

Remove category & tag base from WordPress url - without a plugin

I don´t know how to do it using code, but for those who don't mind using a plugin. This is a great one that works for me:

https://es.wordpress.org/plugins/permalink-manager/

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.

Ternary:

$something = isset($_GET['something']) ? $_GET['something'] : "failed";

If-else:

if (isset($_GET['something'])) {
    $something = $_GET['something'];
} else {
    $something = "failed";
}

The AWS Access Key Id does not exist in our records

If you have an AWS Educate account and you get this problem:

An error occurred (InvalidAccessKeyId) when calling the ListBuckets operation: The AWS Access Key Id you provided does not exist in our records".

The solution is here:

  1. Go to your C:/ drive and search for .aws folder inside your main folder in windows.

  2. Inside that folder you get the "credentials" file and open it with notepad.

  3. Paste the whole key credential from AWS account to the same notepad and save it.

  4. Now you are ready to use you AWS Educate account.

MySQL: NOT LIKE

I don't know why

cfg_name_unique NOT LIKE '%categories%' 

still returns those two values, but maybe exclude them explicit:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%'
    AND developer_configurations_cms.cfg_name_unique NOT IN ('categories_posts', 'categories_news')

Using C# to read/write Excel files (.xls/.xlsx)

If you are doing simple manipulation and can tie yourself to xlsx then you can look into manipulating the XML yourself. I have done it and found it to be faster than grokking the excel libs.

There are also 3rd party libs that can be easier to use... and can be used on the server which MS's can't.

Angular 2 How to redirect to 404 or other path if the path does not exist

My preferred option on 2.0.0 and up is to create a 404 route and also allow a ** route path to resolve to the same component. This allows you to log and display more information about the invalid route rather than a plain redirect which can act to hide the error.

Simple 404 example:

{ path '/', component: HomeComponent },
// All your other routes should come first    
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }

To display the incorrect route information add in import to router within NotFoundComponent:

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

Add it to the constructior of NotFoundComponent:

constructor(public router: Router) { }

Then you're ready to reference it from your HTML template e.g.

The page <span style="font-style: italic">{{router.url}}</span> was not found.

Importing .py files in Google Colab

In case anyone else is interested to know how to import files/packages from gdrive inside a google colab. The following procedure worked for me:

1) Mount your google drive in google colab:

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

2) Append the directory to your python path using sys:

import sys
sys.path.append('/content/gdrive/mypythondirectory')

Now you should be able to import stuff from that directory!

Display an image into windows forms

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:

  • Like you are doing.
  • Using ImageLocation property of the PictureBox like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "../SamuderaJayaMotor.png";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    
  • Using an image from the web like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    

And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.

What is the difference between <html lang="en"> and <html lang="en-US">?

<html lang="en">
<html lang="en-US">

The first lang tag only specifies a language code. The second specifies a language code, followed by a country code.

What other values can follow the dash? According to w3.org "Any two-letter subcode is understood to be a [ISO3166] country code." so does that mean any value listed under the alpha-2 code is an accepted value?

Yes, however the value may or may not have any real meaning.

<html lang="en-US"> essentially means "this page is in the US style of English." In a similar way, <html lang="en-GB"> would mean "this page is in the United Kingdom style of English."

If you really wanted to specify an invalid combination, you could. It wouldn't mean much, but <html lang="en-ES"> is valid according to the specification, as I understand it. However, that language/country combination won't do much since English isn't commonly spoken in Spain.

I mean does this somehow further help the browser to display the page?

It doesn't help the browser to display the page, but it is useful for search engines, screen readers, and other things that might read and try to interpret the page, besides human beings.

Fill an array with random numbers

People don't see the nice cool Stream producers all over the Java libs.

public static double[] list(){
    return new Random().ints().asDoubleStream().toArray();
}

Testing if value is a function

// This should be a function, because in certain JavaScript engines (V8, for
// example, try block kills many optimizations).
function isFunction(func) {
    // For some reason, function constructor doesn't accept anonymous functions.
    // Also, this check finds callable objects that aren't function (such as,
    // regular expressions in old WebKit versions), as according to EcmaScript
    // specification, any callable object should have typeof set to function.
    if (typeof func === 'function')
        return true

    // If the function isn't a string, it's probably good idea to return false,
    // as eval cannot process values that aren't strings.
    if (typeof func !== 'string')
        return false

    // So, the value is a string. Try creating a function, in order to detect
    // syntax error.
    try {
        // Create a function with string func, in order to detect whatever it's
        // an actual function. Unlike examples with eval, it should be actually
        // safe to use with any string (provided you don't call returned value).
        Function(func)
        return true
    }
    catch (e) {
        // While usually only SyntaxError could be thrown (unless somebody
        // modified definition of something used in this function, like
        // SyntaxError or Function, it's better to prepare for unexpected.
        if (!(e instanceof SyntaxError)) {
            throw e
        }

        return false
    }
}

jQuery - determine if input element is textbox or select list

alternatively you can retrieve DOM properties with .prop

here is sample code for select box

if( ctrl.prop('type') == 'select-one' ) { // for single select }

if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }

for textbox

  if( ctrl.prop('type') == 'text' ) { // for text box }

Multiple Updates in MySQL

You may also be interested in using joins on updates, which is possible as well.

Update someTable Set someValue = 4 From someTable s Inner Join anotherTable a on s.id = a.id Where a.id = 4
-- Only updates someValue in someTable who has a foreign key on anotherTable with a value of 4.

Edit: If the values you are updating aren't coming from somewhere else in the database, you'll need to issue multiple update queries.

Round up double to 2 decimal places

@Rounded, A swift 5.1 property wrapper Example :

struct GameResult {
    @Rounded(rule: NSDecimalNumber.RoundingMode.up,scale: 4)
    var score: Decimal
}

var result = GameResult()
result.score = 3.14159265358979
print(result.score) // 3.1416

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

Jquery - How to get the style display attribute "none / block"

You could try:

$j('div.contextualError.ckgcellphone').css('display')

Delete first character of a string in Javascript

//---- remove first and last char of str    
str = str.substring(1,((keyw.length)-1));

//---- remove only first char    
str = str.substring(1,(keyw.length));

//---- remove only last char    
str = str.substring(0,(keyw.length));

Can I install Python 3.x and 2.x on the same Windows computer?

The official solution for coexistence seems to be the Python Launcher for Windows, PEP 397 which was included in Python 3.3.0. Installing the release dumps py.exe and pyw.exe launchers into %SYSTEMROOT% (C:\Windows) which is then associated with py and pyw scripts, respectively.

In order to use the new launcher (without manually setting up your own associations to it), leave the "Register Extensions" option enabled. I'm not quite sure why, but on my machine it left Py 2.7 as the "default" (of the launcher).

Running scripts by calling them directly from the command line will route them through the launcher and parse the shebang (if it exists). You can also explicitly call the launcher and use switches: py -3 mypy2script.py.

All manner of shebangs seem to work

  • #!C:\Python33\python.exe
  • #!python3
  • #!/usr/bin/env python3

as well as wanton abuses

  • #! notepad.exe

Django - taking values from POST request

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))

How to check if a table is locked in sql server

sys.dm_tran_locks contains the locking information of the sessions

If you want to know a specific table is locked or not, you can use the following query

SELECT 
 * 
from 
 sys.dm_tran_locks 
where 
  resource_associated_entity_id = object_id('schemaname.tablename')

if you are interested in finding both login name of the user and the query being run

SELECT
 DB_NAME(resource_database_id)
 , s.original_login_name
 , s.status
 , s.program_name
 , s.host_name
 , (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
 ,*
from
  sys.dm_tran_locks dbl
     JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
  INNER JOIN  sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
 DB_NAME(dbl.resource_database_id) = 'dbname'

For more infomraton locking query

More infor about sys.dm_tran_locks

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Here is the solutions that worked for me:

  1. open index.php from the htdocs folder
  2. inside replace the word dashboard with your database name.
  3. restart the server

This should resolve the issue :-)

How do I get JSON data from RESTful service using Python?

You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:

import httplib2 as http
import json

try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=UTF-8'
}

uri = 'http://yourservice.com'
path = '/path/to/resource/'

target = urlparse(uri+path)
method = 'GET'
body = ''

h = http.Http()

# If you need authentication some example:
if auth:
    h.add_credentials(auth.user, auth.password)

response, content = h.request(
        target.geturl(),
        method,
        body,
        headers)

# assume that content is a json reply
# parse content with the json module
data = json.loads(content)

Find duplicate lines in a file and count how many time each line was duplicated?

To find and count duplicate lines in multiple files, you can try the following command:

sort <files> | uniq -c | sort -nr

or:

cat <files> | sort | uniq -c | sort -nr

Hide/Show components in react native

I would vouch for using the opacity-method if you do not want to remove the component from your page, e.g. hiding a WebView.

<WebView
   style={{opacity: 0}} // Hide component
   source={{uri: 'https://www.google.com/'}}
 />

This is useful if you need to submit a form to a 3rd party website.

How to enable curl in Wamp server

Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

How many characters can a Java String have?

The heap part gets worse, my friends. UTF-16 isn't guaranteed to be limited to 16 bits and can expand to 32

How to trigger HTML button when you press Enter in textbox?

First of all add jquery library file jquery and call it in your html head.

and then Use jquery based code...

$("#id_of_textbox").keyup(function(event){
    if(event.keyCode == 13){
        $("#id_of_button").click();
    }
});

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

How to print number with commas as thousands separators?

Python 3

--

Integers (without decimal):

"{:,d}".format(1234567)

--

Floats (with decimal):

"{:,.2f}".format(1234567)

where the number before f specifies the number of decimal places.

--

Bonus

Quick-and-dirty starter function for the Indian lakhs/crores numbering system (12,34,567):

https://stackoverflow.com/a/44832241/4928578

"Untrusted App Developer" message when installing enterprise iOS Application

Today, I was testing this with iOS 9 Beta and found the solution.

To solve it, go to:

  1. Settings -> General -> Profiles [Device Management on iOS 10]
  2. Under ENTERPRISE APP, choose your current developer account name.
  3. Tap Trust "Your developer account name"
  4. Tap "Trust" in pop up.
  5. Done

Best HTML5 markup for sidebar

The book HTML5 Guidelines for Web Developers: Structure and Semantics for Documents suggested this way (option 1):

<aside id="sidebar">
    <section id="widget_1"></section>
    <section id="widget_2"></section>
    <section id="widget_3"></section>
</aside>

It also points out that you can use sections in the footer. So section can be used outside of the actual page content.

How do I retrieve my MySQL username and password?

Save the file. For this example, the file will be named C:\mysql-init.txt. it asking administrative permisions for saving the file

Select a Dictionary<T1, T2> with LINQ

A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

How to create a temporary directory/folder in Java?

If you need a temporary directory for testing and you are using jUnit, @Rule together with TemporaryFolder solves your problem:

@Rule
public TemporaryFolder folder = new TemporaryFolder();

From the documentation:

The TemporaryFolder Rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails)


Update:

If you are using JUnit Jupiter (version 5.1.1 or greater), you have the option to use JUnit Pioneer which is the JUnit 5 Extension Pack.

Copied from the project documentation:

For example, the following test registers the extension for a single test method, creates and writes a file to the temporary directory and checks its content.

@Test
@ExtendWith(TempDirectory.class)
void test(@TempDir Path tempDir) {
    Path file = tempDir.resolve("test.txt");
    writeFile(file);
    assertExpectedFileContent(file);
}

More info in the JavaDoc and the JavaDoc of TempDirectory

Gradle:

dependencies {
    testImplementation 'org.junit-pioneer:junit-pioneer:0.1.2'
}

Maven:

<dependency>
   <groupId>org.junit-pioneer</groupId>
   <artifactId>junit-pioneer</artifactId>
   <version>0.1.2</version>
   <scope>test</scope>
</dependency>

Update 2:

The @TempDir annotation was added to the JUnit Jupiter 5.4.0 release as an experimental feature. Example copied from the JUnit 5 User Guide:

@Test
void writeItemsToFile(@TempDir Path tempDir) throws IOException {
    Path file = tempDir.resolve("test.txt");

    new ListWriter(file).write("a", "b", "c");

    assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
}

Column calculated from another column?

You can use generated columns from MYSQL 5.7.

Example Usage:

ALTER TABLE tbl_test
ADD COLUMN calc_val INT 
GENERATED ALWAYS AS (((`column1` - 1) * 16) + `column2`) STORED;

VIRTUAL / STORED

  • Virtual: calculated on the fly when a record is read from a table (default)
  • Stored: calculated when a new record is inserted/updated within the table

How to convert FormData (HTML5 object) to JSON

Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:

// original version from @dzuc
const data = Array.from(formData.entries())
  .reduce((memo, pair) => ({
    ...memo,
    [pair[0]: pair[1],
  }), {})

// with array destructuring
const data = Array.from(formData.entries())
  .reduce((memo,[key, value]) => ({
    ...memo,
    [key]: value,
  }), {})

Importing CSV with line breaks in Excel 2007

This is for Excel 2016:

Just had the same problem with line breaks inside a csv file with the Excel Wizard.

Afterwards I was trying it with the "New Query" Feature: Data -> New Query -> From File -> From CSV -> Choose the File -> Import -> Load

It was working perfectly and a very quick workaround for all of you that have the same problem.

How to install JQ on Mac by command-line?

The simplest way to install jq and test that it works is through brew and then using the simplest filter that merely formats the JSON

Install

brew is the easiest way to manage packages on a mac:

brew install jq

Need brew? Run the following command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Failing that: instructions to install and use are on https://brew.sh/

Test

The . filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)

echo '{ "name":"John", "age":31, "city":"New York" }' | jq .

The result should appear like so in your terminal:

{
  "name": "John",
  "age": 31,
  "city": "New York"
}

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

Found conflicts between different versions of the same dependent assembly that could not be resolved

I could solve this installing Newtonsoft Json in the web project with nugget packages

How can you detect the version of a browser?

This is a Update on Fzs2 & kennebec For New Edge Chromium

_x000D_
_x000D_
function get_browser() {
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 
    if(/trident/i.test(M[1])){
        tem=/\brv[ :]+(\d+)/g.exec(ua) || []; 
        return {name:'IE',version:(tem[1]||'')};
        }   
    if(M[1]==='Chrome'){
        tem=ua.match(/\bEdg\/(\d+)/)
        if(tem!=null)   {return {name:'Edge(Chromium)', version:tem[1]};}
        tem=ua.match(/\bOPR\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }   
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
    return {
      name: M[0],
      version: M[1]
    };
 }

var browser=get_browser(); // browser.name = 'Edge(Chromium)'
                           // browser.version = '86'

console.log(browser);
_x000D_
_x000D_
_x000D_

Android: Flush DNS

Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.

Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb

Comparing strings in C# with OR in an if statement

Here's a more valid way which also check if your textbox is filled with only blanks.

// When spaces are not allowed
if (string.IsNullOrWhiteSpace(txtBox1.Text) || string.IsNullOrWhiteSpace(txtBox2.Text))
  //...give error...

// When spaces are allowed
if (string.IsNullOrEmpty(txtBox1.Text) || string.IsNullOrEmpty(txtBox2.Text))
  //...give error...

The edited answer of @Habib.OSU is also fine, this is just another approach.

fatal: does not appear to be a git repository

You've got the syntax for the scp-style way of specifying a repository slightly wrong - it has to be:

[user@]host.xz:path/to/repo.git/

... as you can see in the git clone documentation. You should use instead the URL:

[email protected]:/gittest.git

i.e. in the URL you're using, you missed out the : (colon)

To update the URL for origin you could do:

git remote set-url origin [email protected]:/gittest.git

Abstract Class vs Interface in C++

An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error when multiline string included new line (\n) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.

Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.

I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.

HTTPS connections over proxy servers

as far as i can remember, you need to use a HTTP CONNECT query on the proxy. this will convert the request connection to a transparent TCP/IP tunnel.

so you need to know if the proxy server you use support this protocol.

Getting reference to child component in parent component

You can use ViewChild

<child-tag #varName></child-tag>

@ViewChild('varName') someElement;

ngAfterViewInit() {
  someElement...
}

where varName is a template variable added to the element. Alternatively, you can query by component or directive type.

There are alternatives like ViewChildren, ContentChild, ContentChildren.

@ViewChildren can also be used in the constructor.

constructor(@ViewChildren('var1,var2,var3') childQuery:QueryList)

The advantage is that the result is available earlier.

See also http://www.bennadel.com/blog/3041-constructor-vs-property-querylist-injection-in-angular-2-beta-8.htm for some advantages/disadvantages of using the constructor or a field.

Note: @Query() is the deprecated predecessor of @ContentChildren()

Update

Query is currently just an abstract base class. I haven't found if it is used at all https://github.com/angular/angular/blob/2.1.x/modules/@angular/core/src/metadata/di.ts#L145

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I Insert data into SQL Server using VBNet

Function ExtSql(ByVal sql As String) As Boolean
    Dim cnn As SqlConnection
    Dim cmd As SqlCommand
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        cmd = New SqlCommand
        cmd.Connection = cnn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cnn.Close()
        cmd.Dispose()
    Catch ex As Exception
        cnn.Close()
        Return False
    End Try
    Return True
End Function

create unique id with javascript

put in your namespace an instance similar to the following one

var myns = {/*.....*/};
myns.uid = new function () {
    var u = 0;
    this.toString = function () {
        return 'myID_' + u++;
    };
};
console.dir([myns.uid, myns.uid, myns.uid]);

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How to get scrollbar position with Javascript?

You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.

Convert string to ASCII value python

You can use a list comprehension:

>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]

How to query GROUP BY Month in a Year

You can use:

    select FK_Items,Sum(PoiQuantity) Quantity  from PurchaseOrderItems POI
    left join PurchaseOrder PO ON po.ID_PurchaseOrder=poi.FK_PurchaseOrder
    group by FK_Items,DATEPART(MONTH, TransDate)

How to insert an item into a key/value pair object?

Use a linked list. It was designed for this exact situation.
If you still need the dictionary O(1) lookups, use both a dictionary and a linked list.

Convert bytes to int?

Assuming you're on at least 3.2, there's a built in for this:

int.from_bytes( bytes, byteorder, *, signed=False )

...

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

The signed argument indicates whether two’s complement is used to represent the integer.


## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

How to stop (and restart) the Rails Server?

On OSX, you can take advantage of the UNIX-like command line - here's what I keep handy in my .bashrc to enable me to more easily restart a server that's running in background (-d) mode (note that you have to be in the Rails root directory when running this):

alias restart_rails='kill -9 `cat tmp/pids/server.pid`; rails server -d'

My initial response to the comment by @zane about how the PID file isn't removed was that it might be behavior dependent on the Rails version or OS type. However, it's also possible that the shell runs the second command (rails server -d) sooner than the kill can actually cause the previous running instance to stop.

So alternatively, kill -9 cat tmp/pids/server.pid && rails server -d might be more robust; or you can specifically run the kill, wait for the tmp/pids folder to empty out, then restart your new server.

Clicking URLs opens default browser

The method boolean shouldOverrideUrlLoading(WebView view, String url) was deprecated in API 24. If you are supporting new devices you should use boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request).

You can use both by doing something like this:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    });
} else {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
}

adding classpath in linux

I don't like setting CLASSPATH. CLASSPATH is a global variable and as such it is evil:

  • If you modify it in one script, suddenly some java programs will stop working.
  • If you put there the libraries for all the things which you run, and it gets cluttered.
  • You get conflicts if two different applications use different versions of the same library.
  • There is no performance gain as libraries in the CLASSPATH are not shared - just their name is shared.
  • If you put the dot (.) or any other relative path in the CLASSPATH that means a different thing in each place - that will cause confusion, for sure.

Therefore the preferred way is to set the classpath per each run of the jvm, for example:

java -Xmx500m -cp ".:../somejar.jar:../mysql-connector-java-5.1.6-bin.jar"    "folder.subfolder../dit1/some.xml

If it gets long the standard procedure is to wrap it in a bash or batch script to save typing.

How to compare two NSDates: Which is more recent?

Why don't you guys use these NSDate compare methods:

- (NSDate *)earlierDate:(NSDate *)anotherDate;
- (NSDate *)laterDate:(NSDate *)anotherDate;

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

+--------------------+-------------------+--------+
|                 _c5|                _c7|count(1)|
+--------------------+-------------------+--------+
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|
+--------------------+-------------------+--------+

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

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

Your problem is that you have declare twice the exec-maven-plugin :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-  
      integration\src\main\java\example\Main< /mainClass>
    </configuration>
</plugin>

...

< plugin>
    < groupId>org.codehaus.mojo</groupId>
    < artifactId>exec-maven-plugin</artifactId>
    < version>1.2</version>
< /plugin>

How can I tell Moq to return a Task?

Your method doesn't have any callbacks so there is no reason to use .CallBack(). You can simply return a Task with the desired values using .Returns() and Task.FromResult, e.g.:

MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.FromResult(someValue));

Update 2014-06-22

Moq 4.2 has two new extension methods to assist with this.

mock.Setup(arg=>arg.DoSomethingAsync())
    .ReturnsAsync(someValue);

mock.Setup(arg=>arg.DoSomethingAsync())        
    .ThrowsAsync(new InvalidOperationException());

Update 2016-05-05

As Seth Flowers mentions in the other answer, ReturnsAsync is only available for methods that return a Task<T>. For methods that return only a Task,

.Returns(Task.FromResult(default(object)))

can be used.

As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);, e.g.:

mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.CompletedTask);

How to center horizontal table-cell

If you add text-align: center to the declarations for .columns-container then they align centrally:

.columns-container {
    display: table-cell;
    height: 100%;
    width:600px;
    text-align: center;
}

_x000D_
_x000D_
/*************************_x000D_
 * Sticky footer hack_x000D_
 * Source: http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/_x000D_
 ************************/_x000D_
_x000D_
/* Stretching all container's parents to full height */_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
_x000D_
#container {_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
_x000D_
.section {_x000D_
  display: table-row;_x000D_
  height: 1px;_x000D_
}_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
_x000D_
.section.expand {_x000D_
  height: auto;_x000D_
}_x000D_
/*************************_x000D_
 * Full height columns_x000D_
 ************************/_x000D_
_x000D_
/* We need one extra container, setting it to full width */_x000D_
_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
width:600px;_x000D_
text-align: center;_x000D_
}_x000D_
/* Creating columns */_x000D_
_x000D_
.column {_x000D_
  /* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
  display: inline-block;_x000D_
  /* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
  vertical-align: top;_x000D_
  height: 100%;_x000D_
  width: 100px;_x000D_
}_x000D_
/****************************************************************_x000D_
 * Just some coloring so that we're able to see height of columns_x000D_
 ****************************************************************/_x000D_
_x000D_
header {_x000D_
  background-color: yellow;_x000D_
}_x000D_
#a {_x000D_
  background-color: pink;_x000D_
}_x000D_
#b {_x000D_
  background-color: lightgreen;_x000D_
}_x000D_
#c {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
footer {_x000D_
  background-color: purple;_x000D_
}
_x000D_
<div id="container">_x000D_
  <header class="section">_x000D_
    foo_x000D_
  </header>_x000D_
_x000D_
  <div class="section expand">_x000D_
    <div class="columns-container">_x000D_
      <div class="column" id="a">_x000D_
        <p>Contents A</p>_x000D_
      </div>_x000D_
      <div class="column" id="b">_x000D_
        <p>Contents B</p>_x000D_
      </div>_x000D_
      <div class="column" id="c">_x000D_
        <p>Contents C</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <footer class="section">_x000D_
    bar_x000D_
  </footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This does, though, require that you reset the .column elements to text-align: left (assuming you want them left-aligned, obviously (JS Fiddle demo).

What is w3wp.exe?

  • A worker process runs as an executables file named W3wp.exe
  • A Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.

  • The worker process is controlled by the www service.

  • worker processes also run application code, Such as ASP .NET applications and XML web Services.

  • When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.

  • When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.htmlenter image description here

Convert datetime object to a String of date only in Python

You could use simple string formatting methods:

>>> dt = datetime.datetime(2012, 2, 23, 0, 0)
>>> '{0.month}/{0.day}/{0.year}'.format(dt)
'2/23/2012'
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year)
'2/23/2012'

Bridged networking not working in Virtualbox under Windows 10

From Reddit:

https://www.reddit.com/r/Windows10/comments/39af75/for_my_win10_companions_heres_how_to_get/

I can't see the original source in this thread, although I would like to.

I am using these instructions with a laptop that upgraded from windows 8 to windows 10. I have to repeat the last instructions after rebooting.

I have test an get solution for my self and want to share my solution. - Host Only worked - Bridge Adapter worked

My Configuration is - Surface Pro 1 - Clean install Windows 10 x64 build 10130 - VirtualBox-5.0.0_RC1-100731-Win.exe

(this is my opinion but not tested on how to remove previous version by install VirtualBox-5.0.0_RC1-100731-Win.exe with select all function to install its will fault and rollback all, then its same as uninstall)

Install Step - Right Click on VirtualBox-5.0.0_RC1-100731-Win.exe and select "Run as Administrator" - "Unselect" option bridge network

  • next until finish

  • Open "Device Manager", you can use search bar to get this, under "Network adapters" then Right Click "VirtualBox Host-Only Ethernet Adapter" select "Update Driver Software" select "Search automactic" wait until its finish

  • Open "Network Connections", you can use search bar to get this, at here you should find VirtualBox Host-Only Ethernet Adapter
  • Open "CMD", you can use search bar to get this, Right Click and Select Run as Administrator
  • cd to your install path and run command "VirtualBox-5.0.0_RC1-100731-Win.exe -extract" its will return pop-up tell where is extracted folder
  • in extracted folder extract "VirtualBox-5.0.0_RC1-r100731-MultiArch_amd64.msi" by 7-Zip or any similar
  • in msi extracted folder rename all files by remove file_ in front of them
  • copy "VBoxNetFltNobj.sys" and "VBoxNetFlt.sys" to C:\Windows\System32\
  • Open "CMD", you can use search bar to get this, Right Click and Select Run as Administrator run command "regsvr32.exe /s VBoxNetFltNobj.sys" run command "regsvr32.exe /s VBoxNetFlt.sys"
  • Open "Network Connections", you can use search bar to get this, Right Click on any real network adapter select Properties select Install select Service select "Have Disk" and browse to "VBoxDrv.inf" select "VirtualBox NDIS6 Bridged Networking Driver" after finish install you should see its avaliable in this connection
  • On Start Menu Right Click on "Orcle VM VirtualBox" select open file location

  • Right Click on Shortcut then select properties on tab "Compatibility" checked "Run this Program as Administrator"

!!! this very important to run application with adminstrator if not you will lose host-only network adapter

  • Open "Virtual Box" select file > preference select network then select Host On Network select edit change ip to 192.168.56.1 and netmask to 255.255.255.0
  • Now you can use both host-only and bridge network on your guest

I think reason why normal installation was error is about Administrator access level when regis service and run application

Sorry for my bad english and this is so long procedure

Hope this will work for you too. ^_^!

Simpler way to check if variable is not equal to multiple string values?

For your first code, you can use a short alteration of the answer given by @ShankarDamodaran using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

or even shorter with [] notation available since php 5.4 as pointed out by @Forty in the comments

if ( !in_array($some_variable, ['uk','in'], true ) ) {

is the same as:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

equals

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

How can I show/hide component with JSF?

check this below code. this is for dropdown menu. In this if we select others then the text box will show otherwise text box will hide.

function show_txt(arg,arg1)
{
if(document.getElementById(arg).value=='other')
{
document.getElementById(arg1).style.display="block";
document.getElementById(arg).style.display="none";
}
else
{
document.getElementById(arg).style.display="block";
document.getElementById(arg1).style.display="none";
}
}
The HTML code here :

<select id="arg" onChange="show_txt('arg','arg1');">
<option>yes</option>
<option>No</option>
<option>Other</option>
</select>
<input type="text" id="arg1" style="display:none;">

or you can check this link click here

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css

With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.

Then just replace 1140px with 98% of the screen width.

@media (min-width: 1200px) {
  .container {
    width: 1140px;
  }
}

enter image description here

After editing

@media (min-width: 1200px) {
  .container {
    width: 98%;
  }
}

enter image description here Save and restart your notebook


Update

Recently had to wider Jupyter cells on an environment it is installed, which led me to come back here and remind myself.

If you need to do it in virtual env you installed jupyter on. You can find the css file in this subdir

env/lib/python3.6/site-packages/notebook/static/style/stye.min.css

What is the difference between encrypting and signing in asymmetric encryption?

Signing is producing a "hash" with your private key that can be verified with your public key. The text is sent in the clear.

Encrypting uses the receiver's public key to encrypt the data; decoding is done with their private key.

So, the use of keys is not reversed (otherwise your private key wouldn't be private anymore!).

How do I add a reference to the MySQL connector for .NET?

This is an older question, but I found it yesterday while struggling with getting the MySQL Connector reference working properly on examples I'd found on the web. I'm working with VS 2010 on Win7 64 bit but have to work with .NET 3.5.

As others have stated, you need to download the .Net & Mono versions (I don't know why this is true, but it's what I've found works). The link to the connectors is given above in the earlier answers.

  • Extract the connectors somewhere convenient.
  • Open the project in Visual Studio, then on the menu bar navigate to Solution Explorer (View > Solution Explorer), and choose Properties (first box on the far left of the toolbar. The Solution Explorer shows up in the top right pane for me, but YMMV).
  • In Properties, select References & locate the instance for mysql.data. It's likely to have a yellow bang on it (Yellow triangle with exclamation point in it). Remove it.
  • Then on the menu bar, navigate to Project > Add Reference... > Browse > point to where you downloaded the connectors. I have only been able to get the V2 version to work, but that may be a factor of my platform, not sure.
  • Clean & build your application. You should now be able to use the MySQL connectors to talk to your database.
  • You can also now downgrade your .NET instance if you need to (we're constrained to .NET 3.5, but mysql.data.dll wants 4.0 at the time of my writing this). On the menu bar, navigate to the properties of your project (Project > Properties). Choose the Application tab > Target framework > Choose which .NET framework you want to use. You have to build the application at least once before you can change the .NET framework. Once you built once the connector will no longer complain about the lower version of .NET.

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

modify list of host names for your system:

C:\Windows\System32\drivers\etc\hosts

Make sure that you have the following entry:

127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem

(you may need to change modify permission to modify this file)

This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.

Android Studio Stuck at Gradle Download on create new project

Gradle is actually included with Android Studio (at least on the Mac OS X version.) I had to point it to the installed location, inside the Android Studio application "package contents" (can view by control/right-clicking on the application icon.)
Location of gradle inside Android Studio package

How to make multiple divs display in one line but still retain width?

You can float your column divs using float: left; and give them widths.

And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.

Hope this helps.

How do I duplicate a line or selection within Visual Studio Code?

  • For Jetbrains IDE Users who migrated to VSCode , no problem.

  • Install:
    1) JetBrains IDE Keymap: Extension
    2) vscode-intellij-idea-keybindings Extension (Preferred)

  • Use this Intellij Darcula Theme: Extension

  • The keymap has covered most of keyboard shortcuts of VS Code, and makes VS Code more 'JetBrains IDE like'.

  • Above extensions imports keybindings from JetBrains to VS Code. After installing the extension and restarting VS Code you can use VS Code just like IntelliJ IDEA, Webstorm, PyCharm, etc.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

does R stop no matter the N value you use? try to use small values and see if it's the mvrnorm function that is the issue or you could simply loop it on subsets. Insert the gc() function in the loop to free some RAM continuously

CSS: background image on background color

And if you want Generate a Black Shadow in the background, you can use the following:

background:linear-gradient( rgba(0, 0, 0, 0.5) 100%, rgba(0, 0, 0, 0.5)100%),url("logo/header-background.png");

Is there a simple way to convert C++ enum to string?

Here is a CLI program I wrote to easily convert enums to strings. Its easy to use, and takes about 5 seconds to get it done (including the time to cd to the directory containing the program, then run it, passing to it the file containing the enum).

Download here: http://www.mediafire.com/?nttignoozzz

Discussion topic on it here: http://cboard.cprogramming.com/projects-job-recruitment/127488-free-program-im-sharing-convertenumtostrings.html

Run the program with the "--help" argument to get a description how to use it.

npm notice created a lockfile as package-lock.json. You should commit this file

came out of this issue by changing the version in package.json file and also changing the name of the package and finally deleted the package-lock.json file

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

**

bundle install --no-deployment

**

$ jekyll help

jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby