Programs & Examples On #Hardware

Programming questions related to the physical components of a computer. Please specify the model of your hardware in your question.

Can I write or modify data on an RFID tag?

I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number. Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).

I'd recomment that you look at the OpenPCD platform if you are into development.

This is also of interest regarding the cryptographic functions in some RFID cards.

What's the difference between a word and byte?

Why not say 8 bits?

Because not all machines have 8-bit bytes. Since you tagged this C, look up CHAR_BIT in limits.h.

How to fast get Hardware-ID in C#?

For more details refer to this link

The following code will give you CPU ID:

namespace required System.Management

var mbs = new ManagementObjectSearcher("Select ProcessorId From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
    id = mo["ProcessorId"].ToString();
    break;
}

For Hard disk ID and motherboard id details refer this-link

To speed up this procedure, make sure you don't use SELECT *, but only select what you really need. Use SELECT * only during development when you try to find out what you need to use, because then the query will take much longer to complete.

Difference between nVidia Quadro and Geforce cards?

I have read that while the underlying chips are essentially the same, the design of the board is different.

Gamers want performance, and tend to favor overclocking and other things to get high frame rates but which maybe burn out the hardware occasionally.

Businesses want reliability, and tend to favor underclocking so they can be sure that their people can keep working.

Also, I have read that the quadro boards use ECC memory.

If you don't know what ECC memory is about: it's a [relatively] well known fact that sometimes memory "flips bits (experiences errors)". This does not happen too often, but is an unavoidable consequence of the underlying physics of the memory cards and the world we live in. ECC memory adds a small percentage to the cost and a small penalty to the performance and has enough redundancy to correct occasional errors and to detect (but not correct) somewhat rarer errors. Gamers don't care about that kind of accuracy because for gamers those are just very rare visual glitches. Companies do care about that kind of accuracy because those glitches would wind up as glitches in their products or else would require more double or triple checking (which winds up being a 2x or 3x performance penalty for some part of their business).

Another issue I have read about has to do with hooking up the graphics card to third party hardware. In other words: sending the images to another card or to another machine instead of to the screen. Most gamers are just using canned software that doesn't have any use for such capabilities. Companies that use that kind of thing get orders of magnitude performance gains from the more direct connections.

What are the ascii values of up down left right?

Gaa! Go to asciitable.com. The arrow keys are the control equivalent of the HJKL keys. I.e., in vi create a big block of text. Note you can move around in that text using the HJKL keys. The arrow keys are going to be ^H, ^J, ^K, ^L.

At asciitable.com find, "K" in the third column. Now, look at the same row in the first column to find the matching control-code ("VT" in this case).

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

Python functions call by reference

class demoClass:
    x = 4
    y = 3
foo1 = demoClass()
foo1.x = 2
foo2 = demoClass()
foo2.y = 5
def mySquare(myObj):
    myObj.x = myObj.x**2
    myObj.y = myObj.y**2
print('foo1.x =', foo1.x)
print('foo1.y =', foo1.y)
print('foo2.x =', foo2.x)
print('foo2.y =', foo2.y)
mySquare(foo1)
mySquare(foo2)
print('After square:')
print('foo1.x =', foo1.x)
print('foo1.y =', foo1.y)
print('foo2.x =', foo2.x)
print('foo2.y =', foo2.y)

Get the previous month's first and last day dates in c#

If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons... This will prevent you from missing any requests created during the date of Jan 31.

DateTime now = DateTime.Now;
DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastMonth = thisMonth.AddMonths(-1);

var RequestIds = rdc.request
  .Where(r => lastMonth <= r.dteCreated)
  .Where(r => r.dteCreated < thisMonth)
  .Select(r => r.intRequestId);

Is there a way to make numbers in an ordered list bold?

This is an update for dcodesmith's answer https://stackoverflow.com/a/21369918/1668200

The proposed solution also works when the text is longer (i.e. the lines need to wrap): Updated Fiddle

When you're using a grid system, you might need to do one of the following (at least this is true for Foundation 6 - couldn't reproduce it in the Fiddle):

  • Add box-sizing:content-box; to the list or its container
  • OR change text-indent:-2em; to -1.5em

P.S.: I wanted to add this as an edit to the original answer, but it was rejected.

mysql datetime comparison

I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :

[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...

stopPropagation vs. stopImmediatePropagation

event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.

$("p").click(function(event)
{ event.stopImmediatePropagation();
});
$("p").click(function(event)
{ // This function won't be executed 
$(this).css("color", "#fff7e3");
});

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

Can't get Gulp to run: cannot find module 'gulp-util'

You should install these as devDependencies:
- gulp-util
- gulp-load-plugins

Then, you can use them either this way:

var plugins     = require('gulp-load-plugins')();
Use gulp-util as : plugins.util()

or this:

var util = require('gulp-util')

What exactly is LLVM?

A good summary of LLVM is this:

enter image description here

At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.

At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.

Simple java program of pyramid

enter image description here

 import java.util.Scanner;
    public class Print {
        public static void main(String[] args) {
            int row,temp,c,n;
            Scanner s=new Scanner(System.in);
            n=s.nextInt();
            temp = n;
            for ( row = 1 ; row <= n ; row++ )
               {
                  for ( c = 1 ; c < temp ; c++ )
                    System.out.print(" ");

                  temp--;

                  for ( c = 1 ; c <= 2*row - 1 ; c++ )
                      System.out.print("*");

                  System.out.println("");
               }
        }

    }

Interface/enum listing standard mime-type constants

There is now also the class org.apache.http.entity.ContentType from package org.apache.httpcomponents.httpcore, starting from 4.2 up.

JSON - Iterate through JSONArray

for(int i = 0; i < getArray.size(); i++){
      Object object = getArray.get(i);
      // now do something with the Object
}

You need to check for the type:

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]

In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names() to retrieve the individual keys.

"Non-static method cannot be referenced from a static context" error

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want

public void loanItem() {
    this.media.setLoanItem("Yes");
}

or

public void loanItem(Media object) {
    object.setLoanItem("Yes");
}

depending on how you want to pass that instance around.

How can I use std::maps with user-defined types as key?

By default std::map (and std::set) use operator< to determine sorting. Therefore, you need to define operator< on your class.

Two objects are deemed equivalent if !(a < b) && !(b < a).

If, for some reason, you'd like to use a different comparator, the third template argument of the map can be changed, to std::greater, for example.

How to line-break from css, without using <br />?

Using &nbsp; instead of spaces will prevent a break.

<span>I&nbsp;DONT&nbsp;WANT&nbsp;TO&nbsp;BREAK&nbsp;THIS&nbsp;LINE&nbsp;UP, but this text can be on any line.</span>

How to retrieve Jenkins build parameters using the Groovy API?

Update: Jenkins 2.x solution:

With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:

echo " FOOBAR value: ${params.'FOOBAR'}"

The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at: https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters

Original Answer for Jenkins 1.x:

For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:

// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters: https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

The salient part is reproduced below:

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${it.name}:"
   println it.dump()
}

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

mkdir's "-p" option

mkdir [-switch] foldername

-p is a switch which is optional, it will create subfolder and parent folder as well even parent folder doesn't exist.

From the man page:

-p, --parents no error if existing, make parent directories as needed

Example:

mkdir -p storage/framework/{sessions,views,cache}

This will create subfolder sessions,views,cache inside framework folder irrespective of 'framework' was available earlier or not.

Internal Error 500 Apache, but nothing in the logs?

The answers by @eric-leschinski is correct.

But there is another case if your Server API is FPM/FastCGI (Default on Centos 8 or you can check use phpinfo() function)

In this case:

  1. Run phpinfo() in a php file;
  2. Looking for Loaded Configuration File param to see where is config file for your PHP.
  3. Edit config file like @eric-leschinski 's answer.
  4. Check Server API param. If your server only use apache handle API -> restart apache. If your server use php-fpm you must restart php-fpm service

    systemctl restart php-fpm

    Check the log file in php-fpm log folder. eg /var/log/php-fpm/www-error.log

Adding a caption to an equation in LaTeX

As in this forum post by Gonzalo Medina, a third way may be:

\documentclass{article}
\usepackage{caption}

\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}

\begin{document}

Some text

\begin{equ}[!ht]
  \begin{equation}
    a=b+c
  \end{equation}
\caption{Caption of the equation}
\end{equ}

Some other text
 
\end{document}

More details of the commands used from package caption: here.

A screenshot of the output of the above code:

screenshot of output

Using %s in C correctly - very basic level

Here goes:

char str[] = "This is the end";
char input[100];

printf("%s\n", str);
printf("%c\n", *str);

scanf("%99s", input);

Send email by using codeigniter library via localhost

$insert = $this->db->insert('email_notification', $data);
                $this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");

                //require ("plugins/mailer/PHPMailerAutoload.php");
                $mail = new PHPMailer;
                $mail->SMTPOptions = array(
                    'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                ),
                );

                $message="
                     Your Account Has beed created successfully by Admin:
                    Username: ".$this->input->post('username')." <br><br>
                    Email: ".$this->input->post('sender_email')." <br><br>
                    Regargs<br>
                    <div class='background-color:#666;color:#fff;padding:6px;
                    text-align:center;'>
                         Bookly Admin.
                    </div>
                ";
                $mail->isSMTP(); // Set mailer to use SMTP
                $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
                $mail->SMTPAuth = true; 
                $subject = "Hello  ".$this->input->post('username');
                $mail->SMTDebug=2;
                $email = $this->input->post('sender_email'); //this email is user email
                $from_label = "Account Creation";
                $mail->Username = 'your email'; // SMTP username
                $mail->Password = 'password'; // SMTP password
                $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 465;
                $mail->setFrom($from_label);
                $mail->addAddress($email, 'Bookly Admin');
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message;
                $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
             if($mail->send()){

                  }

String literals and escape characters in postgresql

Cool.

I also found the documentation regarding the E:

http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS

PostgreSQL also accepts "escape" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g. E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \b is a backspace, \f is a form feed, \n is a newline, \r is a carriage return, \t is a tab. Also supported are \digits, where digits represents an octal byte value, and \xhexdigits, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (\\). Also, a single quote can be included in an escape string by writing \', in addition to the normal way of ''.

