Programs & Examples On #Mysql error 1062

ERROR 1062 (23000): Duplicate entry '%s' for key '%s'

#1062 - Duplicate entry for key 'PRIMARY'

You need to remove shares as your PRIMARY KEY OR UNIQUE_KEY

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

The main reason why the error has been generated is because there is already an existing value of 1 for the column ID in which you define it as PRIMARY KEY (values are unique) in the table you are inserting.

Why not set the column ID as AUTO_INCREMENT?

CREATE  TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `viale` VARCHAR(45) NULL ,
   .....

and when you are inserting record, you can now skip the column ID

INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...) 
VALUES ('Viale Cogel ', '120', ...)

MySQL duplicate entry error even though there is no duplicate entry

Less common cases, but keep in mind that according to DOC https://dev.mysql.com/doc/refman/5.6/en/innodb-online-ddl-limitations.html

When running an online ALTER TABLE operation, the thread that runs the ALTER TABLE operation will apply an “online log” of DML operations that were run concurrently on the same table from other connection threads. When the DML operations are applied, it is possible to encounter a duplicate key entry error (ERROR 1062 (23000): Duplicate entry), even if the duplicate entry is only temporary and would be reverted by a later entry in the “online log”. This is similar to the idea of a foreign key constraint check in InnoDB in which constraints must hold during a transaction.

The entity type <type> is not part of the model for the current context

For me the issue was that I had not included the Entity Class within my db set inside the context for entity framework.

public DbSet<ModelName> ModelName { get; set; }

Get current time in hours and minutes

With bash version >= 4.2:

printf "%(%H:%M)T\n"

or

printf -v foo "%(%H:%M)T\n"
echo "$foo"

See: man bash

Entity framework left join

For 2 and more left joins (left joining creatorUser and initiatorUser )

IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
                                             join candidateUser in authContext.AuthUsers
                                             on r.CandidateId equals candidateUser.Id
                                             join creatorUser in authContext.AuthUsers
                                             on r.CreatorId equals creatorUser.Id into gj
                                             from x in gj.DefaultIfEmpty()
                                             join initiatorUser in authContext.AuthUsers
                                             on r.InitiatorId equals initiatorUser.Id into init
                                             from x1 in init.DefaultIfEmpty()

                                             where candidateUser.UserName.Equals(candidateUsername)
                                             select new CreateRequestModel
                                             {
                                                 UserName = candidateUser.UserName,
                                                 CreatorId = (x == null ? String.Empty : x.UserName),
                                                 InitiatorId = (x1 == null ? String.Empty : x1.UserName),
                                                 CandidateId = candidateUser.UserName
                                             };

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

How to save and load numpy.array() data properly?

The most reliable way I have found to do this is to use np.savetxt with np.loadtxt and not np.fromfile which is better suited to binary files written with tofile. The np.fromfile and np.tofile methods write and read binary files whereas np.savetxt writes a text file. So, for example:

a = np.array([1, 2, 3, 4])
np.savetxt('test1.txt', a, fmt='%d')
b = np.loadtxt('test1.txt', dtype=int)
a == b
# array([ True,  True,  True,  True], dtype=bool)

Or:

a.tofile('test2.dat')
c = np.fromfile('test2.dat', dtype=int)
c == a
# array([ True,  True,  True,  True], dtype=bool)

I use the former method even if it is slower and creates bigger files (sometimes): the binary format can be platform dependent (for example, the file format depends on the endianness of your system).

There is a platform independent format for NumPy arrays, which can be saved and read with np.save and np.load:

np.save('test3.npy', a)    # .npy extension is added if not given
d = np.load('test3.npy')
a == d
# array([ True,  True,  True,  True], dtype=bool)

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

Build android release apk on Phonegap 3.x CLI

Following up to @steven-anderson you can also configure passwords inside the ant.properties, so the process can be fully automated

so if you put in platform\android\ant.properties the following

key.store=../../yourCertificate.jks
key.store.password=notSoSecretPassword
key.alias=userAlias
key.alias.password=notSoSecretPassword

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

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

I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0

I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps

HTTP Range header

It's a syntactically valid request, but not a satisfiable request. If you look further in that section you see:

If a syntactically valid byte-range-set includes at least one byte- range-spec whose first-byte-pos is less than the current length of the entity-body, or at least one suffix-byte-range-spec with a non- zero suffix-length, then the byte-range-set is satisfiable. Otherwise, the byte-range-set is unsatisfiable. If the byte-range-set is unsatisfiable, the server SHOULD return a response with a status of 416 (Requested range not satisfiable). Otherwise, the server SHOULD return a response with a status of 206 (Partial Content) containing the satisfiable ranges of the entity-body.

So I think in your example, the server should return a 416 since it's not a valid byte range for that file.

How to add parameters to a HTTP GET request in Android?

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","value1");

String query = URLEncodedUtils.format(params, "utf-8");

URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null
HttpGet httpGet = new HttpGet(url);

URI javadoc

Note: url = new URI(...) is buggy

How to use radio buttons in ReactJS?

Just an idea here: when it comes to radio inputs in React, I usually render all of them in a different way that was mentionned in the previous answers.

If this could help anyone who needs to render plenty of radio buttons:

