Programs & Examples On #F script

F-Script is a scripting programming language for Mac OS X.

IE9 jQuery AJAX with CORS returns "Access is denied"

To solve this problem, also check if you have some included .js into your ajax file called: I received Access denied error while including shadowbox.js in my ajax.php

What is Shelving in TFS?

One point that is missed in a lot of these discussions is how you revert back on the SAME machine on which you shelved your changes. Perhaps obvious to most, but wasn't to me. I believe you perform an Undo Pending Changes - is that right?

I understand the process to be as follows:

  1. To shelve your current pending changes, right click the project, Shelve, add a shelve name
  2. This will save (or Shelve) the changes to the server (no-one will see them)
  3. You then do Undo Pending Changes to revert your code back to the last check-in point
  4. You can then do what you need to do with the reverted code baseline
  5. You can Unshelve the changes at any time (may require some merge confliction)

So, if you want to start some work which you may need to Shelve, make sure you check-in before you start, as the check-in point is where you'll return to when doing the Undo Pending Changes step above.

WPF: simple TextBox data binding

Just for future needs.

In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window to make it work.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

On Windows OS by default git is instaled with

core.ignorecase = true

This means that git repo files will be case insensitive, to change this you need to execute:

\yourLocalRepo> git config core.ignorecase false

you can find this configuration on .git\config file

form with no action and where enter does not reload page

an idea:

<form method="POST" action="javascript:void(0);" onSubmit="CheckPassword()">
    <input id="pwset" type="text" size="20" name='pwuser'><br><br>
    <button type="button" onclick="CheckPassword()">Next</button>
</form>

and

<script type="text/javascript">
    $("#pwset").focus();
    function CheckPassword()
    {
        inputtxt = $("#pwset").val();
        //and now your code
        $("#div1").load("next.php #div2");
        return false;
    }
</script>

How to use Bootstrap 4 in ASP.NET Core

Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.

Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)

The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write: Bower is maintained only.Recommend using LibManager

Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:

In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]

enter image description here

Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

MongoDB query multiple collections at once

One solution: add isAdmin: 0/1 flag to your post collection document.

Other solution: use DBrefs

Add an element to an array in Swift

In Swift 4.2: You can use

myArray.append("Tim") //To add "Tim" into array

or

myArray.insert("Tim", at: 0) //Change 0 with specific location 

Case vs If Else If: Which is more efficient?

it can do this for case statements as the values are compiler constants. An explanation in more detail is here http://sequence-points.blogspot.com/2007/10/why-is-switch-statement-faster-than-if.html

How to write to error log file in PHP

you can simply use :

error_log("your message");

By default, the message will be send to the php system logger.

"Error: Main method not found in class MyClass, please define the main method as..."

If you are running the correct class and the main is properly defined, also check if you have a class called String defined in the same package. This definition of String class will be considered and since it doesn't confirm to main(java.lang.String[] args), you will get the same exception.

  • It's not a compile time error since compiler just assumes you are defining a custom main method.

Suggestion is to never hide library java classes in your package.

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.

JavaScript function in href vs. onclick

This works

<a href="#" id="sampleApp" onclick="myFunction(); return false;">Click Here</a>

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Testing the type of a DOM element in JavaScript

roenving is correct BUT you need to change the test to:

if(element.nodeType == 1) {
//code
}

because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp

How to convert jsonString to JSONObject in Java

You can use google-gson. Details:

Object Examples

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(Serialization)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
==> json is {"value1":1,"value2":"abc"}

Note that you can not serialize objects with circular references since that will result in infinite recursion.

(Deserialization)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
==> obj2 is just like obj

Another example for Gson:

Gson is easy to learn and implement, you need to know is the following two methods:

-> toJson() – convert java object to JSON format

-> fromJson() – convert JSON into java object

import com.google.gson.Gson;

public class TestObjectToJson {
  private int data1 = 100;
  private String data2 = "hello";

  public static void main(String[] args) {
      TestObjectToJson obj = new TestObjectToJson();
      Gson gson = new Gson();

      //convert java object to JSON format
      String json = gson.toJson(obj);

      System.out.println(json);
  }

}

Output

{"data1":100,"data2":"hello"}

Resources:

Google Gson Project Home Page

Gson User Guide

Example

Angular ForEach in Angular4/Typescript?

you can try typescript's For :

selectChildren(data , $event){
   let parentChecked : boolean = data.checked;
   for(let o of this.hierarchicalData){
      for(let child of o){
         child.checked = parentChecked;
      }
   }
}

PHP read and write JSON from file

Try using second parameter for json_decode function:

$json = json_decode(file_get_contents($file), true);

Sql Server : How to use an aggregate function like MAX in a WHERE clause

You could use a sub query...

WHERE t1.field3 = (SELECT MAX(st1.field3) FROM table1 AS st1)

But I would actually move this out of the where clause and into the join statement, as an AND for the ON clause.

Date Conversion from String to sql Date in Java giving different output?

You need to use MM as mm stands for minutes.

There are two ways of producing month pattern.

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01

Full coding snippet:

        String startDate="01-Feb-2013"; // Input String
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
        java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
        java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
        System.out.println(sqlStartDate); // Outputs : 2013-02-01

Force git stash to overwrite added files

TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.

How to set size for local image using knitr for markdown?

If you are converting to HTML, you can set the size of the image using HTML syntax using:

  <img src="path/to/image" height="400px" width="300px" />

or whatever height and width you would want to give.

Remove characters from C# string

Sounds like an ideal application for RegEx -- an engine designed for fast text manipulation. In this case:

Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)

How to get status code from webclient?

You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}

Where can I find the TypeScript version installed in Visual Studio?

Two years after the question was asked, using Visual Studio Command Prompt still did not produce right answer for me. But the usual Help|About window seems working these days:

Snapshot of VS Community "About" dialog

UPDATE (June 2017):

  1. VS 2013 does NOT show this info. (Later note: VS 2017 Enterprise edition does not show this info either).

  2. VS uses Microsoft Build Engine (MSBuild) to compile Typescript files. MSBuild can support several major releases of Typescript, but About window shows only the latest one.

Here is how to get to the bottom of it:

A. To check which versions of Typescript are installed with your Visual Studio/MSBuild, inspect contents of C:\Program Files (x86)\Microsoft SDKs\TypeScript folder. For example, I have versions 1.0, 1.8 and 2.2:

Typescript versions as folder names

B. Check which version of Typescript is requested by your project. In *.csproj file, look for <TypeScriptToolsVersion> tag, or you can add it if it is missing, like this


<PropertyGroup> ... <TypeScriptToolsVersion>1.8</TypeScriptToolsVersion> ... </PropertyGroup>

C. Finally, you can check, which version of Typescript is actually used by MSBuild. In TOOLS | Options | Projects and Solutions | Build and Run set MSBuild project output verbosity to Detailed:

enter image description here

Then build your project and inspect the output: you should see the reference to one of Typescript folders described in (A).

How to grep Git commit diffs or contents for a certain word?

vim-fugitive is versatile for that kind of examining in Vim.

Use :Ggrep to do that. For more information you can install vim-fugitive and look up the turorial by :help Grep. And this episode: exploring-the-history-of-a-git-repository will guide you to do all that.

Authentication issue when debugging in VS2013 - iis express

In Visual Studio 2013 AND VS15 (but i guess if the same for all other version) just press F4 and change this two properties: -Anonymous Authentication: Disable -Windows Authentication: Enable

How to create a fixed sidebar layout with Bootstrap 4?

I used this in my code:

<div class="sticky-top h-100">
    <nav id="sidebar" class="vh-100">
        ....

this cause your sidebar height become 100% and fixed at top.

Remove useless zero digits from decimals in PHP

You can use:

print (floatval)(number_format( $Value), 2 ) );    

Are all Spring Framework Java Configuration injection examples buggy?

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

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

See here:

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

My solution: Installing libffi-dev with apt-get didn't help. But this helped: Installing libffi from source and then installing Python 3.8 from source.

My configuration: Ubuntu 16.04 LTS Python 3.8.2

Step by step:

I got the error message "ModuleNotFoundError: No module named '_ctypes'" when starting the debugger from Visual Studio Code, and when running python3 -c "import sklearn; sklearn.show_versions()".

  • download libffi v3.3 from https://github.com/libffi/libffi/releases
  • install libtool: sudo apt-get install libtool The file README.md from libffi mentions that autoconf and automake are also necessary. They were already installed on my system.
  • configure libffi without docs:

./configure --disable-docs

make check

sudo make install

After that my python installation could find _ctypes.

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

Dynamically select data frame columns using $ and a character value

too late.. but I guess I have the answer -

Here's my sample study.df dataframe -

   >study.df
   study   sample       collection_dt other_column
   1 DS-111 ES768098 2019-01-21:04:00:30         <NA>
   2 DS-111 ES768099 2018-12-20:08:00:30   some_value
   3 DS-111 ES768100                <NA>   some_value

And then -

> ## Selecting Columns in an Given order
> ## Create ColNames vector as per your Preference
> 
> selectCols <- c('study','collection_dt','sample')
> 
> ## Select data from Study.df with help of selection vector
> selectCols %>% select(.data=study.df,.)
   study       collection_dt   sample