React.js create loop through Array

You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

linux execute command remotely

 ssh user@machine 'bash -s' < local_script.sh

or you can just

 ssh user@machine "remote command to run" 

JSON Naming Convention (snake_case, camelCase or PascalCase)

As others have stated there is no standard so you should choose one yourself. Here are a couple of things to consider when doing so:

  1. If you are using JavaScript to consume JSON then using the same naming convention for properties in both will provide visual consistency and possibly some opportunities for cleaner code re-use.

  2. A small reason to avoid kebab-case is that the hyphens may clash visually with - characters that appear in values.

    {
      "bank-balance": -10
    }
    

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

How to grep for multiple strings in file on different lines (Use the pipe symbol):

for file in *;do 
   test $(grep -E 'Dansk|Norsk|Svenska' $file | wc -l) -ge 3 && echo $file
done

Notes:

  1. If you use double quotes "" with your grep, you will have to escape the pipe like this: \| to search for Dansk, Norsk and Svenska.

  2. Assumes that one line has only one language.

Walkthrough: http://www.cyberciti.biz/faq/howto-use-grep-command-in-linux-unix/

Angular - "has no exported member 'Observable'"

I had a similar issue. Back-revving RXJS from 6.x to the latest 5.x release fixed it for Angular 5.2.x.

Open package.json.

Change "rxjs": "^6.0.0", to "rxjs": "^5.5.10",

run npm update

Embedding Windows Media Player for all browsers

The best way to deploy video on the web is using Flash - it's much easier to embed cleanly into a web page and will play on more or less any browser and platform combination. The only reason to use Windows Media Player is if you're streaming content and you need extraordinarily strong digital rights management, and even then providers are now starting to use Flash even for these. See BBC's iPlayer for a superb example.

I would suggest that you switch to Flash even for internal use. You never know who is going to need to access it in the future, and this will give you the best possible future compatibility.

EDIT - March 20 2013. Interesting how these old questions resurface from time to time! How different the world is today and how dated this all seems. I would not recommend a Flash only route today by any means - best practice these days would probably be to use HTML 5 to embed H264 encoded video, with a Flash fallback as described here: http://diveintohtml5.info/video.html

I want to convert std::string into a const wchar_t *

First convert it to std::wstring:

std::wstring widestr = std::wstring(str.begin(), str.end());

Then get the C string:

const wchar_t* widecstr = widestr.c_str();

This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

How to cast List<Object> to List<MyClass>

Depending on your other code the best answer may vary. Try:

List<? extends Object> list = getList();
return (List<Customer>) list;

or

List list = getList();
return (List<Customer>) list;

But have in mind it is not recommended to do such unchecked casts.

Performing user authentication in Java EE / JSF using j_security_check

I suppose you want form based authentication using deployment descriptors and j_security_check.

You can also do this in JSF by just using the same predefinied field names j_username and j_password as demonstrated in the tutorial.

E.g.

<form action="j_security_check" method="post">
    <h:outputLabel for="j_username" value="Username" />
    <h:inputText id="j_username" />
    <br />
    <h:outputLabel for="j_password" value="Password" />
    <h:inputSecret id="j_password" />
    <br />
    <h:commandButton value="Login" />
</form>

You could do lazy loading in the User getter to check if the User is already logged in and if not, then check if the Principal is present in the request and if so, then get the User associated with j_username.

package com.stackoverflow.q2206911;

import java.io.IOException;
import java.security.Principal;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Auth {

    private User user; // The JPA entity.

    @EJB
    private UserService userService;

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userService.find(principal.getName()); // Find User by j_username.
            }
        }
        return user;
    }

}

The User is obviously accessible in JSF EL by #{auth.user}.

To logout do a HttpServletRequest#logout() (and set User to null!). You can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You can also just invalidate the session altogether.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.


Update: you can also use the new Servlet 3.0 HttpServletRequest#login() to do a programmatic login instead of using j_security_check which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username and password properties and a login method which look like this:

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>

And this view scoped managed bean which also remembers the initially requested page:

@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURL += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}

This way the User is accessible in JSF EL by #{user}.

How do I wait for an asynchronously dispatched block to finish?

Very primitive solution to the problem:

void (^nextOperationAfterLongOperationBlock)(void) = ^{

};

[object runSomeLongOperationAndDo:^{
    STAssert…
    nextOperationAfterLongOperationBlock();
}];

how to run a command at terminal from java program?

I know this question is quite old, but here's a library that encapsulates the ProcessBuilder api.

No increment operator (++) in Ruby?

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)

That explains it better than I ever could.

EDIT: and the reason from the language author himself (source):

  1. ++ and -- are NOT reserved operator in Ruby.
  2. C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
  3. self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Below are the differences between CrudRepository and JpaRepository as:

CrudRepository

  1. CrudRepository is a base interface and extends the Repository interface.
  2. CrudRepository mainly provides CRUD (Create, Read, Update, Delete) operations.
  3. Return type of saveAll() method is Iterable.
  4. Use Case - To perform CRUD operations, define repository extending CrudRepository.

JpaRepository

  1. JpaRepository extends PagingAndSortingRepository that extends CrudRepository.
  2. JpaRepository provides CRUD and pagination operations, along with additional methods like flush(), saveAndFlush(), and deleteInBatch(), etc.
  3. Return type of saveAll() method is a List.
  4. Use Case - To perform CRUD as well as batch operations, define repository extends JpaRepository.

How to create Gmail filter searching for text only at start of subject line?

I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:

Matches: subject:([test])
Do this: Skip Inbox

And then I sent a message with the subject

[test] foo

And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

How to write the Fibonacci Sequence?

I was trying to avoid a recursive function to solve this problem, so I took an iterative approach. I was originally doing a memoized recursive function but kept hitting max recursive depth. I also had strict memory goals so you will see me keeping the array as small as I can during the looping process only keeping 2-3 values in the array at any time.

def fib(n):
    fibs = [1, 1] # my starting array
    for f in range(2, n):
        fibs.append(fibs[-1] + fibs[-2]) # appending the new fib number
        del fibs[0] # removing the oldest number
    return fibs[-1] # returning the newest fib

print(fib(6000000))

Getting the 6 millionth fibonacci number takes about 282 seconds on my machine while the 600k fibonacci takes only 2.8 seconds. I was unable to obtain such large fibonacci numbers with a recursive function, even a memoized one.

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

Try downloading a different version of maven. I had the same problem with maven 3.5.2 , I solved my problem just downloading maven 3.0.4

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

How to expire a cookie in 30 minutes using jQuery?

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.

As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).

So 30 minutes is 30 / 1440 = 0.02083333.

Final code:

$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });

I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

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

I had the same problem in my (YouTube player project)... and the following solved the problem for me:

  1. Add this code into your build.gradle (module: app) inside defaultConfing:

    defaultConfig {
        ....
        ....
        multiDexEnabled = true
    }
    
  2. Add this code into your build.gradle (module: app) inside dependencies:

    dependencies {
        compile 'com.android.support:multidex:1.0.1'
        .....
        .....
    }
    
  3. Open AndroidManifest.xml and within application:

    <application
        android:name="android.support.multidex.MultiDexApplication"
        .....
        .....
    </application>
    

    or if you have your App class, extend it from MultiDexApplication like:

    public class MyApp extends MultiDexApplication {
    .....
    

And finally, I think you should have Android Support Repository downloaded, in the Extras in SDK Manager.

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

You can use general compound drawable implementation, but if you need to define a size of drawable use this library:

https://github.com/a-tolstykh/textview-rich-drawable

Here is a small example of usage:

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some text"
        app:compoundDrawableHeight="24dp"
        app:compoundDrawableWidth="24dp" />

How can I flush GPU memory using CUDA (physical reset is unavailable)

on macOS (/ OS X), if someone else is having trouble with the OS apparently leaking memory:

  • https://github.com/phvu/cuda-smi is useful for quickly checking free memory
  • Quitting applications seems to free the memory they use. Quit everything you don't need, or quit applications one-by-one to see how much memory they used.
  • If that doesn't cut it (quitting about 10 applications freed about 500MB / 15% for me), the biggest consumer by far is WindowServer. You can Force quit it, which will also kill all applications you have running and log you out. But it's a bit faster than a restart and got me back to 90% free memory on the cuda device.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Look "!"

Thanks guys. I solved this problem through your help. So, I hope this screenshot helpful to person who have same problem.

Replace tabs with spaces in vim

IIRC, something like:

set tabstop=2 shiftwidth=2 expandtab

should do the trick. If you already have tabs, then follow it up with a nice global RE to replace them with double spaces.

If you already have tabs you want to replace,

:retab

How to serialize an object into a string

Java8 approach, converting Object from/to String, inspired by answer from OscarRyz. For de-/encoding, java.util.Base64 is required and used.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;
import java.util.Optional;

final class ObjectHelper {

  private ObjectHelper() {}

  static Optional<String> convertToString(final Serializable object) {
    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos)) {
      oos.writeObject(object);
      return Optional.of(Base64.getEncoder().encodeToString(baos.toByteArray()));
    } catch (final IOException e) {
      e.printStackTrace();
      return Optional.empty();
    }
  }

  static <T extends Serializable> Optional<T> convertFrom(final String objectAsString) {
    final byte[] data = Base64.getDecoder().decode(objectAsString);
    try (final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
      return Optional.of((T) ois.readObject());
    } catch (final IOException | ClassNotFoundException e) {
      e.printStackTrace();
      return Optional.empty();
    }
  }
}

How do I print the content of a .txt file in Python?

with open("filename.txt", "w+") as file:
  for line in file:
    print line

This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop

Change window location Jquery

I'm assuming you're using jquery to make the AJAX call so you can do this pretty easily by putting the redirect in the success like so:

    $.ajax({
       url: 'ajax_location.html',
       success: function(data) {
          //this is the redirect
          document.location.href='/newpage/';
       }
    });

How do I determine k when using k-means clustering?

You can maximize the Bayesian Information Criterion (BIC):

BIC(C | X) = L(X | C) - (p / 2) * log n