_x000D_
_x000D_
import React from "react"_x000D_
import ReactDOM from "react-dom"_x000D_
_x000D_
// This Component should obviously be a class if you want it to work ;)_x000D_
_x000D_
const RadioInputs = (props) => {_x000D_
  /*_x000D_
    [[Label, associated value], ...]_x000D_
  */_x000D_
  _x000D_
  const inputs = [["Male", "M"], ["Female", "F"], ["Other", "O"]]_x000D_
  _x000D_
  return (_x000D_
    <div>_x000D_
      {_x000D_
        inputs.map(([text, value], i) => (_x000D_
   <div key={ i }>_x000D_
     <input type="radio"_x000D_
              checked={ this.state.gender === value } _x000D_
       onChange={ /* You'll need an event function here */ } _x000D_
       value={ value } /> _x000D_
         { text }_x000D_
          </div>_x000D_
        ))_x000D_
      }_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <RadioInputs />,_x000D_
  document.getElementById("root")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Session 'app': Error Installing APK

Edit:

In newer Android Studio versions you can re-sync the project using this button:

enter image description here

For older versions:

Open Gradle window (on the right side in Android Studio) and click on the refresh button.

However it is not a 100% sure fix.

Solutions for other cases:

Open terminal window and type "adb kill-server", then type "adb start-server". Usually after a few hours of inactivity, adb used to disconnect the device. (If you don't have the sdk/platform-tools in the PATH environment variable, then you should open a terminal in that folder)

One tip if these solutions don't help you: If you open the Event Log window in the right bottom corner of Android Studio, you can see a detailed error message.

Other edge case If you see this error: INSTALL_FAILED_INVALID_APK:... signatures are inconsistent. Then unfortunately a gradle refresh isn't enough, you have to go to Build -> Clean Project and then Run again.

Issue with Android emulator If you want to deploy the APK to an Android Emulator and you see the "Error installing APK" message, your emulator may be frozen and need restart.

How to send HTML email using linux command line

I was struggling with similar problem (with mail) in one of my git's post_receive hooks and finally I found out, that sendmail actually works better for that kind of things, especially if you know a bit of how e-mails are constructed (and it seems like you know). I know this answer comes very late, but maybe it will be of some use to others too. I made use of heredoc operator and use of the feature, that it expands variables, so it can also run inlined scripts. Just check this out (bash script):

#!/bin/bash
recipients=(
    '[email protected]'
    '[email protected]'
#   '[email protected]'
);
sender='[email protected]';
subject='Oh, who really cares, seriously...';
sendmail -t <<-MAIL
    From: ${sender}
    `for r in "${recipients[@]}"; do echo "To: ${r}"; done;`
    Subject: ${subject}
    Content-Type: text/html; charset=UTF-8

    <html><head><meta charset="UTF-8"/></head>
    <body><p>Ladies and gents, here comes the report!</p>
    <pre>`mysql -u ***** -p***** -H -e "SELECT * FROM users LIMIT 20"`</pre>
    </body></html>
MAIL

Note of backticks in the MAIL part to generate some output and remember, that <<- operator strips only tabs (not spaces) from the beginning of lines, so in that case copy-paste will not work (you need to replace indentation with proper tabs). Or use << operator and make no indentation at all. Hope this will help someone. Of course you can use backticks outside o MAIL part and save the output into some variable, that you can later use in the MAIL part — matter of taste and readability. And I know, #!/bin/bash does not always work on every system.

How do I run a program from command prompt as a different user and as an admin

See here: https://superuser.com/questions/42537/is-there-any-sudo-command-for-windows

According to that the command looks like this for admin:

 runas /noprofile /user:Administrator cmd

Reset textbox value in javascript

In Javascript :

document.getElementById('searchField').value = '';

In jQuery :

$('#searchField').val('');

That should do it

How to refresh a page with jQuery by passing a parameter to URL

I would use REGEX with .replace like this:

window.location.href = window.location.href.replace( /[\?#].*|$/, "?single" );

In a URL, should spaces be encoded using %20 or +?

You can use either - which means most people opt for "+" as it's more human readable.

Getting Spring Application Context

There are many way to get application context in Spring application. Those are given bellow:

  1. Via ApplicationContextAware:

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class AppContextProvider implements ApplicationContextAware {
    
    private ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    }
    

Here setApplicationContext(ApplicationContext applicationContext) method you will get the applicationContext

ApplicationContextAware:

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. Implementing this interface makes sense for example when an object requires access to a set of collaborating beans.

  1. Via Autowired:

    @Autowired
    private ApplicationContext applicationContext;
    

Here @Autowired keyword will provide the applicationContext. Autowired has some problem. It will create problem during unit-testing.

how to filter out a null value from spark dataframe

From the hint from Michael Kopaniov, below works

df.where(df("id").isNotNull).show

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

To get the insert ignore logic you can do something like below. I found simply inserting from a select statement of literal values worked best, then you can mask out the duplicate keys with a NOT EXISTS clause. To get the update on duplicate logic I suspect a pl/pgsql loop would be necessary.

INSERT INTO manager.vin_manufacturer
(SELECT * FROM( VALUES
  ('935',' Citroën Brazil','Citroën'),
  ('ABC', 'Toyota', 'Toyota'),
  ('ZOM',' OM','OM')
  ) as tmp (vin_manufacturer_id, manufacturer_desc, make_desc)
  WHERE NOT EXISTS (
    --ignore anything that has already been inserted
    SELECT 1 FROM manager.vin_manufacturer m where m.vin_manufacturer_id = tmp.vin_manufacturer_id)
)

Add CSS3 transition expand/collapse

http://jsfiddle.net/Bq6eK/215/

I did not modify your code for this solution, I wrote my own instead. My solution isn't quite what you asked for, but maybe you could build on it with existing knowledge. I commented the code as well so you know what exactly I'm doing with the changes.

As a solution to "avoid setting the height in JavaScript", I just made 'maxHeight' a parameter in the JS function called toggleHeight. Now it can be set in the HTML for each div of class expandable.

I'll say this up front, I'm not super experienced with front-end languages, and there's an issue where I need to click the 'Show/hide' button twice initially before the animation starts. I suspect it's an issue with focus.

The other issue with my solution is that you can actually figure out what the hidden text is without pressing the show/hide button just by clicking in the div and dragging down, you can highlight the text that's not visible and paste it to a visible space.

My suggestion for a next step on top of what I've done is to make it so that the show/hide button changes dynamically. I think you can figure out how to do that with what you already seem to know about showing and hiding text with JS.

Setting up MySQL and importing dump within Dockerfile

The latest version of the official mysql docker image allows you to import data on startup. Here is my docker-compose.yml

data:
  build: docker/data/.
mysql:
  image: mysql
  ports:
    - "3307:3306"
  environment:
    MYSQL_ROOT_PASSWORD: 1234
  volumes:
    - ./docker/data:/docker-entrypoint-initdb.d
  volumes_from:
    - data

Here, I have my data-dump.sql under docker/data which is relative to the folder the docker-compose is running from. I am mounting that sql file into this directory /docker-entrypoint-initdb.d on the container.

If you are interested to see how this works, have a look at their docker-entrypoint.sh in GitHub. They have added this block to allow importing data

    echo
    for f in /docker-entrypoint-initdb.d/*; do
        case "$f" in
            *.sh)  echo "$0: running $f"; . "$f" ;;
            *.sql) echo "$0: running $f"; "${mysql[@]}" < "$f" && echo ;;
            *)     echo "$0: ignoring $f" ;;
        esac
        echo
    done

An additional note, if you want the data to be persisted even after the mysql container is stopped and removed, you need to have a separate data container as you see in the docker-compose.yml. The contents of the data container Dockerfile are very simple.

FROM n3ziniuka5/ubuntu-oracle-jdk:14.04-JDK8

VOLUME /var/lib/mysql

CMD ["true"]

The data container doesn't even have to be in start state for persistence.

JavaScript: replace last occurrence of text in a string

Simple solution would be to use substring method. Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method

str = str.substring(0, str.length - list[i].length) + "finish"

Options for HTML scraping?

I do a lot of advanced web scraping so wanted to have total control over my stack and understand the limitations. This webscraping library is the result.

Load a UIView from nib in Swift

  let bundle = Bundle(for: type(of: self))
   let views = bundle.loadNibNamed("template", owner: self, options: nil)
    self.view.addSubview(views?[0] as! UIView)

Given a class, see if instance has method (Ruby)

class Foo
 def self.fclass_method
 end
 def finstance_method
 end
end

foo_obj = Foo.new
foo_obj.class.methods(false)
=> [:fclass_method] 

foo_obj.class.instance_methods(false)
=> [:fclass_method] 

Hope this helps you!

Is it possible to set a number to NaN or infinity?

Is it possible to set a number to NaN or infinity?

Yes, in fact there are several ways. A few work without any imports, while others require import, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).

The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float:

+-------------------------------------------------------------------+
¦   result ¦ NaN          ¦ Infinity           ¦ -Infinity          ¦
¦ module   ¦              ¦                    ¦                    ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf")       ¦ -float("inf")      ¦
¦          ¦              ¦ float("infinity")  ¦ -float("infinity") ¦
¦          ¦              ¦ float("+inf")      ¦ float("-inf")      ¦
¦          ¦              ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math     ¦ math.nan     ¦ math.inf           ¦ -math.inf          ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath    ¦ cmath.nan    ¦ cmath.inf          ¦ -cmath.inf         ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy    ¦ numpy.nan    ¦ numpy.PINF         ¦ numpy.NINF         ¦
¦          ¦ numpy.NaN    ¦ numpy.inf          ¦ -numpy.inf         ¦
¦          ¦ numpy.NAN    ¦ numpy.infty        ¦ -numpy.infty       ¦
¦          ¦              ¦ numpy.Inf          ¦ -numpy.Inf         ¦
¦          ¦              ¦ numpy.Infinity     ¦ -numpy.Infinity    ¦
+-------------------------------------------------------------------+

A couple remarks to the table:

  • The float constructor is actually case-insensitive, so you can also use float("NaN") or float("InFiNiTy").
  • The cmath and numpy constants return plain Python float objects.
  • The numpy.NINF is actually the only constant I know of that doesn't require the -.
  • It is possible to create complex NaN and Infinity with complex and cmath:

    +------------------------------------------------------------------------------------------+
    ¦   result ¦ NaN+0j         ¦ 0+NaNj          ¦ Inf+0j              ¦ 0+Infj               ¦
    ¦ module   ¦                ¦                 ¦                     ¦                      ¦
    ¦----------+----------------+-----------------+---------------------+----------------------¦
    ¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf")      ¦ complex("infj")      ¦
    ¦          ¦                ¦                 ¦ complex("infinity") ¦ complex("infinityj") ¦
    +----------+----------------+-----------------+---------------------+----------------------¦
    ¦ cmath    ¦ cmath.nan ¹    ¦ cmath.nanj      ¦ cmath.inf ¹         ¦ cmath.infj           ¦
    +------------------------------------------------------------------------------------------+
    

    The options with ¹ return a plain float, not a complex.

is there any function to check whether a number is infinity or not?

Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import:

+--------------------------------------------------------------+
¦      for ¦ NaN         ¦ Infinity or    ¦ not NaN and        ¦
¦          ¦             ¦ -Infinity      ¦ not Infinity and   ¦
¦ module   ¦             ¦                ¦ not -Infinity      ¦
¦----------+-------------+----------------+--------------------¦
¦ math     ¦ math.isnan  ¦ math.isinf     ¦ math.isfinite      ¦
+----------+-------------+----------------+--------------------¦
¦ cmath    ¦ cmath.isnan ¦ cmath.isinf    ¦ cmath.isfinite     ¦
+----------+-------------+----------------+--------------------¦
¦ numpy    ¦ numpy.isnan ¦ numpy.isinf    ¦ numpy.isfinite     ¦
+--------------------------------------------------------------+

Again a couple of remarks:

  • The cmath and numpy functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.
  • The numpy functions also work for numpy arrays and everything that can be converted to one (like lists, tuple, etc.)
  • There are also functions that explicitly check for positive and negative infinity in NumPy: numpy.isposinf and numpy.isneginf.
  • Pandas offers two additional functions to check for NaN: pandas.isna and pandas.isnull (but not only NaN, it matches also None and NaT)
  • Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):

    def isnan(value):
        return value != value  # NaN is not equal to anything, not even itself
    
    infinity = float("infinity")
    
    def isinf(value):
        return abs(value) == infinity 
    
    def isfinite(value):
        return not (isnan(value) or isinf(value))
    

To summarize the expected results for these functions (assuming the input is a float):

+----------------------------------------------------------------------+
¦          input ¦ NaN   ¦ Infinity   ¦ -Infinity   ¦ something else   ¦
¦ function       ¦       ¦            ¦             ¦                  ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan          ¦ True  ¦ False      ¦ False       ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf          ¦ False ¦ True       ¦ True        ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite       ¦ False ¦ False      ¦ False       ¦ True             ¦
+----------------------------------------------------------------------+

Is it possible to set an element of an array to NaN in Python?

In a list it's no problem, you can always include NaN (or Infinity) there:

>>> [math.nan, math.inf, -math.inf, 1]  # python list
[nan, inf, -inf, 1]

However if you want to include it in an array (for example array.array or numpy.array) then the type of the array must be float or complex because otherwise it will try to downcast it to the arrays type!

>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan,  0.,  0.])

>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])

>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer

How to obtain a Thread id in Python?

You can get the ident of the current running thread. The ident could be reused for other threads, if the current thread ends.

When you crate an instance of Thread, a name is given implicit to the thread, which is the pattern: Thread-number

The name has no meaning and the name don't have to be unique. The ident of all running threads is unique.

import threading


def worker():
    print(threading.current_thread().name)
    print(threading.get_ident())


threading.Thread(target=worker).start()
threading.Thread(target=worker, name='foo').start()

The function threading.current_thread() returns the current running thread. This object holds the whole information of the thread.

Best way to simulate "group by" from bash?

Solution ( group by like mysql)

grep -ioh "facebook\|xing\|linkedin\|googleplus" access-log.txt | sort | uniq -c | sort -n

Result

3249  googleplus
4211 linkedin
5212 xing
7928 facebook

How do I determine if a port is open on a Windows server?

On Windows Server you can use

netstat -an | where{$_.Contains("Yourport")}

What values for checked and selected are false?

Actually, the HTML 4.01 spec says that these attributes do not require values. I haven't personally encountered a situation where providing a value rendered these controls as unselected.

Here are the respective links to the spec document for selected and checked.

Edit: Firebug renders the checkbox as checked regardless of any values I put in quotes for the checked attribute (including just typing "checked" with no values whatsoever), and IE 8's Developer Tools forces checked="checked". I'm not sure if any similar tools exist for other browsers that might alter the rendered state of a checkbox, however.

Understanding timedelta

why do I have to pass seconds = uptime to timedelta

Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int is superfluous as they could also accept floats.

and why does the string casting works so nicely that I get HH:MM:SS ?

It's not the typecasting that formats, is the internal __str__ method of the object. In fact you will achieve the same result if you write:

print datetime.timedelta(seconds=int(uptime))

PHP mySQL - Insert new record into table with auto-increment on primary key

This is phpMyAdmin method.

$query = "INSERT INTO myTable
         (mtb_i_idautoinc, mtb_s_string1, mtb_s_string2) 
         VALUES
         (NULL, 'Jagodina', '35000')";

How do I check if the user is pressing a key?

Try this:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

        char ch = event.getKeyChar();

        System.out.println(event.getKeyChar());

    }

}

python location on mac osx

which python3 simply result in a path in which the interpreter settles down.

Android: Remove all the previous activities from the back stack

One possible solution what I can suggest you is to add android:launchMode="singleTop" in the manifest for my ProfileActivity. and when log out is clicked u can logoff starting again you LoginActivity. on logout u can call this.

Intent in = new Intent(Profile.this,Login.class);
                in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(in);
                finish();

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Manifest Merger failed with multiple errors in Android Studio

for the past few days I was also going through the same issue. But after, a lot of research I finally found a solution for this.
In order to solve this issue, what you need to do is:
1. Check if your project's build.gradle file and the module's build.gradle file contain same versions of all dependencies.
2. Make sure, your project's compileSdkVersion, buildToolsVersion, minSdkVersion and targetSdkVersion matches the one in the modules or libraries that you have added into the project.

compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
    applicationId "com.example.appname"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 22
    versionName "2.0.3"

}

Hope, this helps.

Replace Both Double and Single Quotes in Javascript String

You don't need to escape it inside. You can use the | character to delimit searches.

"\"foo\"\'bar\'".replace(/("|')/g, "")

Regex to remove all special characters from string?

If you don't want to use Regex then another option is to use

char.IsLetterOrDigit

You can use this to loop through each char of the string and only return if true.

Regular expression for not allowing spaces in the input field

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

C# Form.Close vs Form.Dispose

What I have just experiment with VS diagnostic tools is I called this.Close() then formclosing event triggered. Then When I call this.Dispose() at the end in Formclosing event where I dispose many other objects in it, it cleans everything much much smoother.

How to select all columns, except one column in pandas?

When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:

df.loc[:, df.columns != 'b']

          a         c         d
0  0.561196  0.013768  0.772827
1  0.882641  0.615396  0.075381
2  0.368824  0.651378  0.397203
3  0.788730  0.568099  0.869127

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

MySQL - Selecting data from multiple tables all with same structure but different data

Your original attempt to span both tables creates an implicit JOIN. This is frowned upon by most experienced SQL programmers because it separates the tables to be combined with the condition of how.

The UNION is a good solution for the tables as they are, but there should be no reason they can't be put into the one table with decent indexing. I've seen adding the correct index to a large table increase query speed by three orders of magnitude.

How do we use runOnUiThread in Android?

Just wrap it as a function, then call this function from your background thread.

public void debugMsg(String msg) {
    final String str = msg;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mInfo.setText(str);
        }
    });
}

Why doesn't java.util.Set have get(int index)?

Please note only 2 basic data structure can be accessed via index.

  • Array data structure can be accessed via index with O(1) time complexity to achieve get(int index) operation.
  • LinkedList data structure can also be accessed via index, but with O(n) time complexity to achieve get(int index) operation.

In Java, ArrayList is implemented using Array data structure.

While Set data structure usually can be implemented via HashTable/HashMap or BalancedTree data structure, for fast detecting whether an element exists and add non-existing element, usually a well implemented Set can achieve O(1) time complexity contains operation. In Java, HashSet is the most common used implementation of Set, it is implemented by calling HashMap API, and HashMap is implemented using separate chaining with linked lists (a combination of Array and LinkedList).

Since Set can be implemented via different data structure, there is no get(int index) method for it.

Detect when browser receives file download

If Xmlhttprequest with blob is not an option then you can open your file in new window and check if eny elements get populated in that window body with interval.

_x000D_
_x000D_
var form = document.getElementById("frmDownlaod");_x000D_
 form.setAttribute("action","downoad/url");_x000D_
 form.setAttribute("target","downlaod");_x000D_
 var exportwindow = window.open("", "downlaod", "width=800,height=600,resizable=yes");_x000D_
 form.submit();_x000D_
_x000D_
var responseInterval = setInterval(function(){_x000D_
 var winBody = exportwindow.document.body_x000D_
 if(winBody.hasChildNodes()) // or 'downoad/url' === exportwindow.document.location.href_x000D_
 {_x000D_
  clearInterval(responseInterval);_x000D_
  // do your work_x000D_
  // if there is error page configured your application for failed requests, check for those dom elemets _x000D_
 }_x000D_
}, 1000)_x000D_
//Better if you specify maximun no of intervals
_x000D_
_x000D_
_x000D_

How to identify platform/compiler from preprocessor macros?

Here's what I use:

#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
    // Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
    // Unix
#elif __linux__
    // linux
#elif __APPLE__
    // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif

EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

Find nearest value in numpy array

Here is a version with scipy for @Ari Onasafari, answer "to find the nearest vector in an array of vectors"

In [1]: from scipy import spatial

In [2]: import numpy as np

In [3]: A = np.random.random((10,2))*100

In [4]: A
Out[4]:
array([[ 68.83402637,  38.07632221],
       [ 76.84704074,  24.9395109 ],
       [ 16.26715795,  98.52763827],
       [ 70.99411985,  67.31740151],
       [ 71.72452181,  24.13516764],
       [ 17.22707611,  20.65425362],
       [ 43.85122458,  21.50624882],
       [ 76.71987125,  44.95031274],
       [ 63.77341073,  78.87417774],
       [  8.45828909,  30.18426696]])

In [5]: pt = [6, 30]  # <-- the point to find

In [6]: A[spatial.KDTree(A).query(pt)[1]] # <-- the nearest point 
Out[6]: array([  8.45828909,  30.18426696])

#how it works!
In [7]: distance,index = spatial.KDTree(A).query(pt)

In [8]: distance # <-- The distances to the nearest neighbors
Out[8]: 2.4651855048258393

In [9]: index # <-- The locations of the neighbors
Out[9]: 9

#then 
In [10]: A[index]
Out[10]: array([  8.45828909,  30.18426696])

c++ exception : throwing std::string

In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw std::string("it's the end of the world!");
  }
}

void Foo:Caller(){
  try{
    this->Bar();// should throw
  }catch(std::string& caught){ // not quite sure the syntax is ok here...
    std::cout<<"Got "<<caught<<std::endl;
  }
}
  • You should throw anonymous temporaries so the compiler deals with the object lifetime of whatever you're throwing - if you throw something new-ed off the heap, someone else needs to free the thing.
  • You should catch references to prevent object slicing

.

See Meyer's "Effective C++ - 3rd edition" for details or visit https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference

deleted object would be re-saved by cascade (remove deleted object from associations)

I also ran into this error on a badly designed database, where there was a Person table with a one2many relationship with a Code table and an Organization table with a one2many relationship with the same Code table. The Code could apply to both an Organization and Or a Person depending on situation. Both the Person object and the Organization object were set to Cascade=All delete orphans.

What became of this overloaded use of the Code table however was that neither the Person nor the Organization could cascade delete because there was always another collection that had a reference to it. So no matter how it was deleted in the Java code out of whatever referencing collections or objects the delete would fail. The only way to get it to work was to delete it out of the collection I was trying to save then delete it out of the Code table directly then save the collection. That way there was no reference to it.

How can I read user input from the console?

I think there are some compiler errors.

  • Writeline should be WriteLine (capital 'L')
  • missing semicolon at the end of a line

        double a, b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
        a = double.Parse(Console.ReadLine());
        b = a * Math.PI; // Missing colon!
        Console.WriteLine("Sonuç " + b);
    

Find string between two substrings

s[len(start):-len(end)]

How to escape comma and double quote at same time for CSV file?

If you're using CSVWriter. Check that you don't have the option

.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)

When I removed it the comma was showing as expected and not treating it as new column

SelectSingleNode returning null for known good xml node path using XPath

The rule to keep in mind is: if your document specifies a namespace, you MUST use an XmlNamespaceManager in your call to SelectNodes() or SelectSingleNode(). That's a good thing.

See the article Advantages of namespaces . Jon Skeet does a great job in his answer showing how to use XmlNamespaceManager. (This answer should really just be a comment on that answer, but I don't quite have enough Rep Points to comment.)

Find the most popular element in int[] array

Seems like you are looking for the Mode value (Statistical Mode) , have a look at Apache's Docs for Statistical functions.

How to enumerate a range of numbers starting at 1

Ok, I feel a bit stupid here... what's the reason not to just do it with something like
[(a+1,b) for (a,b) in enumerate(r)] ? If you won't function, no problem either:

>>> r = range(2000, 2005)
>>> [(a+1,b) for (a,b) in enumerate(r)]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

>>> enumerate1 = lambda r:((a+1,b) for (a,b) in enumerate(r)) 

>>> list(enumerate1(range(2000,2005)))   # note - generator just like original enumerate()
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

Parser Error when deploy ASP.NET application

I know i am too late to answer but it could help others and save time.

Following might be other solutions.

Solution 1: See Creating a Virtual Directory for Your Application for detailed instructions on creating a virtual directory for your application.

Solution 2: Your application’s Bin folder is missing or the application’s DLL file is missing. See Copying Your Application Files to a Production Server for detailed instructions.

Solution 3: You may have deployed to the web root folder, but have not changed some of the settings in the Web.config file. See Deploying to web root for detailed instructions.

In my case Solution 2 works, while deploying to server some DLL's from bin directory has not been uploaded to server successfully. I have re-upload all DLL's again and it works!!

Here is the reference link to solve asp.net parser error.

How to specify the actual x axis values to plot as x axis ticks in R

You'll find the answer to your question in the help page for ?axis.

Here is one of the help page examples, modified with your data:

Option 1: use xaxp to define the axis labels

plot(x,y, xaxt="n")
axis(1, xaxp=c(10, 200, 19), las=2)

Option 2: Use at and seq() to define the labels:

plot(x,y, xaxt="n")
axis(1, at = seq(10, 200, by = 10), las=2)

Both these options yield the same graphic:

enter image description here


PS. Since you have a large number of labels, you'll have to use additional arguments to get the text to fit in the plot. I use las to rotate the labels.

Case vs If Else If: Which is more efficient?

The debugger is making it simpler, because you don't want to step through the actual code that the compiler creates.

If the switch contains more than five items, it's implemented using a lookup table or hash table, otherwise it's implemeneted using an if..else.

See the closely related question is “else if” faster than “switch() case” ?.

Other languages than C# will of course implement it more or less differently, but a switch is generally more efficient.

Sending GET request with Authentication headers using restTemplate

You're not missing anything. RestTemplate#exchange(..) is the appropriate method to use to set request headers.

Here's an example (with POST, but just change that to GET and use the entity you want).

Here's another example.

Note that with a GET, your request entity doesn't have to contain anything (unless your API expects it, but that would go against the HTTP spec). It can be an empty String.

Refresh page after form submitting

  //insert this php code, at the end after your closing html tag. 

  <?php
  //setting connection to database
  $con = mysqli_connect("localhost","your-username","your-
  passowrd","your-dbname");

  if(isset($_POST['submit_button'])){

     $txt_area = $_POST['update']; 

       $Our_query= "INSERT INTO your-table-name (field1name, field2name) 
                  VALUES ('abc','def')"; // values should match data 
                 //  type to field names

        $insert_query = mysqli_query($con, $Our_query);

        if($insert_query){
            echo "<script>window.open('form.php','_self') </script>"; 
             // supposing form.php is where you have created this form

          }



   } //if statement close         
  ?>

Hope this helps.

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

Make <body> fill entire screen?

Try using viewport (vh, vm) units of measure at the body level

html, body { margin: 0; padding: 0; } body { min-height: 100vh; }

Use vh units for horizontal margins, paddings, and borders on the body and subtract them from the min-height value.

I've had bizarre results using vh,vm units on elements within the body, especially when re-sizing.

Jquery, set value of td in a table?

Try the code below :

$('#detailInfo').html('your value')

How to sign in kubernetes dashboard?

All the previous answers are good to me. But a straight forward answer on my side would come from https://github.com/kubernetes/dashboard/wiki/Creating-sample-user#bearer-token. Just use kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}'). You will have many values for some keys (Name, Namespace, Labels, ..., token). The most important is the token that corresponds to your name. copy that token and paste it in the token box. Hope this helps.

How to fix committing to the wrong Git branch?

To elaborate on this answer, in case you have multiple commits to move from, e.g. develop to new_branch:

git checkout develop # You're probably there already
git reflog # Find LAST_GOOD, FIRST_NEW, LAST_NEW hashes
git checkout new_branch
git cherry-pick FIRST_NEW^..LAST_NEW # ^.. includes FIRST_NEW
git reflog # Confirm that your commits are safely home in their new branch!
git checkout develop
git reset --hard LAST_GOOD # develop is now back where it started

What does "subject" mean in certificate?

Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.

As an example on an SSL certificate for a web site the subject would be the domain name of the web site.

How to open the Chrome Developer Tools in a new window?

If you need to open the DevTools press ctrl-shift-i.

If the DevTools window is already opened you can use the ctrl-shift-d shortcut; it switches the window into a detached mode.

For example in my case the electron application window (Chrome) is really small.

enter image description here

It's not possible to use any other suggestions except the ctrl-shift-d shortcut

Check for special characters in string

Your regexp use ^ and $ so it tries to match the entire string. And if you want only a boolean as the result, use test instead of match.

var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;

if(format.test(string)){
  return true;
} else {
  return false;
}

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

Using Position Relative/Absolute within a TD?

This is because according to CSS 2.1, the effect of position: relative on table elements is undefined. Illustrative of this, position: relative has the desired effect on Chrome 13, but not on Firefox 4. Your solution here is to add a div around your content and put the position: relative on that div instead of the td. The following illustrates the results you get with the position: relative (1) on a div good), (2) on a td(no good), and finally (3) on a div inside a td (good again).

On Firefox 4

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="position:relative;">_x000D_
        <span style="position:absolute; left:150px;">_x000D_
          Absolute span_x000D_
        </span>_x000D_
        Relative div_x000D_
      </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

How can I convert JSON to CSV?

I am assuming that your JSON file will decode into a list of dictionaries. First we need a function which will flatten the JSON objects:

def flattenjson(b, delim):
    val = {}
    for i in b.keys():
        if isinstance(b[i], dict):
            get = flattenjson(b[i], delim)
            for j in get.keys():
                val[i + delim + j] = get[j]
        else:
            val[i] = b[i]
            
    return val

The result of running this snippet on your JSON object:

flattenjson({
    "pk": 22, 
    "model": "auth.permission", 
    "fields": {
      "codename": "add_message", 
      "name": "Can add message", 
      "content_type": 8
    }
  }, "__")

is

{
    "pk": 22, 
    "model": "auth.permission", 
    "fields__codename": "add_message", 
    "fields__name": "Can add message", 
    "fields__content_type": 8
}

After applying this function to each dict in the input array of JSON objects:

input = map(lambda x: flattenjson( x, "__" ), input)

and finding the relevant column names:

columns = [x for row in input for x in row.keys()]
columns = list(set(columns))

it's not hard to run this through the csv module:

with open(fname, 'wb') as out_file:
    csv_w = csv.writer(out_file)
    csv_w.writerow(columns)

    for i_r in input:
        csv_w.writerow(map(lambda x: i_r.get(x, ""), columns))

I hope this helps!

How to store images in mysql database using php

I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.

HTML CODE

<input type="file" name="imageUpload" id="imageUpload">

PHP CODE

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

CODE TO DISPLAY THE IMAGE

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

How to find row number of a value in R code

As of R 3.3.0, one may use startsWith() as a faster alternative to grepl():

which(startsWith(mydata_2$height_seca1, 1578))

mysql query: SELECT DISTINCT column1, GROUP BY column2

Somehow your requirement sounds a bit contradictory ..

group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

What do you think should happen if two people (names) worked from the same IP within the time period specified?


Did you try this?

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday AND time <$today 
GROUP BY name,ip

Python "\n" tag extra line

Add , after the print "\n" line

so that it reads print "\n",

What are some alternatives to ReSharper?

Keep in mind that with Visual Studio 2010 you may not need/want any addon. A lot of the ReSharper features were added into the Visual Studio 2010 core features. ReSharper, CodeRush, etc. have other features above and beyond Visual Studio for sure, but see what's been added vs. what you need. It could be that the core install takes care of what you are interested in now.

I personally use ReSharper 5 still as it has many uses, for me. What each coder finds most important though varies widely. You'll have to test each for yourself, but luckily all the alternatives have trial periods as well.

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

How do I choose the URL for my Spring Boot webapp?

The server.contextPath or server.context-path works if

in pom.xml

  1. packing should be war not jar
  2. Add following dependencies

    <dependency>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Tomcat/TC server -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
     </dependency>
    

    In eclipse, right click on project --> Run as --> Spring Boot App.

How to use php serialize() and unserialize()

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

Java JDBC connection status

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

How do I install an R package from source?

If you have the file locally, then use install.packages() and set the repos=NULL:

install.packages(path_to_file, repos = NULL, type="source")

Where path_to_file would represent the full path and file name:

  • On Windows it will look something like this: "C:\\RJSONIO_0.2-3.tar.gz".
  • On UNIX it will look like this: "/home/blah/RJSONIO_0.2-3.tar.gz".

Zsh: Conda/Pip installs command not found

You need to fix the spacing and quotes:

export PATH ="/Users/Dz/anaconda/bin:$PATH"

Instead use

export PATH="/Users/Dz/anaconda/bin":$PATH

(413) Request Entity Too Large | uploadReadAheadSize

I was receiving this error message, even though I had the max settings set within the binding of my WCF service config file:

<basicHttpBinding>
        <binding name="NewBinding1"
                 receiveTimeout="01:00:00"
                 sendTimeout="01:00:00"
                 maxBufferSize="2000000000"
                 maxReceivedMessageSize="2000000000">

                 <readerQuotas maxDepth="2000000000"
                      maxStringContentLength="2000000000"
                      maxArrayLength="2000000000" 
                      maxBytesPerRead="2000000000" 
                      maxNameTableCharCount="2000000000" />
        </binding>
</basicHttpBinding>

It seemed as though these binding settings weren't being applied, thus the following error message:

IIS7 - (413) Request Entity Too Large when connecting to the service.

The Problem

I realised that the name="" attribute within the <service> tag of the web.config is not a free text field, as I thought it was. It is the fully qualified name of an implementation of a service contract as mentioned within this documentation page.

If that doesn't match, then the binding settings won't be applied!

<services>
  <!-- The namespace appears in the 'name' attribute -->
  <service name="Your.Namespace.ConcreteClassName">
    <endpoint address="http://localhost/YourService.svc"
      binding="basicHttpBinding" bindingConfiguration="NewBinding1"
      contract="Your.Namespace.IConcreteClassName" />
  </service>
</services>

I hope that saves someone some pain...

What is the best way to delete a component with CLI

Angular 10 now I am using. After manually deleting all files and references then I re-run "ng serve", it worked.

How to convert float to varchar in SQL Server

Useful topic thanks.

If you want like me remove leadings zero you can use that :

DECLARE @MyFloat [float];
SET @MyFloat = 1000109360.050;
SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(STR(@MyFloat, 38, 16), '0', ' '))), ' ', '0'),'.',' ')),' ',',')

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

Create list or arrays in Windows Batch

@echo off

set array=

setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set nl=^&echo(

set array=auto blue ^!nl!^
  bycicle green ^!nl!^
  buggy   red

echo convert the String in indexed arrays

set /a index=0

for /F "tokens=1,2,3*" %%a in ( 'echo(!array!' ) do (

 echo(vehicle[!index!]=%%a color[!index!]=%%b 
 set vehicle[!index!]=%%a
 set color[!index!]=%%b
 set /a index=!index!+1   

)

echo use the arrays

echo(%vehicle[1]% %color[1]%
echo oder

set index=1
echo(!vehicle[%index%]! !color[%index%]!

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

What is use of c_str function In c++

In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string> header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str() function.

for example

// a string to a C-style string conversion//

const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;

And the output will be,

Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str 
Operation: strlen(cstr1)
The length of C-style string str1 = 17

Transposing a 1D NumPy array

For 1D arrays:

a = np.array([1, 2, 3, 4])
a = a.reshape((-1, 1)) # <--- THIS IS IT

print a
array([[1],
       [2],
       [3],
       [4]])

Once you understand that -1 here means "as many rows as needed", I find this to be the most readable way of "transposing" an array. If your array is of higher dimensionality simply use a.T.

How to force a checkbox and text on the same line?

http://jsbin.com/etozop/2/edit

put a div wrapper with WIDTH :

  <p><fieldset style="width:60px;">
   <div style="border:solid 1px red;width:80px;">
    <input type="checkbox" id="a">
    <label for="a">a</label>
    <input type="checkbox" id="b">

    <label for="b">b</label>
   </div>

    <input type="checkbox" id="c">
    <label for="c">c</label>
</fieldset></p>

a name could be " john winston ono lennon" which is very long... so what do you want to do? (youll never know the length)... you could make a function that wraps after x chars like : "john winston o...."

What is a MIME type?

I couldn't possibly explain it better than wikipedia does: http://en.wikipedia.org/wiki/MIME_type

In addition to e-mail applications, Web browsers also support various MIME types. This enables the browser to display or output files that are not in HTML format.

IOW, it helps the browser (or content consumer, because it may not just be a browser) determine what content they are about to consume; this means a browser may be able to make a decision on the correct plugin to use to display content, or a media player may be able to load up the correct codec or plugin.

VBoxManage: error: Failed to create the host-only adapter

My solution:

Make sure you have the following files under System32:

vboxnetadp.sys

vboxnetflt.sys

You can download them from here:

http://www.sysfilesdownload.com/V/VBoxNetFltsys.html

http://www.sysfilesdownload.com/U/VBoxNetAdp.sys.html

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

Clear image on picturebox

You need the following:

pictbox.Image = null;
pictbox.update();

IIS7 Cache-Control

The F5 Refresh has the semantic of "please reload the current HTML AND its direct dependancies". Hence you should expect to see any imgs, css and js resource directly referenced by the HTML also being refetched. Of course a 304 is an acceptable response to this but F5 refresh implies that the browser will make the request rather than rely on fresh cache content.

Instead try simply navigating somewhere else and then navigating back.

You can force the refresh, past a 304, by holding ctrl while pressing f5 in most browsers.

How to fetch the row count for all tables in a SQL SERVER database

SQL Server 2005 or later gives quite a nice report showing table sizes - including row counts etc. It's in Standard Reports - and it is Disc Usage by Table.

Programmatically, there's a nice solution at: http://www.sqlservercentral.com/articles/T-SQL/67624/

How do I get the current date in JavaScript?

If you're looking for a lot more granular control over the date formats, I thoroughly recommend checking out date-FNS. Terrific library - much smaller than moment.js and it's function based approach make it much faster then other class based libraries. Provide large number of operations needed over dates.

https://date-fns.org/docs/Getting-Started

How to get min, seconds and milliseconds from datetime.now() in python?

This solution is very similar to that provided by @gdw2 , only that the string formatting is correctly done to match what you asked for - "Should be as compact as possible"

>>> import datetime
>>> a = datetime.datetime.now()
>>> "%s:%s.%s" % (a.minute, a.second, str(a.microsecond)[:2])
'31:45.57'

.NET DateTime to SqlDateTime Conversion

If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.

SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)

Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.

How to generate a number of most distinctive colors in R?

You can use the Polychrome package for this purpose. It just requires the number of colors and a few seedcolors. For example:

# install.packages("Polychrome")
library(Polychrome)

# create your own color palette based on `seedcolors`
P36 = createPalette(36,  c("#ff0000", "#00ff00", "#0000ff"))
swatch(P36)

You can learn more about this package at https://www.jstatsoft.org/article/view/v090c01.

Git: How to remove remote origin from Git repo

first will change push remote url

git remote set-url --push origin https://newurl

second will change fetch remote url

git remote set-url origin https://newurl

How do I put a clear button inside my HTML text input box like the iPhone does?

@Mahmoud Ali Kaseem

I have just changed some CSS to make it look different and added focus();

https://jsfiddle.net/xn9eogmx/81/

_x000D_
_x000D_
$('#clear').click(function() {_x000D_
  $('#input-outer input').val('');_x000D_
  $('#input-outer input').focus();_x000D_
});
_x000D_
body {_x000D_
  font-family: "Arial";_x000D_
  font-size: 14px;_x000D_
}_x000D_
#input-outer {_x000D_
  height: 2em;_x000D_
  width: 15em;_x000D_
  border: 1px #777 solid;_x000D_
  position: relative;_x000D_
  padding: 0px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
#input-outer input {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  border: 0px;_x000D_
  outline: none;_x000D_
  margin: 0 0 0 0px;_x000D_
  color: #666;_x000D_
  box-sizing: border-box;_x000D_
  padding: 5px;_x000D_
  padding-right: 35px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
#clear {_x000D_
  position: absolute;_x000D_
  float: right;_x000D_
  height: 2em;_x000D_
  width: 2em;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  background: #aaa;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
  border-radius: 0px 4px 4px 0px;_x000D_
}_x000D_
#clear:after {_x000D_
  content: "\274c";_x000D_
  position: absolute;_x000D_
  top: 4px;_x000D_
  right: 7px;_x000D_
}_x000D_
#clear:hover,_x000D_
#clear:focus {_x000D_
  background: #888;_x000D_
}_x000D_
#clear:active {_x000D_
  background: #666;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
  <input type="text">_x000D_
  <div id="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Writing string to a file on a new line every time

This is the solution that I came up with trying to solve this problem for myself in order to systematically produce \n's as separators. It writes using a list of strings where each string is one line of the file, however it seems that it may work for you as well. (Python 3.+)

#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
    line = 0
    lines = []
    while line < len(strList):
        lines.append(cheekyNew(line) + strList[line])
        line += 1
    file = open(file, "w")
    file.writelines(lines)
    file.close()

#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
    if line != 0:
        return "\n"
    return ""

Dynamic height for DIV

as prior ans remove the height attrib. if u want your expansion along with its min height then use min-height: 102px instead of height: 102px.

note ie 6 and min-height http://www.dustindiaz.com/min-height-fast-hack/

Argument of type 'X' is not assignable to parameter of type 'X'

This problem basically comes when your compiler gets failed to understand the difference between cast operator of the type string to Number.

you can use the Number object and pass your value to get the appropriate results for it by using Number(<<<<...Variable_Name......>>>>)

symfony 2 No route found for "GET /"

This work for me:

cache:clear --env=prod

Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

Assign output of a program to a variable using a MS batch file

assuming that your application's output is a numeric return code, you can do the following

application arg0 arg1
set VAR=%errorlevel%

Git copy changes from one branch to another

git checkout BranchB
git merge BranchA
git push origin BranchB

This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.

Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.

Make sure you are in the branch where you want to copy all the changes to. git merge will take the branch you specify and merge it with the branch you are currently in.

How to check if the request is an AJAX request with PHP

This function is using in yii framework for ajax call check.

public function isAjax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

What's the difference between ng-model and ng-bind

ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.

This directive executes at priority level 1.

Example Plunker

JAVASCRIPT

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • Providing validation behavior (i.e. required, number, email, url).
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) including animations.
  • Registering the control with its parent form.

ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

This directive executes at priority level 0.

Example Plunker

JAVASCRIPT

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind is responsible for:

  • Replacing the text content of the specified HTML element with the value of a given expression.

How to preventDefault on anchor tags?

The easiest solution I have found is this one :

<a href="#" ng-click="do(); $event.preventDefault()">Click</a>

Execute combine multiple Linux commands in one line

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

Class 'DOMDocument' not found

On fedora 26:

dnf install php-dom

Fixes it !

Convert timestamp to date in Oracle SQL

If you have milliseconds in the date string, you can use the following.

select TO_TIMESTAMP(SUBSTR('2020-09-10T09:37:28.378-07:00',1,23), 'YYYY-MM-DD"T"HH24:MI:SS:FF3')From Dual;

And then convert it to Date with:

select trunc(TO_TIMESTAMP(SUBSTR('2020-09-10T09:37:28.378-07:00',1,23), 'YYYY-MM-DD"T"HH24:MI:SS:FF3')) From Dual;

It worked for me, hope it will help you as well.

How to get value of a div using javascript

As I said in the comments, a <div> element does not have a value attribute. Although (very) bad, it can be accessed as:

console.log(document.getElementById('demo').getAttribute);

I suggest using HTML5 data-* attributes rather. Something like this:

<div id="demo" data-myValue="1">...</div>

in which case you could access it using:

element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

Scala vs. Groovy vs. Clojure

Obviously, the syntax are completely different (Groovy is closest to Java), but I suppose that is not what you are asking for.

If you are interested in using them to script a Java application, Scala is probably not a good choice, as there is no easy way to evaluate it from Java, whereas Groovy is especially suited for that purpose.

Convert number to varchar in SQL with formatting

Use the RIGHT function... e.g.

DECLARE @testnum TINYINT
SET @testnum = 3
PRINT RIGHT('00' + CONVERT(VARCHAR(2), @testnum), 2)

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

How to compare variables to undefined, if I don’t know whether they exist?

if (!obj) {
    // object (not class!) doesn't exist yet
}
else ...

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Take a screenshot via a Python script on Linux

for ubuntu this work for me, you can take a screenshot of select window with this:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk
from gi.repository import GdkPixbuf
import numpy as np
from Xlib.display import Display

#define the window name
window_name = 'Spotify'

#define xid of your select 'window'
def locate_window(stack,window):
    disp = Display()
    NET_WM_NAME = disp.intern_atom('_NET_WM_NAME')
    WM_NAME = disp.intern_atom('WM_NAME') 
    name= []
    for i, w in enumerate(stack):
        win_id =w.get_xid()
        window_obj = disp.create_resource_object('window', win_id)
        for atom in (NET_WM_NAME, WM_NAME):
            window_name=window_obj.get_full_property(atom, 0)
            name.append(window_name.value)
    for l in range(len(stack)):
        if(name[2*l]==window):
            return stack[l]

window = Gdk.get_default_root_window()
screen = window.get_screen()
stack = screen.get_window_stack()
myselectwindow = locate_window(stack,window_name)
img_pixbuf = Gdk.pixbuf_get_from_window(myselectwindow,*myselectwindow.get_geometry()) 

to transform pixbuf into array

def pixbuf_to_array(p):
    w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())
    assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB
    assert p.get_bits_per_sample() == 8
    if  p.get_has_alpha():
        assert c == 4
    else:
        assert c == 3
    assert r >= w * c
    a=np.frombuffer(p.get_pixels(),dtype=np.uint8)
    if a.shape[0] == w*c*h:
        return a.reshape( (h, w, c) )
    else:
        b=np.zeros((h,w*c),'uint8')
        for j in range(h):
            b[j,:]=a[r*j:r*j+w*c]
        return b.reshape( (h, w, c) )

beauty_print = pixbuf_to_array(img_pixbuf)

How to create <input type=“text”/> dynamically

  • Query and get the container DOM element

  • Create new element

  • Put new element to document Tree

//Query some Dib region you Created
let container=document.querySelector("#CalculationInfo .row .t-Form-itemWrapper");
let input = document.createElement("input");

//create new Element  for apex
input.setAttribute("type","text");
input.setAttribute("size","30");
containter.appendChild(input); // put it into the DOM

Sending an HTTP POST request on iOS

Sending an HTTP POST request on iOS (Objective c):

-(NSString *)postexample{

// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

//RESPONDE DATA 
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

For s: When used with printf functions, specifies a single-byte or multi-byte character string; when used with wprintf functions, specifies a wide-character string. Characters are displayed up to the first null character or until the precision value is reached.

For S: When used with printf functions, specifies a wide-character string; when used with wprintf functions, specifies a single-byte or multi-byte character string. Characters are displayed up to the first null character or until the precision value is reached.

In Unix-like platform, s and S have the same meaning as windows platform.

Reference: https://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx

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

While this isn't possible with the video itself, you could use a canvas to draw the frames of the video except for pixels in a color range or whatever. It would take some javascript and such of course. See Video Puzzle (apparently broken at the moment), Exploding Video, and Realtime Video -> ASCII

SQL Server - SELECT FROM stored procedure

You can cheat a little with OPENROWSET :

SELECT ...fieldlist...
FROM OPENROWSET('SQLNCLI', 'connection string', 'name of sp')
WHERE ...

This would still run the entire SP every time, of course.

Angular 2 Hover event

If you want to perform a hover like event on any HTML element, then you can do it like this.

HTML

 <div (mouseenter) ="mouseEnter('div a') "  (mouseleave) ="mouseLeave('div A')">
        <h2>Div A</h2>
 </div> 
 <div (mouseenter) ="mouseEnter('div b')"  (mouseleave) ="mouseLeave('div B')">
        <h2>Div B</h2>
 </div>

Component

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

@Component({
    moduleId: module.id,
    selector: 'basic-detail',
    templateUrl: 'basic.component.html',
})
export class BasicComponent{

   mouseEnter(div : string){
      console.log("mouse enter : " + div);
   }

   mouseLeave(div : string){
     console.log('mouse leave :' + div);
   }
}

You should use both mouseenter and mouseleave events inorder to implement fully functional hover events in angular 2.

Redirect from a view to another view

It's because your statement does not produce output.

Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

If you want to execute methods that don't directly produce output, you do:

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

This is also true for rendering partials like:

@{ Html.RenderPartial("_MyPartial"); }

What is the difference between dict.items() and dict.iteritems() in Python2?

dict.iteritems is gone in Python3.x So use iter(dict.items()) to get the same output and memory alocation

How to convert a Hibernate proxy to a real entity object

Since Hibernate ORM 5.2.10, you can do it likee this:

Object unproxiedEntity = Hibernate.unproxy(proxy);

Before Hibernate 5.2.10. the simplest way to do that was to use the unproxy method offered by Hibernate internal PersistenceContext implementation:

Object unproxiedEntity = ((SessionImplementor) session)
                         .getPersistenceContext()
                         .unproxy(proxy);

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Why use @PostConstruct?

  • because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies.

  • because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.

C++, What does the colon after a constructor mean?

It's called an initialization list. It initializes members before the body of the constructor executes.

Does Java have something like C#'s ref and out keywords?

java has no standard way of doing it. Most swaps will be made on the list that is packaged in the class. but there is an unofficial way to do it:

package Example;

import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;



 public class Test{


private static <T> void SetValue(T obj,T value){
    try {
        Field f = obj.getClass().getDeclaredField("value");
        f.setAccessible(true);
        f.set(obj,value);
        } catch (IllegalAccessException | IllegalArgumentException | 
            NoSuchFieldException | SecurityException ex) {
            Logger.getLogger(CautrucjavaCanBan.class.getName()).log(Level.SEVERE, 
       null, ex);
        }
}
private  static  void permutation(Integer a,Integer b){
    Integer tmp = new Integer(a);
    SetValue(a, b);
    SetValue(b, tmp);
}
 private  static  void permutation(String a,String b){
    char[] tmp = a.toCharArray();
    SetValue(a, b.toCharArray());
    SetValue(b, tmp);
}
public static void main(String[] args) {
    {
        Integer d = 9;
        Integer e = 8;
        HoanVi(d, e);
        System.out.println(d+" "+ e);
    }
    {
        String d = "tai nguyen";
        String e = "Thai nguyen";
        permutation(d, e);
        System.out.println(d+" "+ e);
    }
}

}

How to get the number of days of difference between two dates on mysql?

I prefer TIMESTAMPDIFF because you can easily change the unit if need be.

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

What does ON [PRIMARY] mean?

When you create a database in Microsoft SQL Server you can have multiple file groups, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.

See MSDN for the full syntax.

iPhone App Icons - Exact Radius?

If not considering stroke, the exact radius is actually 10px for 57x57 icon.

I get this info from iconreference.

How to compare two tables column by column in oracle

Using the minus operator was working but also it was taking more time to execute which was not acceptable. I have a similar kind of requirement for data migration and I used the NOT IN operator for that. The modified query is :

select * 
from A 
where (emp_id,emp_name) not in 
   (select emp_id,emp_name from B) 
   union all 
select * from B 
where (emp_id,emp_name) not in 
   (select emp_id,emp_name from A); 

This query executed fast. Also you can add any number of columns in the select query. Only catch is that both tables should have the exact same table structure for this to be executed.

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

How do I set the colour of a label (coloured text) in Java?

object.setForeground(Color.green);

*any colour you wish *object being declared earlier

Returning string from C function

I came across this thread while working on my understanding of Cython. My extension to the original question might be of use to others working at the C / Cython interface. So this is the extension of the original question: how do I return a string from a C function, making it available to Cython & thus to Python?

For those not familiar with it, Cython allows you to statically type Python code that you need to speed up. So the process is, enjoy writing Python :), find its a bit slow somewhere, profile it, calve off a function or two and cythonize them. Wow. Close to C speed (it compiles to C) Fixed. Yay. The other use is importing C functions or libraries into Python as done here.

This will print a string and return the same or another string to Python. There are 3 files, the c file c_hello.c, the cython file sayhello.pyx, and the cython setup file sayhello.pyx. When they are compiled using python setup.py build_ext --inplace they generate a shared library file that can be imported into python or ipython and the function sayhello.hello run.

c_hello.c

#include <stdio.h>

char *c_hello() {
  char *mystr = "Hello World!\n";
  return mystr;
  // return "this string";  // alterative
}

sayhello.pyx

cdef extern from "c_hello.c":
    cdef char* c_hello()

def hello():
    return c_hello()

setup.py

from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize


ext_modules = cythonize([Extension("sayhello", ["sayhello.pyx"])])


setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)

Newline in string attribute

When you need to do it in a string (eg: in your resources) you need to use xml:space="preserve" and the ampersand character codes:

<System:String x:Key="TwoLiner" xml:space="preserve">First line&#10;Second line</System:String>

Or literal newlines in the text:

<System:String x:Key="TwoLiner" xml:space="preserve">First line 
Second line</System:String>

Warning: if you write code like the second example, you have inserted either a newline, or a carriage return and newline, depending on the line endings your operating system and/or text editor use. For instance, if you write that and commit it to git from a linux systems, everything may seem fine -- but if someone clones it to Windows, git will convert your line endings to \r\n and depending on what your string is for ... you might break the world.

Just be aware of that when you're preserving whitespace. If you write something like this:

<System:String x:Key="TwoLiner" xml:space="preserve">
First line 
Second line 
</System:String>

You've actually added four line breaks, possibly four carriage-returns, and potentially trailing white space that's invisible...

How can I increase a scrollbar's width using CSS?

This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:

::-webkit-scrollbar {
    width: 2em;
    height: 2em
}
::-webkit-scrollbar-button {
    background: #ccc
}
::-webkit-scrollbar-track-piece {
    background: #888
}
::-webkit-scrollbar-thumb {
    background: #eee
}?

JSFiddle Demo


References:

How to define constants in Visual C# like #define in C?

static class Constants
{
    public const int MIN_LENGTH = 5;
    public const int MIN_WIDTH  = 5; 
    public const int MIN_HEIGHT = 6;
}

// elsewhere
public CBox()
{
    length = Constants.MIN_LENGTH; 
    width  = Constants.MIN_WIDTH; 
    height = Constants.MIN_HEIGHT;  
}

Get login username in java

inspired by @newacct's answer, a code that can be compiled in any platform:

String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";

if( osName.contains( "windows" ) ){
    className = "com.sun.security.auth.module.NTSystem";
    methodName = "getName";
}
else if( osName.contains( "linux" ) ){
    className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
    className = "com.sun.security.auth.module.SolarisSystem";
}

if( className != null ){
    Class<?> c = Class.forName( className );
    Method method = c.getDeclaredMethod( methodName );
    Object o = c.newInstance();
    System.out.println( method.invoke( o ) );
}

How do I generate sourcemaps when using babel and webpack?

In order to use source map, you should change devtool option value from true to the value which available in this list, for instance source-map

devtool: 'source-map'

devtool: 'source-map' - A SourceMap is emitted.

Best way to make a shell script daemon?

Here is the minimal change to the original proposal to create a valid daemon in Bourne shell (or Bash):

#!/bin/sh
if [ "$1" != "__forked__" ]; then
    setsid "$0" __forked__ "$@" &
    exit
else
    shift
fi

trap 'siguser1=true' SIGUSR1
trap 'echo "Clean up and exit"; kill $sleep_pid; exit' SIGTERM
exec > outfile
exec 2> errfile
exec 0< /dev/null

while true; do
    (sleep 30000000 &>/dev/null) &
    sleep_pid=$!
    wait
    kill $sleep_pid &>/dev/null
    if [ -n "$siguser1" ]; then
        siguser1=''
        echo "Wait was interrupted by SIGUSR1, do things here."
    fi
done

Explanation:

  • Line 2-7: A daemon must be forked so it doesn't have a parent. Using an artificial argument to prevent endless forking. "setsid" detaches from starting process and terminal.
  • Line 9: Our desired signal needs to be differentiated from other signals.
  • Line 10: Cleanup is required to get rid of dangling "sleep" processes.
  • Line 11-13: Redirect stdout, stderr and stdin of the script.
  • Line 16: sleep in the background
  • Line 18: wait waits for end of sleep, but gets interrupted by (some) signals.
  • Line 19: Kill sleep process, because that is still running when signal is caught.
  • Line 22: Do the work if SIGUSR1 has been caught.

Guess it does not get any simpler than that.

Convert HashBytes to VarChar

I have found the solution else where:

SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)

Multiple modals overlay

In my case the problem was caused by a browser extension that includes the bootstrap.js files where the show event handled twice and two modal-backdrop divs are added, but when closing the modal only one of them is removed.

Found that by adding a subtree modification breakpoint to the body element in chrome, and tracked adding the modal-backdrop divs.

C# password TextBox in a ASP.net website

//in aspx page

<asp:TextBox ID="password" runat="server" TextMode="Password" />

//in MVC cshtml

@Html.Password("password", "", new { id = "password", Textmode = "Password" })

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

How to do a logical OR operation for integer comparison in shell scripting?

This should work:

#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:

if (("$#" > 1))
 ...

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(varchar(10), '23/07/2009', 111)

log4j configuration via JVM argument(s)?

Relative Path is also ok:

java -Dlog4j.configuration=file:".\log4j.properties" -jar com.your-1.0-SNAPSHOT.jar

or

java -Dlog4j.configuration=file:".\log4j.xml" -jar com.your-1.0-SNAPSHOT.jar

How to remove all .svn directories from my application directories

Alternatively, if you want to export a copy without modifying the working copy, you can use rsync:

rsync -a --exclude .svn path/to/working/copy path/to/export

QByteArray to QString

You may find QString::fromUtf8() also useful.

For QByteArray input of "\010" and "\000",

QString::fromLocal8Bit(input, 1) returns "\010" and ""

QString::fromUtf8(input, 1) correctly returns "\010" and "\000".

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

How to escape % in String.Format?

This is a stronger regex replace that won't replace %% that are already doubled in the input.

str = str.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");

Adding JPanel to JFrame

public class Test{

Test2 test = new Test2();
JFrame frame = new JFrame();

Test(){
...
frame.setLayout(new BorderLayout());
frame.add(test, BorderLayout.CENTER);
...
}

//main
...
}

//public class Test2{
public class Test2 extends JPanel {

//JPanel test2 = new JPanel();

Test2(){
...
}

Error message "Strict standards: Only variables should be passed by reference"

$instance->find() returns a reference to a variable.

You get the report when you are trying to use this reference as an argument to a function, without storing it in a variable first.

This helps preventing memory leaks and will probably become an error in the next PHP versions.

Your second code block would throw an error if it wrote like (note the & in the function signature):

function &get_arr(){
    return array(1, 2);
}
$el = array_shift(get_arr());

So a quick (and not so nice) fix would be:

$el = array_shift($tmp = $instance->find(..));

Basically, you do an assignment to a temporary variable first and send the variable as an argument.

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Normally this error occurs when you invoke java by supplying the wrong arguments/options. In this case it should be the version option.

java -version

So to double check you can always do java -help, and see if the option exists. In this case, there is no option such as v.

3D Plotting from X, Y, Z Data, Excel or other Tools

I ended up using matplotlib :)

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
x = [1000,1000,1000,1000,1000,5000,5000,5000,5000,5000,10000,10000,10000,10000,10000]
y = [13,21,29,37,45,13,21,29,37,45,13,21,29,37,45]
z = [75.2,79.21,80.02,81.2,81.62,84.79,87.38,87.9,88.54,88.56,88.34,89.66,90.11,90.79,90.87]
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
plt.show()

How do I get the latest version of my code?

It sounds to me like you're having core.autocrlf-problems. core.autocrlf=true can give problems like the ones you describe on Windows if CRLF newlines were checked into the repository. Try disabling core.autocrlf for the repository, and perform a hard-reset.

Resize image proportionally with MaxHeight and MaxWidth constraints

Like this?

public static void Test()
{
    using (var image = Image.FromFile(@"c:\logo.png"))
    using (var newImage = ScaleImage(image, 300, 400))
    {
        newImage.Save(@"c:\test.png", ImageFormat.Png);
    }
}

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);

    using (var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);

    return newImage;
}

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

VB.NET: how to prevent user input in a ComboBox

this is the most simple way but it works for me with a ComboBox1 name

SOLUTION on 3 Basic STEPS:

step 1.

Declare a variable at the beginning of your form which will hold the original text value of the ComboBox. Example:

     Dim xCurrentTextValue as string

step 2.

Create the event combobox1 key down and Assign to xCurrentTextValue variable the current text of the combobox if any key diferrent than "ENTER" is pressed the combobox text value keeps the original text value

Example:

Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyDown

    xCurrentTextValue = ComboBox1.Text

    If e.KeyCode <> Keys.Enter Then
        Me.ComboBox1.Text = xCmbItem
    End If

End Sub

step 3.

Validate the when the combo text is changed if len(xcurrenttextvalue)> 0 or is different than nothing then the combobox1 takes the xcurrenttextvalue variable value

Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
    If Len(xCurrentTextValue) > 0 Then
        Me.ComboBox1.Text = xCurrentTextValue

    End If
End Sub

========================================================== that's it,

Originally I only tried the step number 2, but I have problems when you press the DEL key and DOWN arrow key, also for some reason it didn't validate the keydown event unless I display any message box


!Sorry, this is a correction on step number 2, I forgot to change the variable xCmbItem to xCurrentTextValue, xCmbItem it was used for my personal use

THIS IS THE CORRECT CODE

xCurrentTextValue = ComboBox1.Text

If e.KeyCode <> Keys.Enter Then
    Me.ComboBox1.Text = xCurrentTextValue
End If

How to properly URL encode a string in PHP?

You can use URL Encoding Functions PHP has the

rawurlencode() 

function

ASP has the

Server.URLEncode() 

function

In JavaScript you can use the

encodeURIComponent() 

function.

'Incomplete final line' warning when trying to read a .csv file into R

To fix this issue through R itself, I just used read.xlsx(..) instead of a read.csv(). Works like a charm!! You do not even have to rename. Renaming an xlsx into to csv is not a viable solution.

Regular Expressions: Is there an AND operator?

Use a non-consuming regular expression.

The typical (i.e. Perl/Java) notation is:

(?=expr)

This means "match expr but after that continue matching at the original match-point."

You can do as many of these as you want, and this will be an "and." Example:

(?=match this expression)(?=match this too)(?=oh, and this)

You can even add capture groups inside the non-consuming expressions if you need to save some of the data therein.

Set Background color programmatically

If you save color code in the colors.xml which is under the values folder,then you should call the following:

root.setBackgroundColor(getResources().getColor(R.color.name));

name means you declare in the <color/> tag.

./configure : /bin/sh^M : bad interpreter

Thanks to pwc101's comment on this post, this command worked in Kali Linux .

sed -i s/{ctrl+v}{ctrl+m}// {filename}

Make sure you replace the bits in brackets, {}. I.e. {ctrl+m} means press Ctrl key and the M key together.

Set inputType for an EditText Programmatically?

Try adding this to the EditText/TextView tag in your layout

android:password="true"

Edit: I just re-read your post, perhaps you need to do this after construction. I don't see why your snippet wouldn't work.

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

How to create duplicate table with new name in SQL Server 2008

  SELECT * INTO newtable FROM oldtable where 1=2

Where 1=2 is used when you need to copy the complete structure of a table without copying the data.

 SELECT * INTO newtable FROM oldtable 

To create a table with data you can use this statement.

How to create the most compact mapping n ? isprime(n) up to a limit N?

I compared the efficiency of the most popular suggestions to determine if a number is prime. I used python 3.6 on ubuntu 17.10; I tested with numbers up to 100.000 (you can test with bigger numbers using my code below).

This first plot compares the functions (which are explained further down in my answer), showing that the last functions do not grow as fast as the first one when increasing the numbers.

plot1

And in the second plot we can see that in case of prime numbers the time grows steadily, but non-prime numbers do not grow so fast in time (because most of them can be eliminated early on).

plot2

Here are the functions I used:

  1. this answer and this answer suggested a construct using all():

    def is_prime_1(n):
        return n > 1 and all(n % i for i in range(2, int(math.sqrt(n)) + 1))
    
  2. This answer used some kind of while loop:

    def is_prime_2(n):
        if n <= 1:
            return False
        if n == 2:
            return True
        if n == 3:
            return True
        if n % 2 == 0:
            return False
        if n % 3 == 0:
            return False
    
        i = 5
        w = 2
        while i * i <= n:
            if n % i == 0:
                return False
            i += w
            w = 6 - w
    
        return True
    
  3. This answer included a version with a for loop:

    def is_prime_3(n):
        if n <= 1:
            return False
    
        if n % 2 == 0 and n > 2:
            return False
    
        for i in range(3, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    
  4. And I mixed a few ideas from the other answers into a new one:

    def is_prime_4(n):
        if n <= 1:          # negative numbers, 0 or 1
            return False
        if n <= 3:          # 2 and 3
            return True
        if n % 2 == 0 or n % 3 == 0:
            return False
    
        for i in range(5, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    

Here is my script to compare the variants:

import math
import pandas as pd
import seaborn as sns
import time
from matplotlib import pyplot as plt


def is_prime_1(n):
    ...
def is_prime_2(n):
    ...
def is_prime_3(n):
    ...
def is_prime_4(n):
    ...

default_func_list = (is_prime_1, is_prime_2, is_prime_3, is_prime_4)

def assert_equal_results(func_list=default_func_list, n):
    for i in range(-2, n):
        r_list = [f(i) for f in func_list]
        if not all(r == r_list[0] for r in r_list):
            print(i, r_list)
            raise ValueError
    print('all functions return the same results for integers up to {}'.format(n))

def compare_functions(func_list=default_func_list, n):
    result_list = []
    n_measurements = 3

    for f in func_list:
        for i in range(1, n + 1):
            ret_list = []
            t_sum = 0
            for _ in range(n_measurements):
                t_start = time.perf_counter()
                is_prime = f(i)
                t_end = time.perf_counter()

                ret_list.append(is_prime)
                t_sum += (t_end - t_start)

            is_prime = ret_list[0]
            assert all(ret == is_prime for ret in ret_list)
            result_list.append((f.__name__, i, is_prime, t_sum / n_measurements))

    df = pd.DataFrame(
        data=result_list,
        columns=['f', 'number', 'is_prime', 't_seconds'])
    df['t_micro_seconds'] = df['t_seconds'].map(lambda x: round(x * 10**6, 2))
    print('df.shape:', df.shape)

    print()
    print('', '-' * 41)
    print('| {:11s} | {:11s} | {:11s} |'.format(
        'is_prime', 'count', 'percent'))
    df_sub1 = df[df['f'] == 'is_prime_1']
    print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
        'all', df_sub1.shape[0], 100))
    for (is_prime, count) in df_sub1['is_prime'].value_counts().iteritems():
        print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
            str(is_prime), count, count * 100 / df_sub1.shape[0]))
    print('', '-' * 41)

    print()
    print('', '-' * 69)
    print('| {:11s} | {:11s} | {:11s} | {:11s} | {:11s} |'.format(
        'f', 'is_prime', 't min (us)', 't mean (us)', 't max (us)'))
    for f, df_sub1 in df.groupby(['f', ]):
        col = df_sub1['t_micro_seconds']
        print('|{0}|{0}|{0}|{0}|{0}|'.format('-' * 13))
        print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
            f, 'all', col.min(), col.mean(), col.max()))
        for is_prime, df_sub2 in df_sub1.groupby(['is_prime', ]):
            col = df_sub2['t_micro_seconds']
            print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
                f, str(is_prime), col.min(), col.mean(), col.max()))
    print('', '-' * 69)

    return df

Running the function compare_functions(n=10**5) (numbers up to 100.000) I get this output:

df.shape: (400000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |     100,000 |     100.0 % |
| False       |      90,408 |      90.4 % |
| True        |       9,592 |       9.6 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.57 |        2.50 |      154.35 |
| is_prime_1  | False       |        0.57 |        1.52 |      154.35 |
| is_prime_1  | True        |        0.89 |       11.66 |       55.54 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        1.14 |      304.82 |
| is_prime_2  | False       |        0.24 |        0.56 |      304.82 |
| is_prime_2  | True        |        0.25 |        6.67 |       48.49 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        0.95 |       50.99 |
| is_prime_3  | False       |        0.20 |        0.60 |       40.62 |
| is_prime_3  | True        |        0.58 |        4.22 |       50.99 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.20 |        0.89 |       20.09 |
| is_prime_4  | False       |        0.21 |        0.53 |       14.63 |
| is_prime_4  | True        |        0.20 |        4.27 |       20.09 |
 ---------------------------------------------------------------------

Then, running the function compare_functions(n=10**6) (numbers up to 1.000.000) I get this output:

df.shape: (4000000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |   1,000,000 |     100.0 % |
| False       |     921,502 |      92.2 % |
| True        |      78,498 |       7.8 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.51 |        5.39 |     1414.87 |
| is_prime_1  | False       |        0.51 |        2.19 |      413.42 |
| is_prime_1  | True        |        0.87 |       42.98 |     1414.87 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        2.65 |      612.69 |
| is_prime_2  | False       |        0.24 |        0.89 |      322.81 |
| is_prime_2  | True        |        0.24 |       23.27 |      612.69 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        1.93 |       67.40 |
| is_prime_3  | False       |        0.20 |        0.82 |       61.39 |
| is_prime_3  | True        |        0.59 |       14.97 |       67.40 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.18 |        1.88 |      332.13 |
| is_prime_4  | False       |        0.20 |        0.74 |      311.94 |
| is_prime_4  | True        |        0.18 |       15.23 |      332.13 |
 ---------------------------------------------------------------------

I used the following script to plot the results:

def plot_1(func_list=default_func_list, n):
    df_orig = compare_functions(func_list=func_list, n=n)
    df_filtered = df_orig[df_orig['t_micro_seconds'] <= 20]
    sns.lmplot(
        data=df_filtered, x='number', y='t_micro_seconds',
        col='f',
        # row='is_prime',
        markers='.',
        ci=None)

    plt.ticklabel_format(style='sci', axis='x', scilimits=(3, 3))
    plt.show()

Get protocol, domain, and port from URL

var getBasePath = function(url) {
    var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
    return r ? r[0] : '';
};

How do you 'redo' changes after 'undo' with Emacs?

Beware of an undo-tree quirk for redo!

Many popular “starter kits” (prelude, purcell, spacemacs) come bundled with undo-tree. Most (all?) even auto-enable it. As mentioned, undo-tree is a handy way to visualize and traverse the undo/redo tree. Prelude even gives it a key-chord (uu), and also C-x u.

The problem is: undo-tree seems to wreck Emacs’ default and well-known binding for redo: C-g C-/.

Instead, you can use these symmetrical keys for undo/redo:

C-/     undo
C-S-/   redo

These are useful since sometimes you want to quickly redo without opening up the visualizer.

With CSS, use "..." for overflowed block of multi-lines

There are also several jquery plugins that deal with this issue, but many do not handle multiple lines of text. Following works:

There also some preformance tests.

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

Catching errors in Angular HttpClient

You probably want to have something like this:

this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})

It highly depends also how do you use your service but this is the basic case.

Why does overflow:hidden not work in a <td>?

Apply CSS table-layout:fixed; (and sometimes width:<any px or %>) to the TABLE and white-space: nowrap; overflow: hidden; style on TD. Then set CSS widths on the correct cell or column elements.

Significantly, fixed-layout table column widths are determined by the cell widths in the first row of the table. If there are TH elements in the first row, and widths are applied to TD (and not TH), then the width only applies to the contents of the TD (white-space and overflow may be ignored); the table columns will distribute evenly regardless of the set TD width (because there are no widths specified [on TH in the first row]) and the columns will have [calculated] equal widths; the table will not recalculate the column width based on TD width in subsequent rows. Set the width on the first cell elements the table will encounter.

Alternatively, and the safest way to set column widths is to use <COLGROUP> and <COL> tags in the table with the CSS width set on each fixed width COL. Cell width related CSS plays nicer when the table knows the column widths in advance.