1 DS-111 2019-01-21:04:00:30 ES768098
2 DS-111 2018-12-20:08:00:30 ES768099
3 DS-111                <NA> ES768100
> 

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

Along with other provided solutions, make sure to have the following within project/build.gradle

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

How to check if a table exists in a given schema

It depends on what you want to test exactly.

Information schema?

To find "whether the table exists" (no matter who's asking), querying the information schema (information_schema.tables) is incorrect, strictly speaking, because (per documentation):

Only those tables and views are shown that the current user has access to (by way of being the owner or having some privilege).

The query provided by @kong can return FALSE, but the table can still exist. It answers the question:

How to check whether a table (or view) exists, and the current user has access to it?

SELECT EXISTS (
   SELECT FROM information_schema.tables 
   WHERE  table_schema = 'schema_name'
   AND    table_name   = 'table_name'
   );

The information schema is mainly useful to stay portable across major versions and across different RDBMS. But the implementation is slow, because Postgres has to use sophisticated views to comply to the standard (information_schema.tables is a rather simple example). And some information (like OIDs) gets lost in translation from the system catalogs - which actually carry all information.

System catalogs

Your question was:

How to check whether a table exists?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   AND    c.relkind = 'r'    -- only tables
   );

Use the system catalogs pg_class and pg_namespace directly, which is also considerably faster. However, per documentation on pg_class:

The catalog pg_class catalogs tables and most everything else that has columns or is otherwise similar to a table. This includes indexes (but see also pg_index), sequences, views, materialized views, composite types, and TOAST tables;

For this particular question you can also use the system view pg_tables. A bit simpler and more portable across major Postgres versions (which is hardly of concern for this basic query):

SELECT EXISTS (
   SELECT FROM pg_tables
   WHERE  schemaname = 'schema_name'
   AND    tablename  = 'table_name'
   );

Identifiers have to be unique among all objects mentioned above. If you want to ask:

How to check whether a name for a table or similar object in a given schema is taken?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   );

Alternative: cast to regclass

SELECT 'schema_name.table_name'::regclass

This raises an exception if the (optionally schema-qualified) table (or other object occupying that name) does not exist.

If you do not schema-qualify the table name, a cast to regclass defaults to the search_path and returns the OID for the first table found - or an exception if the table is in none of the listed schemas. Note that the system schemas pg_catalog and pg_temp (the schema for temporary objects of the current session) are automatically part of the search_path.

You can use that and catch a possible exception in a function. Example:

A query like above avoids possible exceptions and is therefore slightly faster.

to_regclass(rel_name) in Postgres 9.4+

Much simpler now:

SELECT to_regclass('schema_name.table_name');

Same as the cast, but it returns ...

... null rather than throwing an error if the name is not found

word-wrap break-word does not work in this example

This combination of properties helped for me:

display: inline-block;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal;
line-break: strict;
hyphens: none;
-webkit-hyphens: none;
-moz-hyphens: none;

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.

Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.

This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.

See also here:

The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.


In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.


1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2

Can I specify multiple users for myself in .gitconfig?

There is a simple solution that seems to work well for avoiding mistakes.

Simply remove the [user] section from your ~/.gitconfig, which will prevent you from making any commits without setting user.name for each repository.

In your ~/.bashrc, add some simple aliases for the user and email:

alias ggmail='git config user.name "My Name";git config user.email [email protected]'
alias gwork='git config user.name "My Name";git config user.email [email protected]'

How to schedule a periodic task in Java?

Have you tried Spring Scheduler using annotations ?

@Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
    //body can be another method call which returns some value.
}

you can do this with xml as well.

 <task:scheduled-tasks>
   <task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
 <task:scheduled-tasks>

Understanding Popen.communicate

Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.

Do it like this:

p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)

# get output from process "Something to print"
one_line_output = p.stdout.readline()

# write 'a line\n' to the process
p.stdin.write('a line\n')

# get output from process "not time to break"
one_line_output = p.stdout.readline() 

# write "n\n" to that process for if r=='n':
p.stdin.write('n\n') 

# read the last output from the process  "Exiting"
one_line_output = p.stdout.readline()

What you would do to remove the error:

all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]

But since communicate closes the stdout and stdin and stderr, you can not read or write after you called communicate.

How to forward declare a template class in namespace std?

The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:

namespace std {
  template<class T, class Allocator = std::allocator<T>>
  class list;
}

But to make even such a forward declaration in namespace std is explicitly prohibited by the standard: the only thing you're allowed to put in std is a template specialisation, commonly std::less on a user-defined type. Someone else can cite the relevant text if necessary.

Just #include <list> and don't worry about it.

Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H instead of __TEST__. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.

Regex: Specify "space or start of string" and "space or end of string"

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s)  #the | means or. () is a capturing group. 


/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=\s|$)          #to look ahead.

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

What's a good (free) visual merge tool for Git? (on windows)

Another free option is jmeld: http://keeskuip.home.xs4all.nl/jmeld/

It's a java tool and could therefore be used on several platforms.

But (as Preet mentioned in his answer), free is not always the best option. The best diff/merge tool I ever came across is Araxis Merge. Standard edition is available for 99 EUR which is not that much.

They also provide a documentation for how to integrate Araxis with msysGit.

If you want to stick to a free tool, JMeld comes pretty close to Araxis.

Create zip file and ignore directory structure

Alternatively, you could create a temporary symbolic link to your file:

ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$

This works also for a directory.

How to disable Google Chrome auto update?

For Ubuntu:

  1. go to 'Software & Updates'.
  2. click 'Other Software' tab.
  3. Uncheck the next checkbox 'http://dl.google.com/linux/chrome/deb/ stable main'

enter image description here

Git command to checkout any branch and overwrite local changes

Couple of points:

  • I believe git stash + git stash drop could be replaced with git reset --hard
  • ... or, even shorter, add -f to checkout command:

    git checkout -f -b $branch
    

    That will discard any local changes, just as if git reset --hard was used prior to checkout.

As for the main question: instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.

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

I'm using Node.js v.6.0.0 and the fastest is the one with index (the 3rd method in Lo Sauer's answer).

The second is:

_x000D_
_x000D_
function count(s, c) {_x000D_
  var n = 0;_x000D_
  for (let x of s) {_x000D_
    if (x == c)_x000D_
      n++;_x000D_
  }_x000D_
  return n;_x000D_
}
_x000D_
_x000D_
_x000D_

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

How can I see the current value of my $PATH variable on OS X?

You need to use the command echo $PATH to display the PATH variable or you can just execute set or env to display all of your environment variables.

By typing $PATH you tried to run your PATH variable contents as a command name.

Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:

/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin

To me this list appears to be complete.

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

Solutions for INSERT OR UPDATE on SQL Server

You can use this query. Work in all SQL Server editions. It's simple, and clear. But you need use 2 queries. You can use if you can't use MERGE

    BEGIN TRAN

    UPDATE table
    SET Id = @ID, Description = @Description
    WHERE Id = @Id

    INSERT INTO table(Id, Description)
    SELECT @Id, @Description
    WHERE NOT EXISTS (SELECT NULL FROM table WHERE Id = @Id)

    COMMIT TRAN

NOTE: Please explain answer negatives

Convert nullable bool? to bool

The complete way would be:

bool b1;
bool? b2 = ???;
if (b2.HasValue)
   b1 = b2.Value;

Or you can test for specific values using

bool b3 = (b2 == true); // b2 is true, not false or null

What is log4j's default log file dumping path

By default, Log4j logs to standard output and that means you should be able to see log messages on your Eclipse's console view. To log to a file you need to use a FileAppender explicitly by defining it in a log4j.properties file in your classpath.

Create the following log4j.properties file in your classpath. This allows you to log your message to both a file as well as your console.

log4j.rootLogger=debug, stdout, file

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=example.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%p %t %c - %m%n

Note: The above creates an example.log in your current working directory (i.e. Eclipse's project directory) so that the same log4j.properties could work with different projects without overwriting each other's logs.

References:
Apache log4j 1.2 - Short introduction to log4j

How to make a .NET Windows Service start right after the installation?

To add to ScottTx's answer, here's the actual code to start the service if you're doing it the Microsoft way (ie. using a Setup project etc...)

(excuse the VB.net code, but this is what I'm stuck with)

Private Sub ServiceInstaller1_AfterInstall(ByVal sender As System.Object, ByVal e As System.Configuration.Install.InstallEventArgs) Handles ServiceInstaller1.AfterInstall
    Dim sc As New ServiceController()
    sc.ServiceName = ServiceInstaller1.ServiceName

    If sc.Status = ServiceControllerStatus.Stopped Then
        Try
            ' Start the service, and wait until its status is "Running".
            sc.Start()
            sc.WaitForStatus(ServiceControllerStatus.Running)

            ' TODO: log status of service here: sc.Status
        Catch ex As Exception
            ' TODO: log an error here: "Could not start service: ex.Message"
            Throw
        End Try
    End If
End Sub

To create the above event handler, go to the ProjectInstaller designer where the 2 controlls are. Click on the ServiceInstaller1 control. Go to the properties window under events and there you'll find the AfterInstall event.

Note: Don't put the above code under the AfterInstall event for ServiceProcessInstaller1. It won't work, coming from experience. :)

AngularJS Uploading An Image With ng-upload

You can try ng-file-upload angularjs plugin (instead of ng-upload).

It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.

html

<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script> 
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script> 

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', //upload.php script, node.js route, or servlet url
        data: {myObj: $scope.myModelObj},
        file: file,
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).then(function(response) {
        var data = response.data;
        // file is uploaded successfully
        console.log(data);
      });
    }
  };
}];