where L(X | C) is the log-likelihood of the dataset X according to model C, p is the number of parameters in the model C, and n is the number of points in the dataset. See "X-means: extending K-means with efficient estimation of the number of clusters" by Dan Pelleg and Andrew Moore in ICML 2000.

Another approach is to start with a large value for k and keep removing centroids (reducing k) until it no longer reduces the description length. See "MDL principle for robust vector quantisation" by Horst Bischof, Ales Leonardis, and Alexander Selb in Pattern Analysis and Applications vol. 2, p. 59-72, 1999.

Finally, you can start with one cluster, then keep splitting clusters until the points assigned to each cluster have a Gaussian distribution. In "Learning the k in k-means" (NIPS 2003), Greg Hamerly and Charles Elkan show some evidence that this works better than BIC, and that BIC does not penalize the model's complexity strongly enough.

How can I close a browser window without receiving the "Do you want to close this window" prompt?

Because of the security enhancements in IE, you can't close a window unless it is opened by a script. So the way around this will be to let the browser think that this page is opened using a script, and then to close the window. Below is the implementation.

Try this, it works like a charm!
javascript close current window without prompt IE

<script type="text/javascript">
function closeWP() {
 var Browser = navigator.appName;
 var indexB = Browser.indexOf('Explorer');

 if (indexB > 0) {
    var indexV = navigator.userAgent.indexOf('MSIE') + 5;
    var Version = navigator.userAgent.substring(indexV, indexV + 1);

    if (Version >= 7) {
        window.open('', '_self', '');
        window.close();
    }
    else if (Version == 6) {
        window.opener = null;
        window.close();
    }
    else {
        window.opener = '';
        window.close();
    }

 }
else {
    window.close();
 }
}
</script>

javascript close current window without prompt IE

Why I've got no crontab entry on OS X when using vim?

The error crontab: temp file must be edited in place is because of the way vim treats backup files.

To use vim with cron, add the following lines in your .bash_profile
export EDITOR=vim
alias crontab="VIM_CRONTAB=true crontab"

Source the file:
source .bash_profile

And then in your .vimrc add:
if $VIM_CRONTAB == "true" set nobackup set nowritebackup endif

This will disable backups when using vim with cron. And you will be able to use crontab -e to add/edit cronjobs.

On successfully saving your cronjob, you will see the message:
crontab: installing new crontab

Source:
http://drawohara.com/post/6344279/crontab-temp-file-must-be-edited-in-placeenter link description here

What is the best way to delete a value from an array in Perl?

If you know the array index, you can delete() it. The difference between splice() and delete() is that delete() does not renumber the remaining elements of the array.

Visual Studio loading symbols

I had a similar issue where visual studio keeps loading symbol and got stuck.

It turns out I added some "Command line arguments" in the Debug options, and one of the parameters is invalid(I am supposed to pass in some values). enter image description here

After I remove the extra parameter, it starts working again.

Request Monitoring in Chrome

In the step 5 of Phil, "Resources" is no longer available in the new version of the Chrome. You need to click the page icon just beside the Ajax page listed in the bottom pane with the columns of Name, Method, Status, ...

Then it will show you more panels where you will find the error messages.

Generate Json schema from XML schema (XSD)

Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.

Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.

Let's take the Purchase Order schema for example. Here's a fragment:

  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>

You can compile this schema using the provided command-line tool:

java -jar jsonix-schema-compiler-full.jar
    -generateJsonSchema
    -p PO
    schemas/purchaseorder.xsd

The compiler generates Jsonix mappings as well the matching JSON Schema.

Here's what the result looks like (edited for brevity):

{
    "id":"PurchaseOrder.jsonschema#",
    "definitions":{
        "PurchaseOrderType":{
            "type":"object",
            "title":"PurchaseOrderType",
            "properties":{
                "shipTo":{
                    "title":"shipTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                },
                "billTo":{
                    "title":"billTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                }, ...
            }
        },
        "USAddress":{ ... }, ...
    },
    "anyOf":[
        {
            "type":"object",
            "properties":{
                "name":{
                    "$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
                },
                "value":{
                    "$ref":"#/definitions/PurchaseOrderType"
                }
            },
            "elementName":{
                "localPart":"purchaseOrder",
                "namespaceURI":""
            }
        }
    ]
}

Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.

The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).

Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.

Links:

"ImportError: No module named" when trying to run Python script

This answer applies to this question if

  1. You don't want to change your code
  2. You don't want to change PYTHONPATH permanently

Temporarily modify PYTHONPATH

path below can be relative

PYTHONPATH=/path/to/dir python script.py

How to add buttons dynamically to my form?

First, you aren't actually creating 10 buttons. Second, you need to set the location of each button, or they will appear on top of each other. This will do the trick:

  for (int i = 0; i < 10; ++i)
  {
      var button = new Button();
      button.Location = new Point(button.Width * i + 4, 0);
      Controls.Add(button);
  }

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

What is the best way to insert source code examples into a Microsoft Word document?

I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.

Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

  1. Choose Insert / Text Box / Simple Text Box
    01word
  2. A default text box is inserted
    02word
  3. Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard
    03npp
  4. Switch back to word, and paste into the text box - it may be too small ...
    04word
  5. ... so you may have to change its size
    05word
  6. Having selected the text box, right-click on it, then choose Insert Caption ...
    06word
  7. In the Caption menu, if you don't have one already, click New Label, and set the new label to "Code", click OK ...
    07word
  8. ... then in the Caption dialog, switch the label to Code, and hit OK
    08word
  9. Finally, type your caption in the newly created caption box
    09word

MySQL config file location - redhat linux server

On RH systems, MySQL configuration file is located under /etc/my.cnf by default.

What Java ORM do you prefer, and why?

SimpleORM, because it is straight-forward and no-magic. It defines all meta data structures in Java code and is very flexible.

SimpleORM provides similar functionality to Hibernate by mapping data in a relational database to Java objects in memory. Queries can be specified in terms of Java objects, object identity is aligned with database keys, relationships between objects are maintained and modified objects are automatically flushed to the database with optimistic locks.

But unlike Hibernate, SimpleORM uses a very simple object structure and architecture that avoids the need for complex parsing, byte code processing etc. SimpleORM is small and transparent, packaged in two jars of just 79K and 52K in size, with only one small and optional dependency (Slf4j). (Hibernate is over 2400K plus about 2000K of dependent Jars.) This makes SimpleORM easy to understand and so greatly reduces technical risk.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Create a Game model which extends Eloquent and use this:

Game::take(30)->skip(30)->get();

take() here will get 30 records and skip() here will offset to 30 records.


In recent Laravel versions you can also use:

Game::limit(30)->offset(30)->get();

How to find if directory exists in Python

os provides you with a lot of these capabilities:

import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in)    #gets you a list of all files and directories under dir_in

the listdir will throw an exception if the input path is invalid.

using stored procedure in entity framework

You can call a stored procedure using SqlQuery (See here)

// Prepare the query
var query = context.Functions.SqlQuery(
    "EXEC [dbo].[GetFunctionByID] @p1", 
    new SqlParameter("p1", 200));

// add NoTracking() if required

// Fetch the results
var result = query.ToList();

Trying to start a service on boot on Android

I have an additional <category>-tag, don't know if that makes any difference.

<receiver android:name="BootIntentReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
            <category android:name="android.intent.category.HOME" />  
        </intent-filter>  
</receiver>

Have you tried ommiting the if-clause "android.intent.action.BOOT_COMPLETED".equals(intent.getAction(), as the receiver probably only receives that intent anyway?

XML Parsing - Read a Simple XML File and Retrieve Values

I usually use XmlDocument for this. The interface is pretty straight forward:

var doc = new XmlDocument();
doc.LoadXml(xmlString);

You can access nodes similar to a dictionary:

var tasks = doc["Tasks"];

and loop over all children of a node.

How to Identify port number of SQL server

  1. Open Run in your system.

  2. Type %windir%\System32\cliconfg.exe

  3. Click on ok button then check that the "TCP/IP Network Protocol Default Value Setup" pop-up is open.

  4. Highlight TCP/IP under the Enabled protocols window.

  5. Click the Properties button.

  6. Enter the new port number, then click OK.

enter image description here

Linux command-line call not returning what it should from os.system?

If you're only interested in the output from the process, it's easiest to use subprocess' check_output function:


output = subprocess.check_output(["command", "arg1", "arg2"]);

Then output holds the program output to stdout. Check the link above for more info.

Unix command to find lines common in two files

While

grep -v -f 1.txt 2.txt > 3.txt

gives you the differences of two files (what is in 2.txt and not in 1.txt), you could easily do a

grep -f 1.txt 2.txt > 3.txt

to collect all common lines, which should provide an easy solution to your problem. If you have sorted files, you should take comm nonetheless. Regards!

Mockito How to mock only the call of a method of the superclass

create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test

jQuery selector first td of each row

You should use :first-child instead of :first:

Sounds like you're wanting to iterate through them. You can do this using .each().

Example:

$('td:first-child').each(function() {
    console.log($(this).text());
});

Result:

nonono
nonono2
nonono3

Alernatively if you're not wanting to iterate:

$('td:first-child').css('background', '#000');

JSFiddle demo.

How to multiply values using SQL

Why use GROUP BY at all?

SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC

How to evaluate a math expression given in string form?

The correct way to solve this is with a lexer and a parser. You can write simple versions of these yourself, or those pages also have links to Java lexers and parsers.

Creating a recursive descent parser is a really good learning exercise.

Java foreach loop: for (Integer i : list) { ... }

One way to do that is to use a counter:

ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) { 
    ...
    if (--size == 0) {
        // Last item.
        ...
    }
}

Edit

Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for loop or the iterator, as everything you win when using the Java5 syntax will be lost in the loop itself...

for (int i = 0; i < list.size(); i++) {
    ...

    if (i == (list.size() - 1)) {
        // Last item...
    }
}

or

for (Iterator it = list.iterator(); it.hasNext(); ) {
    ...

    if (!it.hasNext()) {
        // Last item...
    }
}

What is the use of the %n format specifier in C?

Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

#include <stdio.h>

int main()
{
  int val;

  printf("blah %n blah\n", &val);

  printf("val = %d\n", val);

  return 0;

}

The previous code prints:

blah  blah
val = 5

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

How to make overlay control above all other controls?

Put the control you want to bring to front at the end of your xaml code. I.e.

<Grid>
  <TabControl ...>
  </TabControl>
  <Button Content="ALways on top of TabControl Button"/>
</Grid>

'Syntax Error: invalid syntax' for no apparent reason

I encountered a similar problem, with a syntax error that I knew should not be a syntax error. In my case it turned out that a Python 2 interpreter was trying to run Python 3 code, or vice versa; I think that my shell had a PYTHONPATH with a mixture of Python 2 and Python 3.

Track a new remote branch created on GitHub

First of all you have to fetch the remote repository:

git fetch remoteName

Than you can create the new branch and set it up to track the remote branch you want:

git checkout -b newLocalBranch remoteName/remoteBranch

You can also use "git branch --track" instead of "git checkout -b" as max specified.

git branch --track newLocalBranch remoteName/remoteBranch

Easy way to password-protect php page

Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.

Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.

They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.

If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.

<?php
$user = $_POST['user'];
$pass = $_POST['pass'];

if($user == "admin"
&& $pass == "admin")
{
        include("secure.html");
}
else
{
    if(isset($_POST))
    {?>

            <form method="POST" action="secure.php">
            User <input type="text" name="user"></input><br/>
            Pass <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Go"></input>
            </form>
    <?}
}
?>

Call apply-like function on each row of dataframe with multiple arguments from each row

data.table has a really intuitive way of doing this as well:

library(data.table)

sample_fxn = function(x,y,z){
    return((x+y)*z)
}

df = data.table(A = 1:5,B=seq(2,10,2),C = 6:10)
> df
   A  B  C
1: 1  2  6
2: 2  4  7
3: 3  6  8
4: 4  8  9
5: 5 10 10

The := operator can be called within brackets to add a new column using a function

df[,new_column := sample_fxn(A,B,C)]
> df
   A  B  C new_column
1: 1  2  6         18
2: 2  4  7         42
3: 3  6  8         72
4: 4  8  9        108
5: 5 10 10        150

It's also easy to accept constants as arguments as well using this method:

df[,new_column2 := sample_fxn(A,B,2)]

> df
   A  B  C new_column new_column2
1: 1  2  6         18           6
2: 2  4  7         42          12
3: 3  6  8         72          18
4: 4  8  9        108          24
5: 5 10 10        150          30

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

Convert a PHP script into a stand-alone windows executable

Peachpie

http://www.peachpie.io

https://github.com/iolevel/peachpie

Peachpie is PHP 7 compiler based on Roslyn by Microsoft and drawing from popular Phalanger. It allows PHP to be executed within the .NET/.NETCore by compiling the PHP code to pure MSIL.

Phalanger

http://v4.php-compiler.net/

http://wiki.php-compiler.net/Phalanger_Wiki

https://github.com/devsense/phalanger

Phalanger is a project which was started at Charles University in Prague and was supported by Microsoft. It compiles source code written in the PHP scripting language into CIL (Common Intermediate Language) byte-code. It handles the beginning of a compiling process which is completed by the JIT compiler component of the .NET Framework. It does not address native code generation nor optimization. Its purpose is to compile PHP scripts into .NET assemblies, logical units containing CIL code and meta-data.

Bambalam

https://github.com/xZero707/Bamcompile/

Bambalam PHP EXE Compiler/Embedder is a free command line tool to convert PHP applications to standalone Windows .exe applications. The exe files produced are totally standalone, no need for php dlls etc. The php code is encoded using the Turck MMCache Encode library so it's a perfect solution if you want to distribute your application while protecting your source code. The converter is also suitable for producing .exe files for windowed PHP applications (created using for example the WinBinder library). It's also good for making stand-alone PHP Socket servers/clients (using the php_sockets.dll extension). It's NOT really a compiler in the sense that it doesn't produce native machine code from PHP sources, but it works!

ZZEE PHPExe

http://www.zzee.com/phpexe/

ZZEE PHPExe compiles PHP, HTML, Javascript, Flash and other web files into Windows GUI exes. You can rapidly develop Windows GUI applications by employing the familiar PHP web paradigm. You can use the same code for online and Windows applications with little or no modification. It is a Commercial product.

phc-win

http://wiki.swiftlytilting.com/Phc-win

The PHP extension bcompiler is used to compile PHP script code into PHP bytecode. This bytecode can be included just like any php file as long as the bcompiler extension is loaded. Once all the bytecode files have been created, a modified Embeder is used to pack all of the project files into the program exe.

Requires

  • php5ts.dll
  • php_win32std.dll
  • php_bcompiler.dll
  • php-embed.ini

ExeOutput

http://www.exeoutput.com/

Commercial

WinBinder

http://winbinder.org/

WinBinder is an open source extension to PHP, the script programming language. It allows PHP programmers to easily build native Windows applications, producing quick and rewarding results with minimum effort. Even short scripts with a few dozen lines can generate a useful program, thanks to the power and flexibility of PHP.

PHPDesktop

https://github.com/cztomczak/phpdesktop

PHP Desktop is an open source project founded by Czarek Tomczak in 2012 to provide a way for developing native desktop applications using web technologies such as PHP, HTML5, JavaScript & SQLite. This project is more than just a PHP to EXE compiler, it embeds a web-browser (Internet Explorer or Chrome embedded), a Mongoose web-server and a PHP interpreter. The development workflow you are used to remains the same, the step of turning an existing website into a desktop application is basically a matter of copying it to "www/" directory. Using SQLite database is optional, you could embed mysql/postgresql database in application's installer.

PHP Nightrain

https://github.com/kjellberg/nightrain

Using PHP Nightrain you will be able to deploy and run HTML, CSS, JavaScript and PHP web applications as a native desktop application on Windows, Mac and the Linux operating systems. Popular PHP Frameworks (e.g. CakePHP, Laravel, Drupal, etc…) are well supported!

phc-win "fork"

https://github.com/RDashINC/phc-win

A more-or-less forked version of phc-win, it uses the same techniques as phc-win but supports almost all modern PHP versions. (5.3, 5.4, 5.5, 5.6, etc) It also can use Enigma VB to combine the php5ts.dll with your exe, aswell as UPX compress it. Lastly, it has win32std and winbinder compilied statically into PHP.

EDIT

Another option is to use

http://www.appcelerator.com/products/titanium-cross-platform-application-development/

an online compiler that can build executables for a number of different platforms, from a number of different languages including PHP

TideSDK

http://www.tidesdk.org/

TideSDK is actually the renamed Titanium Desktop project. Titanium remained focused on mobile, and abandoned the desktop version, which was taken over by some people who have open sourced it and dubbed it TideSDK.

Generally, TideSDK uses HTML, CSS and JS to render applications, but it supports scripted languages like PHP, as a plug-in module, as well as other scripting languages like Python and Ruby.

Scanner vs. StringTokenizer vs. String.Split

String.split seems to be much slower than StringTokenizer. The only advantage with split is that you get an array of the tokens. Also you can use any regular expressions in split. org.apache.commons.lang.StringUtils has a split method which works much more faster than any of two viz. StringTokenizer or String.split. But the CPU utilization for all the three is nearly the same. So we also need a method which is less CPU intensive, which I am still not able to find.

UIGestureRecognizer on UIImageView

SWIFT 3 Example

override func viewDidLoad() {

    self.backgroundImageView.addGestureRecognizer(
        UITapGestureRecognizer.init(target: self, action:#selector(didTapImageview(_:)))
    )

    self.backgroundImageView.isUserInteractionEnabled = true
}

func didTapImageview(_ sender: Any) {
    // do something
}

No gesture recongnizer delegates or other implementations where necessary.

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

Dynamically updating plot in matplotlib

In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw alone does not produce the plot (at least with the qt backend).

The following works for me:

import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
    #Suppose we know the x range
    min_x = 0
    max_x = 10

    def on_launch(self):
        #Set up plot
        self.figure, self.ax = plt.subplots()
        self.lines, = self.ax.plot([],[], 'o')
        #Autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(self.min_x, self.max_x)
        #Other stuff
        self.ax.grid()
        ...

    def on_running(self, xdata, ydata):
        #Update data (with the new _and_ the old points)
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        #Need both of these in order to rescale
        self.ax.relim()
        self.ax.autoscale_view()
        #We need to draw *and* flush
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()

    #Example
    def __call__(self):
        import numpy as np
        import time
        self.on_launch()
        xdata = []
        ydata = []
        for x in np.arange(0,10,0.5):
            xdata.append(x)
            ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
            self.on_running(xdata, ydata)
            time.sleep(1)
        return xdata, ydata

d = DynamicUpdate()
d()

How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

Implementing two interfaces in a class with same method. Which interface method is overridden?

As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.

But when two interface have a method with the same name but different return type and you implement two methods in concrete class:

Please look at below code:

public interface InterfaceA {
  public void print();
}


public interface InterfaceB {
  public int print();
}

public class ClassAB implements InterfaceA, InterfaceB {
  public void print()
  {
    System.out.println("Inside InterfaceA");
  }
  public int print()
  {
    System.out.println("Inside InterfaceB");
    return 5;
  }
}

when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.

So it goes haywire for compiler.

In this way, you will not be able to implement two interface having a method of same name but different return type.

How to remove blank lines from a Unix file

Use grep to match any line that has nothing between the start anchor (^) and the end anchor ($):

grep -v '^$' infile.txt > outfile.txt

If you want to remove lines with only whitespace, you can still use grep. I am using Perl regular expressions in this example, but here are other ways:

grep -P -v '^\s*$' infile.txt > outfile.txt

or, without Perl regular expressions:

grep -v '^[[:space:]]*$' infile.txt > outfile.txt

Play sound on button click android

there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.

Nice!

MediaActionSound

A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs

use like:

fun playBeepSound() {
    val sound = MediaActionSound()
    sound.play(MediaActionSound.START_VIDEO_RECORDING)
}

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

Both the accepted answer and the most-voted answer so far are now outdated. Password authentication is deprecated and it will be removed on November 13, 2020 at 16:00 UTC.

The way to use GitHub API now is via personal access tokens.

You need to (replace ALL CAPS keywords):

  1. Create a personal access token via the website. Yes, you have to use the browser, but it is only once for all future accesses. Store the token securely.
  2. Create the repo via
curl -H 'Authorization: token MY_ACCESS_TOKEN' https://api.github.com/user/repos  -d '{"name":"REPO"}'

or, to make it private from the start:

curl -H 'Authorization: token MY_ACCESS_TOKEN' https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}'
  1. Add the new origin and push to it:
git remote add origin [email protected]:USER/REPO.git
git push origin master

This has the disadvantage that you have to type the token each time, and that it appears in your bash history.

To avoid this, you can

  1. Store the header in a file (let's call it, say, HEADER_FILE)
Authorization: token MY_ACCESS_TOKEN
  1. Have curl read from the file
curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO"}' # public repo
curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}' # private repo
  1. To make things more secure, you could set access permissions to 400 and the user to root
chmod 400 HEADER_FILE
sudo chown root:root HEADER_FILE
  1. Now sudo will be needed to access the header file
sudo curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO"}' # public repo
sudo curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}' # private repo

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

How do I generate a random int number?

 int n = new Random().Next();

You can also give minimum and maximum value to Next() function. Like:

 int n = new Random().Next(5, 10);

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

Find character position and update file name

If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.

 $text = "asdfNAME=PC123456<>Diweursejsfdjiwr"

asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456

 $text.IndexOf("E=")

7 - this is the "FIND" command for Powershell

 $text.substring(10,5)

C1234 - this is the "MID" command for Powershell

 $text.substring($text.IndexOf("E=")+2,8)

PC123456 - tada it has found and cut our text

-RavonTUS

Expected initializer before function name

Try adding a semi colon to the end of your structure:

 struct sotrudnik {
    string name;
    string speciality;
    string razread;
    int zarplata;
} //Semi colon here

Better way to Format Currency Input editText?

I used this to allow the user to enter the currency and to convert it from string into int to store in db and to change back from int into string again

https://github.com/nleigh/Restaurant/blob/master/Restaurant/src/uk/co/nathanleigh/restaurant/CurrencyFormat.java

How can I convert a .py to .exe for Python?

Steps to convert .py to .exe in Python 3.6

  1. Install Python 3.6.
  2. Install cx_Freeze, (open your command prompt and type pip install cx_Freeze.
  3. Install idna, (open your command prompt and type pip install idna.
  4. Write a .py program named myfirstprog.py.
  5. Create a new python file named setup.py on the current directory of your script.
  6. In the setup.py file, copy the code below and save it.
  7. With shift pressed right click on the same directory, so you are able to open a command prompt window.
  8. In the prompt, type python setup.py build
  9. If your script is error free, then there will be no problem on creating application.
  10. Check the newly created folder build. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.

See the original script in my blog.

setup.py:

from cx_Freeze import setup, Executable

base = None    

executables = [Executable("myfirstprog.py", base=base)]

packages = ["idna"]
options = {
    'build_exe': {    
        'packages':packages,
    },    
}

setup(
    name = "<any name>",
    options = options,
    version = "<any number>",
    description = '<any description>',
    executables = executables
)

EDIT:

  • be sure that instead of myfirstprog.py you should put your .pyextension file name as created in step 4;
  • you should include each imported package in your .py into packages list (ex: packages = ["idna", "os","sys"])
  • any name, any number, any description in setup.py file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = '' )
  • the imported packages must be installed before you start step 8.

How do I install a custom font on an HTML site

Try this

_x000D_
_x000D_
@font-face {  _x000D_
    src: url(fonts/Market_vilis.ttf) format("truetype");_x000D_
}_x000D_
div.FontMarket { _x000D_
    font-family:  Market Deco;_x000D_
}
_x000D_
 <div class="FontMarket">KhonKaen Market</div>
_x000D_
_x000D_
_x000D_

vilis.org

jQuery each loop in table row

Just a recommendation:

I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.

var table = document.getElementById('tblOne');

var rowLength = table.rows.length;

for(var i=0; i<rowLength; i+=1){
  var row = table.rows[i];

  //your code goes here, looping over every row.
  //cells are accessed as easy

  var cellLength = row.cells.length;
  for(var y=0; y<cellLength; y+=1){
    var cell = row.cells[y];

    //do something with every cell here
  }
}

Remove an element from a Bash array

This is the most direct way to unset a value if you know it's position.

$ array=(one two three)
$ echo ${#array[@]}
3
$ unset 'array[1]'
$ echo ${array[@]}
one three
$ echo ${#array[@]}
2

ng-repeat: access key and value for each object in array of objects

In case this is an option for you, if you put your data into object form it works the way I think you're hoping for:

$scope.steps = {
 companyName: true,
 businessType: true,
 physicalAddress: true
};

Here's a fiddle of this: http://jsfiddle.net/zMjVp/

add an element to int [] array in java

Like others suggested you are better off using collection. If you however for some reason must stick to array then Apache Commons ArrayUtils may help:

int[] series = {4,2};
series = ArrayUtils.add(series, 3); // series is now {4,2,3}
series = ArrayUtils.add(series, 4); // series is now {4,2,3,4};

Note that the add method creates a new array, copies the given array and appends the new element at the end, which may have impact on performance.

Calling a parent window function from an iframe

parent.abc() will only work on same domain due to security purposes. i tried this workaround and mine worked perfectly.

<head>
    <script>
    function abc() {
        alert("sss");
    }

    // window of the iframe
    var innerWindow = document.getElementById('myFrame').contentWindow;
    innerWindow.abc= abc;

    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="abc();" href="#">Click Me</a>
    </iframe>
</body>

Hope this helps. :)

How to enable loglevel debug on Apache2 server

Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.

For older version apache:

For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:

RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"

Conditional HTML Attributes using Razor MVC3

You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...

<input type="text" id="@strElementID" class="@strCSSClass" />

If strCSSClass is null then the class attribute won't render at all.

SSSHHH...don't tell. :)

How to generate a create table script for an existing table in phpmyadmin?

Using PHP Function.

Of course query function ($this->model) you have to change to your own.

/**
 * Creating a copy table based on the current one
 * 
 * @param type $table_to_copy
 * @param type $new_table_name
 * @return type
 * @throws Exception
 */
public function create($table_to_copy, $new_table_name)
{
    $sql = "SHOW CREATE TABLE ".$table_to_copy;

    $res = $this->model->queryRow($sql, PDO::FETCH_ASSOC);

    if(!filled($res['Create Table']))
        throw new Exception('Could not get the create code for '.$table_to_copy);

    $newCreateSql = preg_replace(array(
        '@CREATE TABLE `'.$table_to_copy.'`@',
        '@KEY `'.$table_to_copy.'(.*?)`@',
        '@CONSTRAINT `'.$table_to_copy.'(.*?)`@',
        '@AUTO_INCREMENT=(.*?) @',
    ), array(
        'CREATE TABLE `'.$new_table_name.'`',
        'KEY `'.$new_table_name.'$1`',
        'CONSTRAINT `'.$new_table_name.'$1`',
        'AUTO_INCREMENT=1 ',
    ), $res['Create Table']);

    return $this->model->exec($newCreateSql);
}

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Some other service may be using port 80: try to stop the other services: HTTPD, SSL, NGINX, PHP, with the command sudo systemctl stop and then use the command sudo systemctl start httpd

UIView Hide/Show with animation

You can try this.

 func showView(objView:UIView){

    objView.alpha = 0.0
    UIView.animate(withDuration: 0.5, animations: {
        objView.alpha = 0.0
    }, completion: { (completeFadein: Bool) -> Void in
        objView.alpha = 1.0
        let transition = CATransition()
        transition.duration = 0.5
        transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        transition.type = kCATransitionFade
        objView.layer.add(transition, forKey: nil)
    })
}

func HideView(objView:UIView){

    UIView.animate(withDuration: 0.5, animations: {
        objView.alpha = 1.0
    }, completion: { (completeFadein: Bool) -> Void in
        objView.alpha = 0.0
        let transition = CATransition()
        transition.duration = 0.5
        transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        transition.type = kCATransitionFade
        objView.layer.add(transition, forKey: nil)
    })
}

And pass your view name

        showView(objView: self.viewSaveCard)
        HideView(objView: self.viewSaveCard)

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

jQuery add required to input fields

You can do it by using attr, the mistake that you made is that you put the true inside quotes. instead of that try this:

$("input").attr("required", true);

How can I get the browser's scrollbar sizes?

Using jQuery, you can shorten Matthew Vines answer to:

function getScrollBarWidth () {
    var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
        widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
    $outer.remove();
    return 100 - widthWithScroll;
};

Why does PEP-8 specify a maximum line length of 79 characters?

Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.

Readability is also one of the reasons for enforced line indentation.

Command failed due to signal: Segmentation fault: 11

If you're using multiple versions of XCode, this error can easily happen if your paths have changed (eg. You downloaded the DMG to Desktop, extracted, but then moved XCode to Applications afterward). Carefully read the Segmentation Fault 11 error given to you in XCode, it may reference your old path which is the cause of the Segmentation Fault. If it does, you can fix it by either:

  1. xcode-select the correct path. Eg. sudo xcode-select -s /Applications/Xcode-beta.app/Contents/Developer/ (obviously input your correct path here)
  2. When installing your second version of XCode, ensure it's being extracted to the final path (extract to Applications itself) and that 'XCode.app' doesn't already exist when you do so (rename your previous one if it exists). After it's installed, you can rename both as you like.

Another potential fix for this issue:

Upgrading from El Capitan to Sierra and 'installing extra components' when launching Xcode after this upgrade fixed it for me the first time this happened.

How do I make curl ignore the proxy?

Long shot but try setting the proxy to "" (empty string) that should override any proxy settings according to the man page.

How to remove multiple deleted files in Git repository

The built in clean function can also be helpful...

git clean -fd

Putting a simple if-then-else statement on one line

That's more specifically a ternary operator expression than an if-then, here's the python syntax

value_when_true if condition else value_when_false

Better Example: (thanks Mr. Burns)

'Yes' if fruit == 'Apple' else 'No'

Now with assignment and contrast with if syntax

fruit = 'Apple'
isApple = True if fruit == 'Apple' else False

vs

fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True

how to delete default values in text field using selenium?

.clear() can be used to clear the text

  (locator).clear();

using clear with the locator deletes all the value in that exact locator.

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

How to decode jwt token in javascript without using a library?

You can use jwt-decode, so then you could write:

import jwt_decode from 'jwt-decode';

var token = 'eyJ0eXAiO.../// jwt token';

var decoded = jwt_decode(token);
console.log(decoded);
/*{exp: 10012016 name: john doe, scope:['admin']}*/

Algorithm to calculate the number of divisors of a given number

Before you commit to a solution consider that the Sieve approach might not be a good answer in the typical case.

A while back there was a prime question and I did a time test--for 32-bit integers at least determining if it was prime was slower than brute force. There are two factors going on:

1) While a human takes a while to do a division they are very quick on the computer--similar to the cost of looking up the answer.

2) If you do not have a prime table you can make a loop that runs entirely in the L1 cache. This makes it faster.