Why does AngularJS include an empty option in select?

A quick solution:

select option:empty { display:none }

Hope it helps someone. Ideally, the selected answer should be the approach but if in case that's not possible then should work as a patch.

What is a Subclass

A subclass is something that extends the functionality of your existing class. I.e.

Superclass - describes the catagory of objects:

public abstract class Fruit {

    public abstract Color color;

}

Subclass1 - describes attributes of the individual Fruit objects:

public class Apple extends Fruit {

    Color color = red;

}

Subclass2 - describes attributes of the individual Fruit objects:

public class Banana extends Fruit {

    Color color = yellow;

}

The 'abstract' keyword in the superclass means that the class will only define the mandatory information that each subclass must have i.e. A piece of fruit must have a color so it is defines in the super class and all subclasses must 'inherit' that attribute and define the value that describes the specific object.

Does that make sense?

wget: unable to resolve host address `http'

remove the http or https from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip . this worked fine for me.

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

Install IPA with iTunes 12

Do not use any service similar to https://www.diawi.com/ as it can potentially have huge security implications. Using this kind of process and with some clever coding skills, a third party can inject extra stuff in you application. And they are basically charging you for something that you can do yourself.

In iTunes 12.7.x, it is still possible to install an ipa directly on a device with a simple drag-n-drop. Look at @ganesh ubale' solution here or the other answers at https://stackoverflow.com/a/46520816/609862 or https://stackoverflow.com/a/46229114/609862.

The Apple developer web site also have detailed information about how to configure a web site for installing an IPA wirelessly (by simply sharing the download link).

How to add days to the current date?

SELECT DateAdd(5,day(getdate()) this is for adding 5 days to current days. for eg:today date is 23/08/2018 it became 28/08/2018 by using the above query

How do you update a DateTime field in T-SQL?

Is there maybe a trigger on the table setting it back?

jquery select option click handler

What I have done in this situation is that I put in the option elements OnClick event like this:

<option onClick="something();">Option Name</option>

Then just create a script function like this:

function something(){
    alert("Hello"); 
    }

UPDATE: Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm

how to write procedure to insert data in to the table in phpmyadmin?

# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12

(IN numRating_Chapter INT(11) UNSIGNED, 

 IN txtRating_Chapter VARCHAR(250),

 IN chapterName VARCHAR(250),

 IN addedBy VARCHAR(250)

)

BEGIN
DECLARE numRating_Chapter INT;

DECLARE txtRating_Chapter VARCHAR(250);

DECLARE chapterName1 VARCHAR(250);

DECLARE addedBy1 VARCHAR(250);

DECLARE chapterId INT;

DECLARE studentId INT;

SET chapterName1 = chapterName;
SET addedBy1 = addedBy;

SET chapterId = (SELECT chapterId 
                   FROM chapters 
                   WHERE chaptername = chapterName1);

SET studentId = (SELECT Id 
                   FROM students 
                   WHERE email = addedBy1);

SELECT chapterId;
SELECT studentId;

INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);

END //

//DELIMITER;

HTML: can I display button text in multiple lines?

Yes, you can have it on multiple lines using the white-space css property :)

_x000D_
_x000D_
input[type="submit"] {_x000D_
    white-space: normal;_x000D_
    width: 100px;_x000D_
}
_x000D_
<input type="submit" value="Some long text that won't fit." />
_x000D_
_x000D_
_x000D_

add this to your element

 white-space: normal;
 width: 100px;

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa
</div>

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use

Error Importing SSL certificate : Not an X.509 Certificate

I will also add my experience here in case it helps someone:

At work we commonly use the following two commands to enable IntelliJ IDEA to talk to various servers, for example our internal maven repositories:

[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool 
    -printcert -rfc -sslserver maven.services.{our-company}.com:443 > public.crt

[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
    -import -storepass changeit -noprompt -trustcacerts -alias services.{our-company}.com 
    -keystore lib\security\cacerts -file public.crt

Now, what sometimes happens is that the keytool -printcert command is unable to communicate with the outside world due to temporary connectivity issues, such as the firewall preventing it, the user forgot to start his VPN, whatever. It is a fact of life that this may happen. This is not actually the problem.

The problem is that when the stupid tool encounters such an error, it does not emit the error message to the standard error device, it emits it to the standard output device!

So here is what ends up happening:

  • When you execute the first command, you don't see any error message, so you have no idea that it failed. However, instead of a key, the public.crt file now contains an error message saying keytool error: java.lang.Exception: No certificate from the SSL server.
  • When you execute the second command, it finds an error message instead of a key in public.crt, so it fails, saying keytool error: java.lang.Exception: Input not an X.509 certificate.

Bottom line is: after keytool -printcert ... > public.crt always dump the contents of public.crt to make sure it is actually a key and not an error message before proceeding to run keytool -import ... -file public.crt

header('HTTP/1.0 404 Not Found'); not doing anything

Use these codes for 404 not found.

if(strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  readfile('404missing.html');
  exit();
}

Here 404missing.html is your Not found design page. (it can be .html or .php)

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

Simple way to encode a string according to a password?

Assuming you are only looking for simple obfuscation that will obscure things from the very casual observer, and you aren't looking to use third party libraries. I'd recommend something like the Vigenere cipher. It is one of the strongest of the simple ancient ciphers.

Vigenère cipher

It's quick and easy to implement. Something like:

import base64

def encode(key, string):
    encoded_chars = []
    for i in xrange(len(string)):
        key_c = key[i % len(key)]
        encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = "".join(encoded_chars)
    return base64.urlsafe_b64encode(encoded_string)

Decode is pretty much the same, except you subtract the key.

It is much harder to break if the strings you are encoding are short, and/or if it is hard to guess the length of the passphrase used.

If you are looking for something cryptographic, PyCrypto is probably your best bet, though previous answers overlook some details: ECB mode in PyCrypto requires your message to be a multiple of 16 characters in length. So, you must pad. Also, if you want to use them as URL parameters, use base64.urlsafe_b64_encode(), rather than the standard one. This replaces a few of the characters in the base64 alphabet with URL-safe characters (as it's name suggests).

However, you should be ABSOLUTELY certain that this very thin layer of obfuscation suffices for your needs before using this. The Wikipedia article I linked to provides detailed instructions for breaking the cipher, so anyone with a moderate amount of determination could easily break it.

JPA - Persisting a One to Many relationship

One way to do that is to set the cascade option on you "One" side of relationship:

class Employee {
   // 

   @OneToMany(cascade = {CascadeType.PERSIST})
   private Set<Vehicles> vehicles = new HashSet<Vehicles>();

   //
}

by this, when you call

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

it will save the vehicles too.

Creating csv file with php

Its blank because you are writing to file. you should write to output using php://output instead and also send header information to indicate that it's csv.

Example

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
        'aaa,bbb,ccc,dddd',
        '123,456,789',
        '"aaa","bbb"'
);

$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val);
}
fclose($fp);

sizing div based on window width

Viewport units for CSS

1vw = 1% of viewport width
1vh = 1% of viewport height

This way, you don't have to write many different media queries or javascript.

If you prefer JS

window.innerWidth;
window.innerHeight;

Input placeholders for Internet Explorer

After trying some suggestions and seeing issues in IE here is the one that works:

https://github.com/parndt/jquery-html5-placeholder-shim/

What I have liked - you just include the js file. No need to initiate it or anything.

Use URI builder in Android or create URL with variables

Excellent answer from above turned into a simple utility method.

private Uri buildURI(String url, Map<String, String> params) {

    // build url with parameters.
    Uri.Builder builder = Uri.parse(url).buildUpon();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.appendQueryParameter(entry.getKey(), entry.getValue());
    }

    return builder.build();
}

Regex to check if valid URL that ends in .jpg, .png, or .gif

(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png)

This will mach all images from this string:

background: rgb(255, 0, 0) url(../res/img/temp/634043/original/cc3d8715eed0c.jpg) repeat fixed left top; cursor: auto;
<div id="divbg" style="background-color:#ff0000"><img id="bg" src="../res/img/temp/634043/original/cc3d8715eed0c.jpg" width="100%" height="100%" /></div>
background-image: url(../res/img/temp/634043/original/cc3d8715eed0c.png);
background: rgb(255, 0, 0) url(http://google.com/res/../img/temp/634043/original/cc3    _d8715eed0c.jpg) repeat fixed left top; cursor: auto;
background: rgb(255, 0, 0) url(https://google.com/res/../img/temp/634043/original/cc3_d8715eed0c.jpg) repeat fixed left top; cursor: auto;

Test your regex here: https://regex101.com/r/l2Zt7S/1

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

How to open maximized window with Javascript?

If I use Firefox then screen.width and screen.height works fine but in IE and Chrome they don't work properly instead it opens with the minimum size.

And yes I tried giving too large numbers too like 10000 for both height and width but not exactly the maximized effect.

Java FileReader encoding issue

For Java 7+ doc you can use this:

BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);

Here are all Charsets doc

For example if your file is in CP1252, use this method

Charset.forName("windows-1252");

Here is other canonical names for Java encodings both for IO and NIO doc

If you do not know with exactly encoding you have got in a file, you may use some third-party libs like this tool from Google this which works fairly neat.

How to update std::map after using the find method?

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

What can cause a “Resource temporarily unavailable” on sock send() command

Let'e me give an example:

  1. client connect to server, and send 1MB data to server every 1 second.

  2. server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer in the client side will be full.

Code in client side:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...)                                                                          \
    if (r) {                                                                                     \
        printf(__VA_ARGS__);                                                                     \
        printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
        exit(1);                                                                                 \
    }

void setNonBlock(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    exit_if(flags < 0, "fcntl failed");
    int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    exit_if(r < 0, "fcntl failed");
}

void test_full_sock_buf_1(){
    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;


    int fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd<0, "create socket error");

    int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(ret<0, "connect to server error");
    setNonBlock(fd);

    printf("connect to server success");

    const int LEN = 1024 * 1000;
    char msg[LEN];  // 1MB data
    memset(msg, 'a', LEN);

    for (int i = 0; i < 1000; ++i) {
        int len = send(fd, msg, LEN, 0);
        printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
        sleep(1);
    }

}

int main(){
    test_full_sock_buf_1();

    return 0;
}

Code in server side:

    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <string.h>
    #define exit_if(r, ...)                                                                          \
        if (r) {                                                                                     \
            printf(__VA_ARGS__);                                                                     \
            printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
            exit(1);                                                                                 \
        }
void test_full_sock_buf_1(){

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(listenfd<0, "create socket error");

    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(r<0, "bind socket error");

    r = listen(listenfd, 100);
    exit_if(r<0, "listen socket error");

    struct sockaddr_in raddr;
    socklen_t rsz = sizeof(raddr);
    int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
    exit_if(cfd<0, "accept socket error");

    sockaddr_in peer;
    socklen_t alen = sizeof(peer);
    getpeername(cfd, (sockaddr *) &peer, &alen);

    printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));

    printf("but now I will sleep 15 second, then exit");
    sleep(15);
}

Start server side, then start client side.

server side may output:

accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0

enter image description here

client side may output:

connect to server successsend: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 552190, erron: 0, Success 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 104, Connection reset by peer 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 

enter image description here

You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer get full, but you still send data, so you may get Resource temporarily unavailable error.

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

Copying sets Java

The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from). When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:

findbugs says

The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.

As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.

Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:

Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
    copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));

Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.

Register .NET Framework 4.5 in IIS 7.5

For Windows 8 and Windows Server 2012 use dism /online /enable-feature /featurename:IIS-ASPNET45 As administrative command prompt.

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

Format Date output in JSF

Use <f:convertDateTime>. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat.

<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>

Counting inversions in an array

Java implementation:

import java.lang.reflect.Array;
import java.util.Arrays;


public class main {

public static void main(String[] args) {
    int[] arr = {6, 9, 1, 14, 8, 12, 3, 2};
    System.out.println(findinversion(arr,0,arr.length-1));
}

public static int findinversion(int[] arr,int beg,int end) {
    if(beg >= end)
        return 0;

    int[] result = new int[end-beg+1];
    int index = 0;
    int mid = (beg+end)/2;
    int count = 0, leftinv,rightinv;
    //System.out.println("...."+beg+"   "+end+"  "+mid);
    leftinv = findinversion(arr, beg, mid);
    rightinv = findinversion(arr, mid+1, end);
    l1:
    for(int i = beg, j = mid+1; i<=mid || j<=end;/*index < result.length;*/ ) {
        if(i>mid) {
            for(;j<=end;j++)
                result[index++]=arr[j];
            break l1;
        }
        if(j>end) {
            for(;i<=mid;i++)
                result[index++]=arr[i];
            break l1;
        }
        if(arr[i] <= arr[j]) {
            result[index++]=arr[i];
            i++;    
        } else {
            System.out.println(arr[i]+"  "+arr[j]);
            count = count+ mid-i+1;
            result[index++]=arr[j];
            j++;    
        }
    }

    for(int i = 0, j=beg; i< end-beg+1; i++,j++)
        arr[j]= result[i];
    return (count+leftinv+rightinv);
    //System.out.println(Arrays.toString(arr));
}

}

How to output git log with the first line only?

if you want to always use git log in such way you could add git alias by

git config --global alias.log log --oneline

after that git log will print what normally would be printed by git log --oneline

How can I pad an int with leading zeros when using cout << operator?

cout.fill( '0' );    
cout.width( 3 );
cout << value;

How can I install a .ipa file to my iPhone simulator

First of all, IPAs usually only have ARM slices because the App Store does not currently accept Simulator slices in uploads.

Secondly, as of Xcode 8.3 you can drag & drop a .app bundle into the Simulator window and it will be installed. You can find the app in your build products directory ~/Library/Developer/Xcode/DerivedData/projectname-xyzzyabcdefg/Build/Products/Debug-iphonesimulator if you want to save it or distribute it to other people.

To install from the command line use xcrun simctl install <device> <path>.

device can be the device UUID, its name, or booted which means the currently booted device.

How to Git stash pop specific stash in 1.8.3?

First check the list:-

git stash list

copy the index you wanted to pop from the stash list

git stash pop stash@{index_number}

eg.:

git stash pop stash@{1}

How do I add a submodule to a sub-directory?

one-liner bash script to help facility Chris's answer above, as I had painted myself in a corner as well using Vundle updates to my .vim scripts. DEST is the path to the directory containing your submodules. Do this after doing git rm -r $DEST

DEST='path'; for file in `ls ${DEST}`; do git submodule add `grep url ${DEST}/${file}/.git/config|awk -F= '{print $2}'` ${DEST}/${file}; done

cheers

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

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

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

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

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

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

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

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

(Of course there are more packages available).

How should I multiple insert multiple records?

If I were you I would not use either of them.

The disadvantage of the first one is that the parameter names might collide if there are same values in the list.

The disadvantage of the second one is that you are creating command and parameters for each entity.

The best way is to have the command text and parameters constructed once (use Parameters.Add to add the parameters) change their values in the loop and execute the command. That way the statement will be prepared only once. You should also open the connection before you start the loop and close it after it.

How do I parse a URL into hostname and path in javascript?

a simple hack with the first answer

var getLocation = function(href=window.location.href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};

this can used even without argument to figure out the current hostname getLocation().hostname will give current hostname

How to make JQuery-AJAX request synchronous

Instead of adding onSubmit event, you can prevent the default action for submit button.

So, in the following html:

<form name="form" action="insert.php" method="post">
    <input type='submit' />
</form>?

first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.

$('input[type=submit]').click(function(e) {
    e.preventDefault(); //prevent form submit when button is clicked

    var password = $.trim($('#employee_password').val());

     $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            var $form = $('form');
            if(arr == "Successful")
            {    
                $form.submit(); //submit the form if the password is correct
            }
        }
    });
});????????????????????????????????

Looking to understand the iOS UIViewController lifecycle

This is for latest iOS Versions(Modified with Xcode 9.3, Swift 4.1). Below are all the stages which makes the lifecycle of a UIViewController complete.

  • loadView()

  • loadViewIfNeeded()

  • viewDidLoad()

  • viewWillAppear(_ animated: Bool)

  • viewWillLayoutSubviews()

  • viewDidLayoutSubviews()

  • viewDidAppear(_ animated: Bool)

  • viewWillDisappear(_ animated: Bool)

  • viewDidDisappear(_ animated: Bool)

Let me explain all those stages.

1. loadView

This event creates/loads the view that the controller manages. It can load from an associated nib file or an empty UIView if null was found. This makes it a good place to create your views in code programmatically.

This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly. Only override this method when you programmatically create views and assign the root view to the view property Don't call super method when you override loadView

2. loadViewIfNeeded

If incase the view of current viewController has not been set yet then this method will load the view but remember, this is only available in iOS >=9.0. So if you are supporting iOS <9.0 then don't expect it to come into the picture.

Loads the view controller's view if it has not already been set.

3. viewDidLoad

The viewDidLoad event is only called when the view is created and loaded into memory but the bounds for the view are not defined yet. This is a good place to initialise the objects that the view controller is going to use.

Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.

4. viewWillAppear

This event notifies the viewController whenever the view appears on the screen. In this step the view has bounds that are defined but the orientation is not set.

Called when the view is about to made visible. Default does nothing.

5. viewWillLayoutSubviews

This is the first step in the lifecycle where the bounds are finalised. If you are not using constraints or Auto Layout you probably want to update the subviews here. This is only available in iOS >=5.0. So if you are supporting iOS <5.0 then don't expect it to come into the picture.

Called just before the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. The default is a nop.

6. viewDidLayoutSubviews

This event notifies the view controller that the subviews have been setup. It is a good place to make any changes to the subviews after they have been set. This is only available in iOS >=5.0. So if you are supporting iOS <5.0 then don't expect it to come into the picture.

Called just after the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. The default is a nop.

7. viewDidAppear

The viewDidAppear event fires after the view is presented on the screen. Which makes it a good place to get data from a backend service or database.

Called when the view has been fully transitioned onto the screen. Default does nothing

8. viewWillDisappear

The viewWillDisappear event fires when the view of presented viewController is about to disappear, dismiss, cover or hide behind other viewController. This is a good place where you can restrict your network calls, invalidate timer or release objects which is bound to that viewController.

Called when the view is dismissed, covered or otherwise hidden.

9. viewDidDisappear

This is the last step of the lifecycle that anyone can address as this event fires just after the view of presented viewController has been disappeared, dismissed, covered or hidden.

Called after the view was dismissed, covered or otherwise hidden. Default does nothing

Now as per Apple when you are implementing this methods you should remember to call super implementation of that specific method.

If you subclass UIViewController, you must call the super implementation of this method, even if you aren't using a NIB. (As a convenience, the default init method will do this for you, and specify nil for both of this methods arguments.) In the specified NIB, the File's Owner proxy should have its class set to your view controller subclass, with the view outlet connected to the main view. If you invoke this method with a nil nib name, then this class' -loadView method will attempt to load a NIB whose name is the same as your view controller's class. If no such NIB in fact exists then you must either call -setView: before -view is invoked, or override the -loadView method to set up your views programatically.

Hope this helped. Thanks.

UPDATE - As @ThomasW pointed inside comment viewWillLayoutSubviews and viewDidLayoutSubviews will also be called at other times when subviews of the main view are loaded, for example when cells of a table view or collection view are loaded.

UPDATE - As @Maria pointed inside comment, description of loadView was updated

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

I had the same issue, due to the fact that I had all the configuration that describe in this post, but in my case was because I had two jquery imports (one of them was primefaces's query) which caused conflicts to upload files.

See Primefaces Jquery conflict

Extract column values of Dataframe as List in Apache Spark

Below is for Python-

df.select("col_name").rdd.flatMap(lambda x: x).collect()

Setting CSS pseudo-class rules from JavaScript

There is another alternative. Instead of manipulating the pseudo-classes directly, create real classes that model the same things, like a "hover" class or a "visited" class. Style the classes with the usual "." syntax and then you can use JavaScript to add or remove classes from an element when the appropriate event fires.

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Adding backslashes without escaping [Python]

The result '\\&' is only displayed - actually the string is \&:

>>> str = '&'
>>> new_str = str.replace('&', '\&')
>>> new_str
'\\&'
>>> print new_str
\&

Try it in a shell.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

The system cannot find the file specified. in Visual Studio

The system cannot find the file specified usually means the build failed (which it will for your code as you're missing a # infront of include, you have a stray >> at the end of your cout line and you need std:: infront of cout) but you have the 'run anyway' option checked which means it runs an executable that doesn't exist. Hit F7 to just do a build and make sure it says '0 errors' before you try running it.

Code which builds and runs:

#include <iostream>

int main()
{
   std::cout << "Hello World";
   system("pause");
   return 0;
}

Why is JsonRequestBehavior needed?

You do not need it.

If your action has the HttpPost attribute, then you do not need to bother with setting the JsonRequestBehavior and use the overload without it. There is an overload for each method without the JsonRequestBehavior enum. Here they are:

Without JsonRequestBehavior

protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);

With JsonRequestBehavior

protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType, 
                                   JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, 
    Encoding contentEncoding, JsonRequestBehavior behavior);

Converting from IEnumerable to List

You can do this very simply using LINQ.

Make sure this using is at the top of your C# file:

using System.Linq;

Then use the ToList extension method.

Example:

IEnumerable<int> enumerable = Enumerable.Range(1, 300);
List<int> asList = enumerable.ToList();

Typescript: Type 'string | undefined' is not assignable to type 'string'

You can use the NonNullable Utility Type:

Example

type T0 = NonNullable<string | number | undefined>;  // string | number
type T1 = NonNullable<string[] | null | undefined>;  // string[]

Docs.

How to set "value" to input web element using selenium?

Use findElement instead of findElements

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");

OR

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");

OR using JavascriptExecutor

WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);

OR

(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);

OR (in javascript)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")

Hope it will help you :)

How to loop through all the properties of a class?

Reflection is pretty "heavy"

Perhaps try this solution:

C#

if (item is IEnumerable) {
    foreach (object o in item as IEnumerable) {
            //do function
    }
} else {
    foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())      {
        if (p.CanRead) {
            Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj,  null)); //possible function
        }
    }
}

VB.Net

  If TypeOf item Is IEnumerable Then

    For Each o As Object In TryCast(item, IEnumerable)
               'Do Function
     Next
  Else
    For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
         If p.CanRead Then
               Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing))  'possible function
          End If
      Next
  End If

Reflection slows down +/- 1000 x the speed of a method call, shown in The Performance of Everyday Things

gradlew: Permission Denied

Try to set the execution flag on your gradlew file:

chmod +x gradlew

When to use @QueryParam vs @PathParam

REST may not be a standard as such, but reading up on general REST documentation and blog posts should give you some guidelines for a good way to structure API URLs. Most rest APIs tend to only have resource names and resource IDs in the path. Such as:

/departments/{dept}/employees/{id}

Some REST APIs use query strings for filtering, pagination and sorting, but Since REST isn't a strict standard I'd recommend checking some REST APIs out there such as github and stackoverflow and see what could work well for your use case.

I'd recommend putting any required parameters in the path, and any optional parameters should certainly be query string parameters. Putting optional parameters in the path will end up getting really messy when trying to write URL handlers that match different combinations.

recursion versus iteration

Recursion is usually much slower because all function calls must be stored in a stack to allow the return back to the caller functions. In many cases, memory has to be allocated and copied to implement scope isolation.

Some optimizations, like tail call optimization, make recursions faster but aren't always possible, and aren't implemented in all languages.

The main reasons to use recursion are

  • that it's more intuitive in many cases when it mimics our approach of the problem
  • that some data structures like trees are easier to explore using recursion (or would need stacks in any case)

Of course every recursion can be modeled as a kind of loop : that's what the CPU will ultimately do. And the recursion itself, more directly, means putting the function calls and scopes in a stack. But changing your recursive algorithm to a looping one might need a lot of work and make your code less maintainable : as for every optimization, it should only be attempted when some profiling or evidence showed it to be necessary.

getting error while updating Composer

The good solution for this error please run this command

composer install --ignore-platform-reqs

List(of String) or Array or ArrayList

look to the List AddRange method here

Unable to create migrations after upgrading to ASP.NET Core 2.0

I had same problem. Just changed the ap.jason to application.jason and it fixed the issue

Jquery insert new row into table at a certain index

$('#my_table tbody tr:nth-child(' + i + ')').after(html);

How to set default value for HTML select?

Note: this is JQuery. See Sébastien answer for Javascript

$(function() {
    var temp="a"; 
    $("#MySelect").val(temp);
});

<select name="MySelect" id="MySelect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

'\r': command not found - .bashrc / .bash_profile

I had the same problem. Solution: I edit the file with pspad editor, and give it a unix format (Menu - Format -> UNIX)

I believe you can set this format to your file with many other editors

typedef struct vs struct definitions

The common idiom is using both:

typedef struct S { 
    int x; 
} S;

They are different definitions. To make the discussion clearer I will split the sentence:

struct S { 
    int x; 
};

typedef struct S S;

In the first line you are defining the identifier S within the struct name space (not in the C++ sense). You can use it and define variables or function arguments of the newly defined type by defining the type of the argument as struct S:

void f( struct S argument ); // struct is required here

The second line adds a type alias S in the global name space and thus allows you to just write:

void f( S argument ); // struct keyword no longer needed

Note that since both identifier name spaces are different, defining S both in the structs and global spaces is not an error, as it is not redefining the same identifier, but rather creating a different identifier in a different place.

To make the difference clearer:

typedef struct S { 
    int x; 
} T;

void S() { } // correct

//void T() {} // error: symbol T already defined as an alias to 'struct S'

You can define a function with the same name of the struct as the identifiers are kept in different spaces, but you cannot define a function with the same name as a typedef as those identifiers collide.

In C++, it is slightly different as the rules to locate a symbol have changed subtly. C++ still keeps the two different identifier spaces, but unlike in C, when you only define the symbol within the class identifier space, you are not required to provide the struct/class keyword:

 // C++
struct S { 
    int x; 
}; // S defined as a class

void f( S a ); // correct: struct is optional

What changes are the search rules, not where the identifiers are defined. The compiler will search the global identifier table and after S has not been found it will search for S within the class identifiers.

The code presented before behaves in the same way:

typedef struct S { 
    int x; 
} T;

void S() {} // correct [*]

//void T() {} // error: symbol T already defined as an alias to 'struct S'

After the definition of the S function in the second line, the struct S cannot be resolved automatically by the compiler, and to create an object or define an argument of that type you must fall back to including the struct keyword:

// previous code here...
int main() {
    S(); 
    struct S s;
}

What exactly is a Context in Java?

since you capitalized the word, I assume you are referring to the interface javax.naming.Context. A few classes implement this interface, and at its simplest description, it (generically) is a set of name/object pairs.

How can I stop Chrome from going into debug mode?

For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.

For me it was the "breakOnLoad": true line in VS Code launch.json config.

How can I reference a dll in the GAC from Visual Studio?

The only way that worked for me, is by copying the dll into your desktop or something, add reference to it, then delete the dll from your desktop. Visual Studio will refresh itself, and will finally reference the dll from the GAC on itself.

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Changing the selected option of an HTML Select element

Markup

<select id="my_select">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
</select>

jQuery

var my_value = 2;
$('#my_select option').each(function(){
    var $this = $(this); // cache this jQuery object to avoid overhead

    if ($this.val() == my_value) { // if this option's value is equal to our value
        $this.prop('selected', true); // select this option
        return false; // break the loop, no need to look further
    }
});

Demo

How to hide "Showing 1 of N Entries" with the dataTables.js library

It is Work for me:

language:{"infoEmpty": "No records available",}

Getting text from td cells with jQuery

$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});

How to filter an array of objects based on values in an inner array with jq?

Very close! In your select expression, you have to use a pipe (|) before contains.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key

E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].

What exactly should be set in PYTHONPATH?

You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.

How to update UI from another thread running in another class

You are going to have to come back to your main thread (also called UI thread) in order to update the UI. Any other thread trying to update your UI will just cause exceptions to be thrown all over the place.

So because you are in WPF, you can use the Dispatcher and more specifically a beginInvoke on this dispatcher. This will allow you to execute what needs done (typically Update the UI) in the UI thread.

You migh also want to "register" the UI in your business, by maintaining a reference to a control/form, so you can use its dispatcher.

How to use JavaScript to change div backgroundColor

This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.

Example:

div.classname:hover
{
    background-color: black;
}

This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox

Happy programming!

Convert date to another timezone in JavaScript

Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.

_x000D_
_x000D_
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
_x000D_
_x000D_
_x000D_

How can a LEFT OUTER JOIN return more records than exist in the left table?

It seems as though there are multiple rows in the DATA.Dim_Member table per SUSP.Susp_Visits row.

javascript scroll event for iPhone/iPad?

Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.

So, if you register the scroll event handler and check window.pageYOffset inside that event handler, everything works just fine.

What is the difference between a URI, a URL and a URN?

URI and URL

URI, URL, URN

As the image above indicates, there are three distinct components at play here. It’s usually best to go to the source when discussing matters like these, so here’s an exerpt from Tim Berners-Lee, et. al. in RFC 3986: Uniform Resource Identifier (URI): Generic Syntax:

A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource.

A URI can be further classified as a locator, a name, or both. The term “Uniform Resource Locator” (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network “location”).

make a phone call click on a button

I was having a hell of a time with this as well. I didn't realize that beyond the extra permission you need to append "tel:" onto the string that has the number in it. This is what mine looks like after getting it functional. Hope this helps.

_x000D_
_x000D_
@Override_x000D_
public void onClick(View v) {_x000D_
  Intent intent = new Intent(Intent.ACTION_DIAL);_x000D_
  String temp = "tel:" + phone;_x000D_
  intent.setData(Uri.parse(temp));_x000D_
_x000D_
  startActivity(intent);_x000D_
}
_x000D_
_x000D_
_x000D_

Read entire file in Scala?

Java 8+

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

val path = Paths.get("file.txt")
new String(Files.readAllBytes(path), StandardCharsets.UTF_8)

Java 11+

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path}

val path = Path.of("file.txt")
Files.readString(path, StandardCharsets.UTF_8)

These offer control over character encoding, and no resources to clean up. It's also faster than other patterns (e.g. getLines().mkString("\n")) due to more efficient allocation patterns.

Return Bit Value as 1/0 and NOT True/False in SQL Server

Modify your query to generate the output that you want.

Try casting them to int:

select cast(bitFlag as int)

Or, if you like, use case:

select (case when bitFlag = 0 then 0 else 1 end)

Getting an Embedded YouTube Video to Auto Play and Loop

All of the answers didn't work for me, I checked the playlist URL and seen that playlist parameter changed to list! So it should be:

&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs

So here is the full code I use make a clean, looping, autoplay video:

<iframe width="100%" height="425" src="https://www.youtube.com/embed/MavEpJETfgI?autoplay=1&showinfo=0&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs&rel=0" frameborder="0" allowfullscreen></iframe>

Can I animate absolute positioned element with CSS transition?

Please Try this code margin-left:60px instead of left:60px

please take a look: http://jsfiddle.net/hbirjand/2LtBh/2/

as @Shomz said,transition must be changed to transition:margin 1s linear; instead of transition:all 1s linear;

What is an index in SQL?

INDEX is a performance optimization technique that speeds up the data retrieval process. It is a persistent data structure that associated with a Table (or View) in order to increase performance during retrieving the data from that table (or View).

Index based search is applied more particularly when your queries include WHERE filter. Otherwise, i.e, a query without WHERE-filter selects whole data and process. Searching whole table without INDEX is called Table-scan.

You will find exact information for Sql-Indexes in clear and reliable way: follow these links:

  1. For cocnept-wise understanding: http://dotnetauthorities.blogspot.in/2013/12/Microsoft-SQL-Server-Training-Online-Learning-Classes-INDEX-Overview-and-Optimizations.html
  2. For implementation-wise understanding: http://dotnetauthorities.blogspot.in/2013/12/Microsoft-SQL-Server-Training-Online-Learning-Classes-INDEX-Creation-Deletetion-Optimizations.html

How to change the color of progressbar in C# .NET 3.5?

The VB.Net colored progressbar which respects WXP Visual Styles answer is ...

I started with the answer from 'user1032613' on 3/17/12. Note that this is now a Module, not a class. From there I converted the code but more was needed. In particular the converted code showed a DirectCast function to convert the 'state' integer to a IntPtr type which didn't work.

Imports System.Runtime.InteropServices

Public Module ModifyProgressBarColor

    Private Declare Function SendMessage Lib "User32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long

    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=False)> _
    Private Function SendMessage(hWnd As IntPtr, Msg As UInteger, w As IntPtr, l As IntPtr) As IntPtr
    End Function

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub SetState(pBar As ProgressBar, state As Integer)

        '-- Convert state as integer to type IntPtr
        Dim s As IntPtr
        Dim y As Integer = state
        s = IntPtr.op_Explicit(y)

        '-- Modify bar color
        SendMessage(pBar.Handle, 1040, s, IntPtr.Zero)

    End Sub

End Module

And again just call this in the using code with this line:

Call ModifyProgressBarColor.SetState(prb, 2)

BTW - I tried other colors - 0, 4, 5 - they all just displayed green.

Does it make sense to use Require.js with Angular.js?

It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

MySQL Query to select data from last week?

i Use this for the week start from SUNDAY:

SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY  
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

Python Create unix timestamp five minutes in the future

The following is based on the answers above (plus a correction for the milliseconds) and emulates datetime.timestamp() for Python 3 before 3.3 when timezones are used.

def datetime_timestamp(datetime):
    '''
    Equivalent to datetime.timestamp() for pre-3.3
    '''
    try:
        return datetime.timestamp()
    except AttributeError:
        utc_datetime = datetime.astimezone(utc)
        return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6

To strictly answer the question as asked, you'd want:

datetime_timestamp(my_datetime) + 5 * 60

datetime_timestamp is part of simple-date. But if you were using that package you'd probably type:

SimpleDate(my_datetime).timestamp + 5 * 60

which handles many more formats / types for my_datetime.

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

How about using a simple loop to count the occurrences of number of spaces!?

_x000D_
_x000D_
txt = "Just an example here move along" _x000D_
count = 1_x000D_
for i in txt:_x000D_
if i == " ":_x000D_
   count += 1_x000D_
print(count)
_x000D_
_x000D_
_x000D_

What are the file limits in Git (number and size)?

This message from Linus himself can help you with some other limits

[...] CVS, ie it really ends up being pretty much oriented to a "one file at a time" model.

Which is nice in that you can have a million files, and then only check out a few of them - you'll never even see the impact of the other 999,995 files.

Git fundamentally never really looks at less than the whole repo. Even if you limit things a bit (ie check out just a portion, or have the history go back just a bit), git ends up still always caring about the whole thing, and carrying the knowledge around.

So git scales really badly if you force it to look at everything as one huge repository. I don't think that part is really fixable, although we can probably improve on it.

And yes, then there's the "big file" issues. I really don't know what to do about huge files. We suck at them, I know.

See more in my other answer: the limit with Git is that each repository must represent a "coherent set of files", the "all system" in itself (you can not tag "part of a repository").
If your system is made of autonomous (but inter-dependent) parts, you must use submodules.

As illustrated by Talljoe's answer, the limit can be a system one (large number of files), but if you do understand the nature of Git (about data coherency represented by its SHA-1 keys), you will realize the true "limit" is a usage one: i.e, you should not try to store everything in a Git repository, unless you are prepared to always get or tag everything back. For some large projects, it would make no sense.


For a more in-depth look at git limits, see "git with large files"
(which mentions git-lfs: a solution to store large files outside the git repo. GitHub, April 2015)

The three issues that limits a git repo:

  • huge files (the xdelta for packfile is in memory only, which isn't good with large files)
  • huge number of files, which means, one file per blob, and slow git gc to generate one packfile at a time.
  • huge packfiles, with a packfile index inefficient to retrieve data from the (huge) packfile.

A more recent thread (Feb. 2015) illustrates the limiting factors for a Git repo:

Will a few simultaneous clones from the central server also slow down other concurrent operations for other users?

There are no locks in server when cloning, so in theory cloning does not affect other operations. Cloning can use lots of memory though (and a lot of cpu unless you turn on reachability bitmap feature, which you should).

Will 'git pull' be slow?

If we exclude the server side, the size of your tree is the main factor, but your 25k files should be fine (linux has 48k files).

'git push'?

This one is not affected by how deep your repo's history is, or how wide your tree is, so should be quick..

Ah the number of refs may affect both git-push and git-pull.
I think Stefan knows better than I in this area.

'git commit'? (It is listed as slow in reference 3.) 'git status'? (Slow again in reference 3 though I don't see it.)
(also git-add)

Again, the size of your tree. At your repo's size, I don't think you need to worry about it.

Some operations might not seem to be day-to-day but if they are called frequently by the web front-end to GitLab/Stash/GitHub etc then they can become bottlenecks. (e.g. 'git branch --contains' seems terribly adversely affected by large numbers of branches.)

git-blame could be slow when a file is modified a lot.

How can I use optional parameters in a T-SQL stored procedure?

Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).

Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:

Dynamic Search Conditions in T-SQL by by Erland Sommarskog

The Curse and Blessings of Dynamic SQL by Erland Sommarskog

If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:

Add OPTION (RECOMPILE) onto your query, see Erland's article, and SQL Server will resolve the OR from within (@LastName IS NULL OR LastName= @LastName) before the query plan is created based on the runtime values of the local variables, and an index can be used.

This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.

CREATE PROCEDURE spDoSearch
    @FirstName varchar(25) = null,
    @LastName varchar(25) = null,
    @Title varchar(25) = null
AS
    BEGIN
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
                (@FirstName IS NULL OR (FirstName = @FirstName))
            AND (@LastName  IS NULL OR (LastName  = @LastName ))
            AND (@Title     IS NULL OR (Title     = @Title    ))
        OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
    END

What is the most efficient way to loop through dataframes with pandas?

Pandas is based on NumPy arrays. The key to speed with NumPy arrays is to perform your operations on the whole array at once, never row-by-row or item-by-item.

For example, if close is a 1-d array, and you want the day-over-day percent change,

pct_change = close[1:]/close[:-1]

This computes the entire array of percent changes as one statement, instead of

pct_change = []
for row in close:
    pct_change.append(...)

So try to avoid the Python loop for i, row in enumerate(...) entirely, and think about how to perform your calculations with operations on the entire array (or dataframe) as a whole, rather than row-by-row.

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

Converting Hexadecimal String to Decimal Integer

You could take advantage of ASCII value for each letter and take off 55, easy and fast:

int asciiOffset = 55;
char hex = Character.toUpperCase('A');  // Only A-F uppercase
int val = hex - asciiOffset;
System.out.println("hexadecimal:" + hex);
System.out.println("decimal:" + val);

Output:
hexadecimal:A
decimal:10

Difference between size and length methods?

I bet (no language specified) size() method returns length property.

However valid for loop should looks like:

for (int i = 0; i < values.length; i++) {}

Get a timestamp in C in microseconds?

But this returns some nonsense value that if I get two timestamps, the second one can be smaller or bigger than the first (second one should always be bigger).

What makes you think that? The value is probably OK. It’s the same situation as with seconds and minutes – when you measure time in minutes and seconds, the number of seconds rolls over to zero when it gets to sixty.

To convert the returned value into a “linear” number you could multiply the number of seconds and add the microseconds. But if I count correctly, one year is about 1e6*60*60*24*360 µsec and that means you’ll need more than 32 bits to store the result:

$ perl -E '$_=1e6*60*60*24*360; say int log($_)/log(2)'
44

That’s probably one of the reasons to split the original returned value into two pieces.

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

Draw on HTML5 Canvas using a mouse

I had to provide a simple example for this subject so I'll share here:

http://jsfiddle.net/Haelle/v6tfp2e1

_x000D_
_x000D_
class SignTool {_x000D_
  constructor() {_x000D_
    this.initVars()_x000D_
    this.initEvents()_x000D_
  }_x000D_
_x000D_
  initVars() {_x000D_
    this.canvas = $('#canvas')[0]_x000D_
    this.ctx = this.canvas.getContext("2d")_x000D_
    this.isMouseClicked = false_x000D_
    this.isMouseInCanvas = false_x000D_
    this.prevX = 0_x000D_
    this.currX = 0_x000D_
    this.prevY = 0_x000D_
    this.currY = 0_x000D_
  }_x000D_
_x000D_
  initEvents() {_x000D_
    $('#canvas').on("mousemove", (e) => this.onMouseMove(e))_x000D_
    $('#canvas').on("mousedown", (e) => this.onMouseDown(e))_x000D_
    $('#canvas').on("mouseup", () => this.onMouseUp())_x000D_
    $('#canvas').on("mouseout", () => this.onMouseOut())_x000D_
    $('#canvas').on("mouseenter", (e) => this.onMouseEnter(e))_x000D_
  }_x000D_
  _x000D_
  onMouseDown(e) {_x000D_
   this.isMouseClicked = true_x000D_
    this.updateCurrentPosition(e)_x000D_
  }_x000D_
  _x000D_
  onMouseUp() {_x000D_
   this.isMouseClicked = false_x000D_
  }_x000D_
  _x000D_
  onMouseEnter(e) {_x000D_
   this.isMouseInCanvas = true_x000D_
    this.updateCurrentPosition(e)_x000D_
  }_x000D_
  _x000D_
  onMouseOut() {_x000D_
   this.isMouseInCanvas = false_x000D_
  }_x000D_
_x000D_
  onMouseMove(e) {_x000D_
    if (this.isMouseClicked && this.isMouseInCanvas) {_x000D_
     this.updateCurrentPosition(e)_x000D_
      this.draw()_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  updateCurrentPosition(e) {_x000D_
      this.prevX = this.currX_x000D_
      this.prevY = this.currY_x000D_
      this.currX = e.clientX - this.canvas.offsetLeft_x000D_
      this.currY = e.clientY - this.canvas.offsetTop_x000D_
  }_x000D_
  _x000D_
  draw() {_x000D_
    this.ctx.beginPath()_x000D_
    this.ctx.moveTo(this.prevX, this.prevY)_x000D_
    this.ctx.lineTo(this.currX, this.currY)_x000D_
    this.ctx.strokeStyle = "black"_x000D_
    this.ctx.lineWidth = 2_x000D_
    this.ctx.stroke()_x000D_
    this.ctx.closePath()_x000D_
  }_x000D_
}_x000D_
_x000D_
var canvas = new SignTool()
_x000D_
canvas {_x000D_
  position: absolute;_x000D_
  border: 2px solid;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<canvas id="canvas" width="500" height="300"></canvas>
_x000D_
_x000D_
_x000D_

What's the best strategy for unit-testing database-driven applications?

I've actually used your first approach with quite some success, but in a slightly different ways that I think would solve some of your problems:

  1. Keep the entire schema and scripts for creating it in source control so that anyone can create the current database schema after a check out. In addition, keep sample data in data files that get loaded by part of the build process. As you discover data that causes errors, add it to your sample data to check that errors don't re-emerge.

  2. Use a continuous integration server to build the database schema, load the sample data, and run tests. This is how we keep our test database in sync (rebuilding it at every test run). Though this requires that the CI server have access and ownership of its own dedicated database instance, I say that having our db schema built 3 times a day has dramatically helped find errors that probably would not have been found till just before delivery (if not later). I can't say that I rebuild the schema before every commit. Does anybody? With this approach you won't have to (well maybe we should, but its not a big deal if someone forgets).

  3. For my group, user input is done at the application level (not db) so this is tested via standard unit tests.

Loading Production Database Copy:
This was the approach that was used at my last job. It was a huge pain cause of a couple of issues:

  1. The copy would get out of date from the production version
  2. Changes would be made to the copy's schema and wouldn't get propagated to the production systems. At this point we'd have diverging schemas. Not fun.

Mocking Database Server:
We also do this at my current job. After every commit we execute unit tests against the application code that have mock db accessors injected. Then three times a day we execute the full db build described above. I definitely recommend both approaches.

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

What's the fastest way to loop through an array in JavaScript?

I'm always write in the first style.

Even if a compiler is smart enough to optimize it for arrays, but still it smart if we are using DOMNodeList here or some complicated object with calculated length?

I know what the question is about arrays, but i think it is a good practice to write all your loops in one style.

Calling Scalar-valued Functions in SQL

That syntax works fine for me:

CREATE FUNCTION dbo.test_func
(@in varchar(20))
RETURNS INT
AS
BEGIN
    RETURN 1
END
GO

SELECT dbo.test_func('blah')

Are you sure that the function exists as a function and under the dbo schema?

Android Studio 3.0 Flavor Dimension Issue

Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
    production {
        dimension 'yourAppName' //you just need to add this line
        //here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.

    }

    staging {
        dimension 'yourAppName' //added here also
        applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
        //or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
        //versionNameSuffix "-staging"

    }

    develop {
        dimension 'yourAppName' //add here too
        applicationIdSuffix ".develop"
        //versionNameSuffix "-develop"

    }

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

The range of floating point numbers usually exceeds the range of integers. By returning a floating point value, the functions can return a sensible value for input values that lie outside the representable range of integers.

Consider: If floor() returned an integer, what should floor(1.0e30) return?

Now, while Python's integers are now arbitrary precision, it wasn't always this way. The standard library functions are thin wrappers around the equivalent C library functions.

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

Get text from pressed button

Try to use:

String buttonText = ((Button)v).getText().toString();

ng is not recognized as an internal or external command

  1. Open cmd and type npm install -g @angular/cli

  2. In environment variables, add either in the user variable or System variable "Path" value=C:\Users\your-user\.npm-packages\node_modules\.bin

  3. In cmd: c:\>cd your-new-project-path

  4. ...\project-path\> ng new my-app

    or ng all-ng-commands

Can't find System.Windows.Media namespace?

You can add PresentationCore.dll more conveniently by editing the project file. Add the following code into your csproj file:

<ItemGroup>
   <FrameworkReference Include="Microsoft.WindowsDesktop.App" />
</ItemGroup>

In your solution explorer, you now should see this framework listed, now. With that, you then can also refer to the classes provided by PresentationCore.dll.

How to print the full NumPy array, without truncation?

with np.printoptions(edgeitems=50):
    print(x)

Change 50 to how many lines you wanna see

Source: here

How do I make an input field accept only letters in javaScript?

Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.

Using cURL with a username and password?

Other answers have suggested netrc to specify username and password, based on what I've read, I agree. Here are some syntax details:

https://ec.haxx.se/usingcurl-netrc.html

Like other answers, I would like to stress the need to pay attention to security regarding this question.

Although I am not an expert, I found these links insightful:

https://ec.haxx.se/cmdline-passwords.html

To summarize:

Using the encrypted versions of the protocols (HTTPS vs HTTP) (FTPS vs FTP) can help avoid Network Leakage.

Using netrc can help avoid Command Line Leakage.

To go a step further, it seems you can also encrypt the netrc files using gpg

https://brandur.org/fragments/gpg-curl

With this your credentials are not "at rest" (stored) as plain text.

How do I delete specific characters from a particular String in Java?

Reassign the variable to a substring:

s = s.substring(0, s.length() - 1)

Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

How to compile c# in Microsoft's new Visual Studio Code?

Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B.

If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M.

(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)

How to filter files when using scp to copy dir recursively?

To exclude dotfiles in base directory:

scp -r [!.]* server:/path/to/something

[!.]* is a shell glob that expands to all files in working directory not starting with a dot.

How to handle iframe in Selenium WebDriver using java

In Webdriver, you should use driver.switchTo().defaultContent(); to get out of a frame. You need to get out of all the frames first, then switch into outer frame again.

// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click(); 

How to deny access to a file in .htaccess

Place the below line in your .htaccess file and replace the file name as you wish

RewriteRule ^(test\.php) - [F,L,NC]

how to call a variable in code behind to aspx page

The HelloFromCsharp.aspx look like this

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <p>
       <%= clients%>
    </p>
    </form>
</body>
</html>

And the HelloFromCsharp.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
{
    public partial class HelloFromCsharp : System.Web.UI.Page
    {
        public string clients;
        protected void Page_Load(object sender, EventArgs e)
        {
            clients = "Hello From C#";
        }
    }
}

How to remove selected commit log entries from a Git repository while keeping their changes?

You can use git cherry-pick for this. 'cherry-pick' will apply a commit onto the branch your on now.

then do

git rebase --hard <SHA1 of A>

then apply the D and E commits.

git cherry-pick <SHA1 of D>
git cherry-pick <SHA1 of E>

This will skip out the B and C commit. Having said that it might be impossible to apply the D commit to the branch without B, so YMMV.

Are PHP Variables passed by value or by reference?

Actually both methods are valid but it depends upon your requirement. Passing values by reference often makes your script slow. So it's better to pass variables by value considering time of execution. Also the code flow is more consistent when you pass variables by value.

Force div element to stay in same place, when page is scrolled

Use position: fixed instead of position: absolute.

See here.

Rails how to run rake task

In rails 4.2 the above methods didn't work.

  1. Go to the Terminal.
  2. Change the directory to the location where your rake file is present.
  3. run rake task_name.
  4. In the above case, run rake iqmedier - will run only iqmedir task.
  5. run rake euroads - will run only the euroads task.
  6. To Run all the tasks in that file assign the following inside the same file and run rake all

    task :all => [:iqmedier, :euroads, :mikkelsen, :orville ] do #This will print all the tasks o/p on the screen 
    end
    

Pyinstaller setting icons don't change

I had similar problem. If no errors from pyinstaller try to change name of .exe file. It works for me

CAST to DECIMAL in MySQL

If you need a lot of decimal numbers, in this example 17, I share with you MySql code:

This is the calculate:

=(9/1147)*100

SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);

What does "publicPath" in Webpack do?

output.path

Local disk directory to store all your output files (Absolute path).

Example: path.join(__dirname, "build/")

Webpack will output everything into localdisk/path-to-your-project/build/


output.publicPath

Where you uploaded your bundled files. (absolute path, or relative to main HTML file)

Example: /assets/

Assumed you deployed the app at server root http://server/.

By using /assets/, the app will find webpack assets at: http://server/assets/. Under the hood, every urls that webpack encounters will be re-written to begin with "/assets/".

src="picture.jpg" Re-writes ? src="/assets/picture.jpg"

Accessed by: (http://server/assets/picture.jpg)


src="/img/picture.jpg" Re-writes ? src="/assets/img/picture.jpg"

Accessed by: (http://server/assets/img/picture.jpg)

How to implement a Map with multiple keys?

I created this to solve a similar issue.

Datastructure

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class HashBucket {
    HashMap<Object, ArrayList<Object>> hmap;

    public HashBucket() {
        hmap = new HashMap<Object, ArrayList<Object>>();
    }

    public void add(Object key, Object value) {
        if (hmap.containsKey(key)) {
            ArrayList al = hmap.get(key);
            al.add(value);
        } else {
            ArrayList al = new ArrayList<Object>();
            al.add(value);
            hmap.put(key, al);
        }
    }

    public Iterator getIterator(Object key) {
        ArrayList al = hmap.get(key);
        return hmap.get(key).iterator();

    }

}

Retrieve a value:

(Note* Cast the Object back to the inserted type. In my case it was my Event Object)

    public Iterator getIterator(Object key) {
        ArrayList al = hmap.get(key);
        if (al != null) {
            return hmap.get(key).iterator();
        } else {
            List<Object> empty = Collections.emptyList();
            return empty.iterator();
        }

    }

Inserting

Event e1 = new Event();
e1.setName("Bob");
e1.setTitle("Test");
map.add("key",e1);

Are multi-line strings allowed in JSON?

JSON does not allow real line-breaks. You need to replace all the line breaks with \n.

eg:

"first line second line"

can saved with:

"first line\nsecond line"

Note:

for Python, this should be written as:

"first line\\nsecond line"

where \\ is for escaping the backslash, otherwise python will treat \n as the control character "new line"

Zip lists in Python

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: "pip install ipython"

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

Binding an enum to a WinForms combo box, and then setting it

A little late to this party ,

The SelectedValue.ToString() method should pull in the DisplayedName . However this article DataBinding Enum and also With Descriptions shows a handy way to not only have that but instead you can add a custom description attribute to the enum and use it for your displayed value if you preferred. Very simple and easy and about 15 lines or so of code (unless you count the curly braces) for everything.

It is pretty nifty code and you can make it an extension method to boot ...

Best way to remove items from a collection

For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation.

Eg.

 workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);

The reasons are:

  1. The Predicate/Linq RemoveAll method is implemented in List and has access to the internal array storing the actual data. It will shift the data and resize the internal array.
  2. The RemoveAt method implementation is quite slow, and will copy the entire underlying array of data into a new array. This means reverse iteration is useless for List

If you are stuck implementing this in a the pre c# 3.0 era. You have 2 options.

  • The easily maintainable option. Copy all the matching items into a new list and and swap the underlying list.

Eg.

List<int> list2 = new List<int>() ; 
foreach (int i in GetList())
{
    if (!(i % 2 == 0))
    {
        list2.Add(i);
    }
}
list2 = list2;

Or

  • The tricky slightly faster option, which involves shifting all the data in the list down when it does not match and then resizing the array.

If you are removing stuff really frequently from a list, perhaps another structure like a HashTable (.net 1.1) or a Dictionary (.net 2.0) or a HashSet (.net 3.5) are better suited for this purpose.

char initial value in Java

Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.

If you want the char equivalent of 0, it's just Unicode 0, which can be written as

char c = '\0';

That's also the default value for an instance (or static) variable of type char.