Angular.js How to change an elements css class on click and to remove all others

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

Parse Json string in C#

I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:

EDIT: I changed the code so it supports reading your json file (array)

Code to parse:

void Main()
{
    var json = System.IO.File.ReadAllText(@"d:\test.json");

    var objects = JArray.Parse(json); // parse as array  
    foreach(JObject root in objects)
    {
        foreach(KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            var description = (String)app.Value["Description"];
            var value = (String)app.Value["Value"];

            Console.WriteLine(appName);
            Console.WriteLine(description);
            Console.WriteLine(value);
            Console.WriteLine("\n");
        }
    }
}

Output:

AppName
Lorem ipsum dolor sit amet
1


AnotherAppName
consectetur adipisicing elit
String


ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text


Application
Ut enim ad minim veniam
100


LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ

BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.

How do I use PHP to get the current year?

in my case the copyright notice in the footer of a wordpress web site needed updating.

thought simple, but involved a step or more thann anticipated.

  1. Open footer.php in your theme's folder.

  2. Locate copyright text, expected this to be all hard coded but found:

    <div id="copyright">
        <?php the_field('copyright_disclaimer', 'options'); ?>
    </div>
    
  3. Now we know the year is written somewhere in WordPress admin so locate that to delete the year written text. In WP-Admin, go to Options on the left main admin menu:

    enter image description here Then on next page go to the tab Disclaimers:

    enter image description here and near the top you will find Copyright year:

    enter image description here DELETE the © symbol + year + the empty space following the year, then save your page with Update button at top-right of page.

  4. With text version of year now delete, we can go and add our year that updates automatically with PHP. Go back to chunk of code in STEP 2 found in footer.php and update that to this:

    <div id="copyright">
        &copy;<?php echo date("Y"); ?> <?php the_field('copyright_disclaimer', 'options'); ?>
    </div>
    
  5. Done! Just need to test to ensure changes have taken effect as expected.

this might not be the same case for many, however we've come across this pattern among quite a number of our client sites and thought it would be best to document here.

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

Convert list of dictionaries to a pandas DataFrame

The easiest way I have found to do it is like this:

dict_count = len(dict_list)
df = pd.DataFrame(dict_list[0], index=[0])
for i in range(1,dict_count-1):
    df = df.append(dict_list[i], ignore_index=True)

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

Mysql database sync between two databases

three different approaches:

  1. Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.

  2. replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.

  3. offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.

ArrayList vs List<> in C#

Using List<T> you can prevent casting errors. It is very useful to avoid a runtime casting error.

Example:

Here (using ArrayList) you can compile this code but you will see an execution error later.

ArrayList array1 = new ArrayList();
array1.Add(1);
array1.Add("Pony"); //No error at compile process
int total = 0;
foreach (int num in array1)
{
 total += num; //-->Runtime Error
}

If you use List, you avoid these errors:

List<int> list1 = new List<int>();
list1.Add(1);
//list1.Add("Pony"); //<-- Error at compile process
int total = 0;
foreach (int num in list1 )
{
 total += num;
}

Reference: MSDN

PHP strtotime +1 month adding an extra month

This should be

$endOfCycle=date('Y-m-d', strtotime("+30 days"));

strtotime

expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

while

date

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.

See the manual pages for:

How can I send an email through the UNIX mailx command?

Its faster with MUTT command

echo "Body Of the Email"  | mutt -a "File_Attachment.csv" -s "Daily Report for $(date)"  -c [email protected] [email protected] -y
  1. -c email cc list
  2. -s subject list
  3. -y to send the mail

How to force Chrome's script debugger to reload javascript?

It seems as the Chrome debugger loads source files into memory and wont let them go despite of browser cache updates, i.e. it has its own cache apart from the browser cache that is not in sync. At least, this is the case when working with source mapped files (I am debugging typescript sources). After successfully refreshing browser cache and validating that by browsing directly to the source file, you download the updated file, but as soon as you reopen the file in the debugger it will keep returning the old file no matter the version from the ordinary browser cache. Very anoying indeed.

I would consider this a bug in chrome. I use version Version 46.0.2490.71 m.

The only thing that helps, is restarting chrome (close down all chrome browsers).

Read from a gzip file in python

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','r') as fin:        
    for line in fin:        
        print('got line', line)

How do I set <table> border width with CSS?

You need to add border-style like this:

<table style="border:1px solid black">

or like this:

<table style="border-width:1px;border-color:black;border-style:solid;">

How to distinguish mouse "click" and "drag"

You could do this:

_x000D_
_x000D_
var div = document.getElementById("div");
div.addEventListener("mousedown", function() {
  window.addEventListener("mousemove", drag);
  window.addEventListener("mouseup", lift);
  var didDrag = false;
  function drag() {
    //when the person drags their mouse while holding the mouse button down
    didDrag = true;
    div.innerHTML = "drag"
  }
  function lift() {
    //when the person lifts mouse
    if (!didDrag) {
      //if the person didn't drag
      div.innerHTML = "click";
    } else div.innerHTML = "drag";
    //delete event listeners so that it doesn't keep saying drag
    window.removeEventListener("mousemove", drag)
    window.removeEventListener("mouseup", this)
  }
})
_x000D_
body {
  outline: none;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica, sans-serif;
  overflow: hidden;
}
#div {
  /* calculating -5px for each side of border in case border-box doesn't work */
  width: calc(100vw - 10px);
  height: calc(100vh - 10px);
  border: 5px solid orange;
  background-color: yellow;
  font-weight: 700;
  display: grid;
  place-items: center;
  user-select: none;
  cursor: pointer;
  padding: 0;
  margin: 0;
}
_x000D_
<html>
  <body>
    <div id="div">Click me or drag me.</div>
  </body>
</html>
_x000D_
_x000D_
_x000D_

VBA collection: list of keys

I don't thinks that possible with a vanilla collection without storing the key values in an independent array.

The easiest alternative to do this is to add a reference to the Microsoft Scripting Runtime & use a more capable Dictionary instead:

Dim dict As Dictionary
Set dict = New Dictionary

dict.Add "key1", "value1"
dict.Add "key2", "value2"

Dim key As Variant
For Each key In dict.Keys
    Debug.Print "Key: " & key, "Value: " & dict.Item(key)
Next

Create autoincrement key in Java DB using NetBeans IDE

It's not possible right now, on Netbeans 7.0.1 . The GUI tool to create columns on a tables is very limited and does not exist a plugin that offer that feature.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

I stumbled upon a simple solution for this in Java8 (non-Android) using the ZoneDateTime class. There may be other classes that implement the TemporalAccessor interface that work, but I haven't found them. This won't work with standard Date, DateTime, LocalDateTime, and Calender classes as far as I can tell.

    ZoneOffset myOffset = ZonedDateTime.now().getOffset();
    ZoneOffset myOffset2 = ZoneOffset.from(ZonedDateTime.now());
    log.info("ZoneOffset is " + myOffset.getId());  // should print "+HH:MM"
    log.info("ZoneOffset2 is " + myOffset2.getId());  // should print "+HH:MM"

The nice thing about this solution is that it avoids a lot of modulo math, string generation, and parsing.

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

Change image size via parent div

I am doing this way:

<div class="card-logo">
    <img height="100%" width="100%" src="http://someimage.jpg">
</div>

and CSS:

.card-logo {
    width: 20%;
}

I prefer this way, as if I need to upscale - I can use 150% as well

What is the ultimate postal code and zip regex?

The unicode CLDR contains the postal code regex for each country. (158 regex's in total!)

Google also has a web service with per-country address formatting information, including postal codes, here - http://i18napis.appspot.com/address (I found that link via http://unicode.org/review/pri180/ )

Edit

Here a copy of postalCodeData.xml regex :

"GB", "GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}"
"JE", "JE\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}"
"GG", "GY\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}"
"IM", "IM\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}"
"US", "\d{5}([ \-]\d{4})?"
"CA", "[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ ]?\d[ABCEGHJ-NPRSTV-Z]\d"
"DE", "\d{5}"
"JP", "\d{3}-\d{4}"
"FR", "\d{2}[ ]?\d{3}"
"AU", "\d{4}"
"IT", "\d{5}"
"CH", "\d{4}"
"AT", "\d{4}"
"ES", "\d{5}"
"NL", "\d{4}[ ]?[A-Z]{2}"
"BE", "\d{4}"
"DK", "\d{4}"
"SE", "\d{3}[ ]?\d{2}"
"NO", "\d{4}"
"BR", "\d{5}[\-]?\d{3}"
"PT", "\d{4}([\-]\d{3})?"
"FI", "\d{5}"
"AX", "22\d{3}"
"KR", "\d{3}[\-]\d{3}"
"CN", "\d{6}"
"TW", "\d{3}(\d{2})?"
"SG", "\d{6}"
"DZ", "\d{5}"
"AD", "AD\d{3}"
"AR", "([A-HJ-NP-Z])?\d{4}([A-Z]{3})?"
"AM", "(37)?\d{4}"
"AZ", "\d{4}"
"BH", "((1[0-2]|[2-9])\d{2})?"
"BD", "\d{4}"
"BB", "(BB\d{5})?"
"BY", "\d{6}"
"BM", "[A-Z]{2}[ ]?[A-Z0-9]{2}"
"BA", "\d{5}"
"IO", "BBND 1ZZ"
"BN", "[A-Z]{2}[ ]?\d{4}"
"BG", "\d{4}"
"KH", "\d{5}"
"CV", "\d{4}"
"CL", "\d{7}"
"CR", "\d{4,5}|\d{3}-\d{4}"
"HR", "\d{5}"
"CY", "\d{4}"
"CZ", "\d{3}[ ]?\d{2}"
"DO", "\d{5}"
"EC", "([A-Z]\d{4}[A-Z]|(?:[A-Z]{2})?\d{6})?"
"EG", "\d{5}"
"EE", "\d{5}"
"FO", "\d{3}"
"GE", "\d{4}"
"GR", "\d{3}[ ]?\d{2}"
"GL", "39\d{2}"
"GT", "\d{5}"
"HT", "\d{4}"
"HN", "(?:\d{5})?"
"HU", "\d{4}"
"IS", "\d{3}"
"IN", "\d{6}"
"ID", "\d{5}"
"IL", "\d{5}"
"JO", "\d{5}"
"KZ", "\d{6}"
"KE", "\d{5}"
"KW", "\d{5}"
"LA", "\d{5}"
"LV", "\d{4}"
"LB", "(\d{4}([ ]?\d{4})?)?"
"LI", "(948[5-9])|(949[0-7])"
"LT", "\d{5}"
"LU", "\d{4}"
"MK", "\d{4}"
"MY", "\d{5}"
"MV", "\d{5}"
"MT", "[A-Z]{3}[ ]?\d{2,4}"
"MU", "(\d{3}[A-Z]{2}\d{3})?"
"MX", "\d{5}"
"MD", "\d{4}"
"MC", "980\d{2}"
"MA", "\d{5}"
"NP", "\d{5}"
"NZ", "\d{4}"
"NI", "((\d{4}-)?\d{3}-\d{3}(-\d{1})?)?"
"NG", "(\d{6})?"
"OM", "(PC )?\d{3}"
"PK", "\d{5}"
"PY", "\d{4}"
"PH", "\d{4}"
"PL", "\d{2}-\d{3}"
"PR", "00[679]\d{2}([ \-]\d{4})?"
"RO", "\d{6}"
"RU", "\d{6}"
"SM", "4789\d"
"SA", "\d{5}"
"SN", "\d{5}"
"SK", "\d{3}[ ]?\d{2}"
"SI", "\d{4}"
"ZA", "\d{4}"
"LK", "\d{5}"
"TJ", "\d{6}"
"TH", "\d{5}"
"TN", "\d{4}"
"TR", "\d{5}"
"TM", "\d{6}"
"UA", "\d{5}"
"UY", "\d{5}"
"UZ", "\d{6}"
"VA", "00120"
"VE", "\d{4}"
"ZM", "\d{5}"
"AS", "96799"
"CC", "6799"
"CK", "\d{4}"
"RS", "\d{6}"
"ME", "8\d{4}"
"CS", "\d{5}"
"YU", "\d{5}"
"CX", "6798"
"ET", "\d{4}"
"FK", "FIQQ 1ZZ"
"NF", "2899"
"FM", "(9694[1-4])([ \-]\d{4})?"
"GF", "9[78]3\d{2}"
"GN", "\d{3}"
"GP", "9[78][01]\d{2}"
"GS", "SIQQ 1ZZ"
"GU", "969[123]\d([ \-]\d{4})?"
"GW", "\d{4}"
"HM", "\d{4}"
"IQ", "\d{5}"
"KG", "\d{6}"
"LR", "\d{4}"
"LS", "\d{3}"
"MG", "\d{3}"
"MH", "969[67]\d([ \-]\d{4})?"
"MN", "\d{6}"
"MP", "9695[012]([ \-]\d{4})?"
"MQ", "9[78]2\d{2}"
"NC", "988\d{2}"
"NE", "\d{4}"
"VI", "008(([0-4]\d)|(5[01]))([ \-]\d{4})?"
"PF", "987\d{2}"
"PG", "\d{3}"
"PM", "9[78]5\d{2}"
"PN", "PCRN 1ZZ"
"PW", "96940"
"RE", "9[78]4\d{2}"
"SH", "(ASCN|STHL) 1ZZ"
"SJ", "\d{4}"
"SO", "\d{5}"
"SZ", "[HLMS]\d{3}"
"TC", "TKCA 1ZZ"
"WF", "986\d{2}"
"XK", "\d{5}"
"YT", "976\d{2}"

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

I wrote the following to print a list of results to standard out based on available charsets. Note that it also tells you what line fails from a 0 based line number in case you are troubleshooting what character is causing issues.

public static void testCharset(String fileName) {
    SortedMap<String, Charset> charsets = Charset.availableCharsets();
    for (String k : charsets.keySet()) {
        int line = 0;
        boolean success = true;
        try (BufferedReader b = Files.newBufferedReader(Paths.get(fileName),charsets.get(k))) {
            while (b.ready()) {
                b.readLine();
                line++;
            }
        } catch (IOException e) {
            success = false;
            System.out.println(k+" failed on line "+line);
        }
        if (success) 
            System.out.println("*************************  Successs "+k);
    }
}

Pandas groupby: How to get a union of strings

You could try this:

df.groupby('A').agg({'B':'sum','C':'-'.join})

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

HTML Text with tags to formatted text in an Excel cell

I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below

  1. First enable developer mode in Excel: Link
  2. Select the Developer Tab > Visual Basic
  3. Click View > Code
  4. Paste the code below updating the lines that require cell references to be correct.
  5. Click the Green Run Arrow or press F5
Sub Sample()
    Dim Ie As Object
    Set Ie = CreateObject("InternetExplorer.Application")
    With Ie
        .Visible = False
        .Navigate "about:blank"
        .document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
             'update to the cell that contains HTML you want converted
        .ExecWB 17, 0
             'Select all contents in browser
        .ExecWB 12, 2
             'Copy them
        ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
             'update to cell you want converted HTML pasted in
        .Quit
    End With
End Sub

How do I delete all messages from a single queue using the CLI?

I guess its late but for others reference, this can be done with pika

import pika
host_ip = #host ip
channel = pika.BlockingConnection(pika.ConnectionParameters(host_ip,
                                                        5672,
                                                        "/",
credentials=pika.PlainCredentials("username","pwd"))).channel()
print "deleting queue..", channel.queue_delete(queue=queue_name)

Change value of input and submit form in JavaScript

You could do something like this instead:

<form name="myform" action="action.php" onsubmit="DoSubmit();">
    <input type="hidden" name="myinput" value="0" />
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" />
</form>

And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:

function DoSubmit(){
  document.myform.myinput.value = '1';
  return true;
}

I'd also be wary of using onclick events on a submit button; the order of events isn't immediately obvious, and your callback won't get called if the user submits by, for example, hitting return in a textbox.

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

Correct use for angular-translate in controllers

EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.


The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.

So, you can do that yourself:

.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.$watch(
        function() { return $filter('translate')('HELLO_WORLD'); },
        function(newval) { $scope.pageTitle = newval; }
    );
});

However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...

Check for column name in a SqlDataReader object

Here the solution from Jasmine in one line... (one more, tho simple!):

reader.GetSchemaTable().Select("ColumnName='MyCol'").Length > 0;

How to set Android camera orientation properly?

check out this solution

 public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

  1. Check if compatible Mysql for your PHP version is correctly installed. (eg. mysql-installer-community-5.5.40.1.msi for PHP 5.2.10, apache 2.2 and phpMyAdmin 3.5.2)
  2. In your php\php.ini set your loadable php extensions path (eg. extension_dir = "C:\php\ext") (https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)
  3. (In your php\php.ini) check if extension=php_mysqli.dll is uncommented (https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)
  4. Set your php folder (eg."C:\php") and php\ext folder (eg."C:\php\ext") as your runtime environment variable path (https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)
  5. Restart apache service (https://drive.google.com/open?id=1kJF5kxPSrj3LdKWJcJTos9ecKFx0ORAW)

How to maintain page scroll position after a jquery event is carried out?

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

Android - Activity vs FragmentActivity?

ianhanniballake is right. You can get all the functionality of Activity from FragmentActivity. In fact, FragmentActivity has more functionality.

Using FragmentActivity you can easily build tab and swap format. For each tab you can use different Fragment (Fragments are reusable). So for any FragmentActivity you can reuse the same Fragment.

Still you can use Activity for single pages like list down something and edit element of the list in next page.

Also remember to use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach a android.support.v4.app.Fragment to an android.app.Activity, as this will cause an exception to be thrown.

How to get subarray from array?

_x000D_
_x000D_
const array_one = [11, 22, 33, 44, 55];_x000D_
const start = 1;_x000D_
const end = array_one.length - 1;_x000D_
const array_2 = array_one.slice(start, end);_x000D_
console.log(array_2);
_x000D_
_x000D_
_x000D_

Dealing with commas in a CSV file

First, let's ask ourselves, "Why do we feel the need to handle commas differently for CSV files?"

For me, the answer is, "Because when I export data into a CSV file, the commas in a field disappear and my field gets separated into multiple fields where the commas appear in the original data." (That it because the comma is the CSV field separator character.)

Depending on your situation, semi colons may also be used as CSV field separators.

Given my requirements, I can use a character, e.g., single low-9 quotation mark, that looks like a comma.

So, here's how you can do it in Go:

// Replace special CSV characters with single low-9 quotation mark
func Scrub(a interface{}) string {
    s := fmt.Sprint(a)
    s = strings.Replace(s, ",", "‚", -1)
    s = strings.Replace(s, ";", "‚", -1)
    return s
}

The second comma looking character in the Replace function is decimal 8218.

Be aware that if you have clients that may have ascii-only text readers that this decima 8218 character will not look like a comma. If this is your case, then I'd recommend surrounding the field with the comma (or semicolon) with double quotes per RFC 4128: https://tools.ietf.org/html/rfc4180

Convert a string date into datetime in Oracle

You can use a cast to char to see the date results

_x000D_
_x000D_
 select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
_x000D_
_x000D_

Inserting a Python datetime.datetime object into MySQL

Try using now.date() to get a Date object rather than a DateTime.

If that doesn't work, then converting that to a string should work:

now = datetime.datetime(2009,5,5)
str_now = now.date().isoformat()
cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now))

SQLRecoverableException: I/O Exception: Connection reset

add java security in your run command

java -jar -Djava.security.egd="file:///dev/urandom" yourjarfilename.jar

How can I remove file extension from a website address?

For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccessbut this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.

I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css,js and phpfiles even more like images or whatever you have.

Cr8Router - Simple PHP Router

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

How to find the kafka version in linux

There are several methods to find kafka version

Method 1 simple:-

ps -ef|grep kafka

it will displays all running kafka clients in the console... Ex:- /usr/hdp/current/kafka-broker/bin/../libs/kafka-clients-0.10.0.2.5.3.0-37.jar we are using 0.10.0.2.5.3.0-37 version of kafka

Method 2:- go to

cd /usr/hdp/current/kafka-broker/libs
ll |grep kafka

Ex:- kafka_2.10-0.10.0.2.5.3.0-37.jar kafka-clients-0.10.0.2.5.3.0-37.jar

same result as method 1 we can find the version of kafka using in kafka libs.

How to Round to the nearest whole number in C#

You can use Math.Round as others have suggested (recommended), or you could add 0.5 and cast to an int (which will drop the decimal part).

double value = 1.1;
int roundedValue = (int)(value + 0.5); // equals 1

double value2 = 1.5;
int roundedValue2 = (int)(value2 + 0.5); // equals 2

How to redirect verbose garbage collection output to a file?

To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.

A brief excerpt:

The flag -XX:+PrintGC (or the alias -verbose:gc) activates the “simple” GC logging mode

By default the GC log is written to stdout. With -Xloggc:<file> we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC and -XX:+PrintGCTimeStamps as well.

If we use -XX:+PrintGCDetails instead of -XX:+PrintGC, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.

With -XX:+PrintGCTimeStamps a timestamp reflecting the real time passed in seconds since JVM start is added to every line.

If we specify -XX:+PrintGCDateStamps each line starts with the absolute date and time.

Git: list only "untracked" files (also, custom commands)

I know its an old question, but in terms of listing untracked files I thought I would add another one which also lists untracked folders:

You can used the git clean operation with -n (dry run) to show you which files it will remove (including the .gitignore files) by:

git clean -xdn

This has the advantage of showing all files and all folders that are not tracked. Parameters:

  • x - Shows all untracked files (including ignored by git and others, like build output etc...)
  • d - show untracked directories
  • n - and most importantly! - dryrun, i.e. don't actually delete anything, just use the clean mechanism to display the results.

It can be a little bit unsafe to do it like this incase you forget the -n. So I usually alias it in git config.

Case insensitive 'in'

I think you have to write some extra code. For example:

if 'MICHAEL89' in map(lambda name: name.upper(), USERNAMES):
   ...

In this case we are forming a new list with all entries in USERNAMES converted to upper case and then comparing against this new list.

Update

As @viraptor says, it is even better to use a generator instead of map. See @Nathon's answer.

How do I view the SSIS packages in SQL Server Management Studio?

When you start SSMS, it allows you to choose a Server Type and Server Name. In the server type dropdown, choose "Integration Services" and connect to the server.

Then you'll be able to see what packages are in the db.

CSS: Set Div height to 100% - Pixels

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
  background-color:gray;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Alternative to itoa() for converting integer to string C++?

Try sprintf():

char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"

sprintf() is like printf() but outputs to a string.

Also, as Parappa mentioned in the comments, you might want to use snprintf() to stop a buffer overflow from occuring (where the number you're converting doesn't fit the size of your string.) It works like this:

snprintf(str, sizeof(str), "%d", num);

How do I push a new local branch to a remote Git repository and track it too?

For GitLab version prior to 1.7, use:

git checkout -b name_branch

(name_branch, ex: master)

To push it to the remote repository, do:

git push -u origin name_new_branch

(name_new_branch, example: feature)

Twitter bootstrap float div right

You can assign the class name like text-center, left or right. The text will align accordingly to these class name. You don't need to make extra class name separately. These classes are built in BootStrap 3 and bootstrap 4.

Bootstrap 3

v3 Text Alignment Docs

<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>

Bootstrap 4

v4 Text Alignment Docs

<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>

How to define the css :hover state in a jQuery selector?

You can try this:

$(".myclass").mouseover(function() {
    $(this).find(" > div").css("background-color","red");
}).mouseout(function() {
    $(this).find(" > div").css("background-color","transparent");
});

DEMO

Download files from SFTP with SSH.NET library

While the example works, its not the correct way to handle the streams...

You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...

       public void DownloadAll()
    {
        string host = @"sftp.domain.com";
        string username = "myusername";
        string password = "mypassword";

        string remoteDirectory = "/RemotePath/";
        string localDirectory = @"C:\LocalDriveFolder\Downloaded\";

        using (var sftp = new SftpClient(host, username, password))
        {
            sftp.Connect();
            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {
                string remoteFileName = file.Name;
                if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))

                    using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
                    { 
                        sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                    }
            }

        }
    }

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

Sublime Text 3 how to change the font size of the file sidebar?

If you want to change the font size then simply follow. Preferences-> Default File preferences.

After clicking on default file preferences, new Tab will open with name of Default File Type.Sublime-options

After find Font properties like font Courier New 12 we (recommend to use CTRL+F) then change size of it. Click save and instantly you can see the changes.

How to encrypt/decrypt data in php?

It took me quite a while to figure out, how to not get a false when using openssl_decrypt() and get encrypt and decrypt working.

    // cryptographic key of a binary string 16 bytes long (because AES-128 has a key size of 16 bytes)
    $encryption_key = '58adf8c78efef9570c447295008e2e6e'; // example
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($plaintext, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
    $encrypted = $encrypted . ':' . base64_encode($iv);

    // decrypt to get again $plaintext
    $parts = explode(':', $encrypted);
    $decrypted = openssl_decrypt($parts[0], 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, base64_decode($parts[1])); 

If you want to pass the encrypted string via a URL, you need to urlencode the string:

    $encrypted = urlencode($encrypted);

To better understand what is going on, read:

To generate 16 bytes long keys you can use:

    $bytes = openssl_random_pseudo_bytes(16);
    $hex = bin2hex($bytes);

To see error messages of openssl you can use: echo openssl_error_string();

Hope that helps.

Good font for code presentations?

I'm personally very fond of Inconsolata

Adding a leading zero to some values in column in MySQL

I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):

UPDATE table SET phone_num = concat('0', phone_num) 

I just concated 0 in front of the phone_num.

Why is HttpClient BaseAddress not working?

Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.

If base URI contains non-empty path, merge procedure discards it's last part (after last /). Relevant section:

5.2.3. Merge Paths

The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:

  • If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise

  • return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).

If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.

How do I select an entire row which has the largest ID in the table?

SELECT * 
FROM table 
WHERE id = (SELECT MAX(id) FROM TABLE)

How can I remove the extension of a filename in a shell script?

Using POSIX's built-in only:

#!/usr/bin/env sh
path=this.path/with.dots/in.path.name/filename.tar.gz

# Get the basedir without external command
# by stripping out shortest trailing match of / followed by anything
dirname=${path%/*}

# Get the basename without external command
# by stripping out longest leading match of anything followed by /
basename=${path##*/}

# Strip uptmost trailing extension only
# by stripping out shortest trailing match of dot followed by anything
oneextless=${basename%.*}; echo "$noext" 

# Strip all extensions
# by stripping out longest trailing match of dot followed by anything
noext=${basename%%.*}; echo "$noext"

# Printout demo
printf %s\\n "$path" "$dirname" "$basename" "$oneextless" "$noext"

Printout demo:

this.path/with.dots/in.path.name/filename.tar.gz
this.path/with.dots/in.path.name
filename.tar.gz
filename.tar
filename

Laravel: PDOException: could not find driver

Solution 1:

1. php -v

Output: PHP 7.3.11-1+ubuntu16.04.1+deb.sury.org+1 (cli)

2. sudo apt-get install php7.3-mysql

Solution 2:

Check your DB credentials like DB Name, DB User, DB Password

jQuery AJAX Call to PHP Script with JSON Return

Use parseJSON jquery method to covert string into object

var objData = jQuery.parseJSON(data);

Now you can write code

$('#result').html(objData .status +':' + objData .message);

How to compare two dates in php

compare the result of maketime() for each of the time

Why is there no xrange function in Python3?

One way to fix up your python2 code is:

import sys

if sys.version_info >= (3, 0):
    def xrange(*args, **kwargs):
        return iter(range(*args, **kwargs))

How to show "Done" button on iPhone number pad

The trick I've seen used is to make a custom transparent button the size of the whole view and then in its click method, have the text field resign first responder. So the user can click anywhere outside of the field to dismiss the keypad.

Inheritance and Overriding __init__ in python

Yes, you must call __init__ for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

How can I get nth element from a list?

I know it's an old post ... but it may be useful for someone ... in a "functional" way ...

import Data.List

safeIndex :: [a] -> Int -> Maybe a
safeIndex xs i 
        | (i> -1) && (length xs > i) = Just (xs!!i)
        | otherwise = Nothing

How do I call an Angular 2 pipe with multiple arguments?

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

Here is the Pipe being called in an *ngFor directive,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

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

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

GitHub Example: Fork a working copy of this example here

*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

Happy Coding :-)

Ansible: Set variable to file content

You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.

Capitalize words in string

Jquery or Javascipt doesn't provide a built-in method to achieve this.

CSS test transform (text-transform:capitalize;) doesn't really capitalize the string's data but shows a capitalized rendering on the screen.

If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>

var capitalizeString = function (word) {    
    word = word.toLowerCase();
    if (word.indexOf(" ") != -1) { // passed param contains 1 + words
        word = word.replace(/\s/g, "--");
        var result = $.camelCase("-" + word);
        return result.replace(/-/g, " ");
    } else {
    return $.camelCase("-" + word);
    }
}