Programs & Examples On #Cups

CUPS is the standards-based, open source printing system for Mac OS X and other UNIX®-like operating systems.

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

How to take input in an array + PYTHON?

raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

How do you execute an arbitrary native command from a string?

Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).

http://connect.microsoft.com/PowerShell/feedback/details/376207/

They suggest using --% as a way to force PowerShell to stop trying to interpret the text to the right.

For example:

MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

the error i received was:

cockpit.socket: Failed to listen on sockets: Address already in use

the fix I discovered is:

  1. I had to disable selinux
  2. in /usr/lib/systemd/system/cockpit service i changed the line :

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws --selinux-type=etc_t
    

    to:

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws 
    

so as you can see i took out the argument about selinux then i ran:

systemctl daemon-reload
systemctl start cockpit.service

then I browsed to:

I accepted the self-signed certificate and was able to login successfully to cockpit and use it normally.

this is all on a fedora25 machine. the 9090 port had already been added using firewall-cmd

List of zeros in python

zlists = [[0] * i for i in range(10)]

zlists[0] is a list of 0 zeroes, zlists[1] is a list of 1 zero, zlists[2] is a list of 2 zeroes, etc.

Spring 3 MVC accessing HttpRequest from controller

I know that is a old question, but...

You can also use this in your class:

@Autowired
private HttpServletRequest context;

And this will provide the current instance of HttpServletRequest for you use on your method.

Merge 2 DataTables and store in a new one

The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);

What is the equivalent of Java's final in C#?

The final keyword has several usages in Java. It corresponds to both the sealed and readonly keywords in C#, depending on the context in which it is used.

Classes

To prevent subclassing (inheritance from the defined class):

Java

public final class MyFinalClass {...}

C#

public sealed class MyFinalClass {...}

Methods

Prevent overriding of a virtual method.

Java

public class MyClass
{
    public final void myFinalMethod() {...}
}

C#

public class MyClass : MyBaseClass
{
    public sealed override void MyFinalMethod() {...}
}

As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual, whereas C# marks them as sealed. Hence, you only need to use the sealed keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual in the base class.

Variables

To only allow a variable to be assigned once:

Java

public final double pi = 3.14; // essentially a constant

C#

public readonly double pi = 3.14; // essentially a constant

As a side note, the effect of the readonly keyword differs from that of the const keyword in that the readonly expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.

mongodb how to get max value from collections

For max value, we can write sql query as

select age from table_name order by age desc limit 1

same way we can write in mongodb too.

db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age

What's the difference between JPA and Hibernate?

Figuratively speaking JPA is just interface, Hibernate/TopLink - class (i.e. interface implementation).

You must have interface implementation to use interface. But you can use class through interface, i.e. Use Hibernate through JPA API or you can use implementation directly, i.e. use Hibernate directly, not through pure JPA API.

Good book about JPA is "High-Performance Java Persistence" of Vlad Mihalcea.

setting multiple column using one update

UPDATE some_table 
   SET this_column=x, that_column=y 
   WHERE something LIKE 'them'

How to replace sql field value

To avoid update names that contain .com like [email protected] to [email protected], you can do this:

UPDATE Yourtable
SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

If you are dealing with a table and one of the dates happens to be null, you can code it like this:

  @{
     if (Model.SomeCollection[i].date_due == null)
       {
         <td><input type='date' id="@("dd" + i)" name="dd" /></td>
       }
       else
       {
         <td><input type='date' value="@Model.SomeCollection[i].date_due.Value.ToString("yyyy-MM-dd")" id="@("dd" + i)" name="dd" /></td>
       }
   }

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

You can try to turn support on in spring's converter

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // add converter suport Content-Type: 'application/x-www-form-urlencoded'
        converters.stream()
                .filter(AllEncompassingFormHttpMessageConverter.class::isInstance)
                .map(AllEncompassingFormHttpMessageConverter.class::cast)
                .findFirst()
                .ifPresent(converter -> converter.addSupportedMediaTypes(MediaType.APPLICATION_FORM_URLENCODED_VALUE));
    }

}

How to tell whether a point is to the right or left side of a line

equation of line is y-y1 = m(x-x1)

here m is y2-y1 / x2-x1

now put m in equation and put condition on y < m(x-x1) + y1 then it is left side point

eg.

for i in rows:

  for j in cols:

    if j>m(i-a)+b:

      image[i][j]=0

static files with express.js

use below inside your app.js

app.use(express.static('folderName'));

(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)

are there dictionaries in javascript like python?

This is an old post, but I thought I should provide an illustrated answer anyway.

Use javascript's object notation. Like so:

states_dictionary={ 
     "CT":["alex","harry"], 
     "AK":["liza","alex"], 
     "TX":["fred", "harry"]
};

And to access the values:

states_dictionary.AK[0] //which is liza

or you can use javascript literal object notation, whereby the keys not require to be in quotes:

states_dictionary={ 
     CT:["alex","harry"], 
     AK:["liza","alex"], 
     TX:["fred", "harry"]
};

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

for i in *.xls ; do 
  [[ -f "$i" ]] || continue
  xls2csv "$i" "${i%.xls}.csv"
done

The first line in the do checks if the "matching" file really exists, because in case nothing matches in your for, the do will be executed with "*.xls" as $i. This could be horrible for your xls2csv.

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

Handling back button in Android Navigation Component

Here is my solution

Use androidx.appcompat.app.AppCompatActivity for the activity that contains the NavHostFragment fragment.

Define the following interface and implement it in all navigation destination fragments

interface InterceptionInterface {

    fun onNavigationUp(): Boolean
    fun onBackPressed(): Boolean
}

In your activity override onSupportNavigateUp and onBackPressed:

override fun onSupportNavigateUp(): Boolean {
        return getCurrentNavDest().onNavigationUp() || navigation_host_fragment.findNavController().navigateUp()
}

override fun onBackPressed() {
        if (!getCurrentNavDest().onBackPressed()){
            super.onBackPressed()
        }
}

private fun getCurrentNavDest(): InterceptionInterface {
        val currentFragment = navigation_host_fragment.childFragmentManager.primaryNavigationFragment as InterceptionInterface
        return currentFragment
}

This solution has the advantage, that the navigation destination fragments don't need to worry about the unregistering of their listeners as soon as they are detached.

Flushing footer to bottom of the page, twitter bootstrap

Keep it simple.

footer {
  bottom: 0;
  position: absolute;
}

You may need to also offset the height of the footer by adding a margin-bottom equivalent to the footer height to the body.

Labeling file upload button

much easier use it

<input type="button" id="loadFileXml" value="Custom Button Name"onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>

How do I convert a decimal to an int in C#?

decimal vIn = 0.0M;
int vOut = Convert.ToInt32(vIn);

Here is a very handy convert data type webpage for those of others. http://www.convertdatatypes.com/Convert-decimal-to-int-in-CSharp.html

Sorting an IList in C#

using System.Linq;

var yourList = SomeDAO.GetRandomThings();
yourList.ToList().Sort( (thing, randomThing) => thing.CompareThisProperty.CompareTo( randomThing.CompareThisProperty ) );

That's pretty !ghetto.

How to declare array of zeros in python (or an array of a certain size)

Depending on what you're actually going to do with the data after it's collected, collections.defaultdict(int) might be useful.

Render HTML to PDF in Django site

You can use iReport editor to define the layout, and publish the report in jasper reports server. After publish you can invoke the rest api to get the results.

Here is the test of the functionality:

from django.test import TestCase
from x_reports_jasper.models import JasperServerClient

"""
    to try integraction with jasper server through rest
"""
class TestJasperServerClient(TestCase):

    # define required objects for tests
    def setUp(self):

        # load the connection to remote server
        try:

            self.j_url = "http://127.0.0.1:8080/jasperserver"
            self.j_user = "jasperadmin"
            self.j_pass = "jasperadmin"

            self.client = JasperServerClient.create_client(self.j_url,self.j_user,self.j_pass)

        except Exception, e:
            # if errors could not execute test given prerrequisites
            raise

    # test exception when server data is invalid
    def test_login_to_invalid_address_should_raise(self):
        self.assertRaises(Exception,JasperServerClient.create_client, "http://127.0.0.1:9090/jasperserver",self.j_user,self.j_pass)

    # test execute existent report in server
    def test_get_report(self):

        r_resource_path = "/reports/<PathToPublishedReport>"
        r_format = "pdf"
        r_params = {'PARAM_TO_REPORT':"1",}

        #resource_meta = client.load_resource_metadata( rep_resource_path )

        [uuid,out_mime,out_data] = self.client.generate_report(r_resource_path,r_format,r_params)
        self.assertIsNotNone(uuid)

And here is an example of the invocation implementation:

from django.db import models
import requests
import sys
from xml.etree import ElementTree
import logging 

# module logger definition
logger = logging.getLogger(__name__)

# Create your models here.
class JasperServerClient(models.Manager):

    def __handle_exception(self, exception_root, exception_id, exec_info ):
        type, value, traceback = exec_info
        raise JasperServerClientError(exception_root, exception_id), None, traceback

    # 01: REPORT-METADATA 
    #   get resource description to generate the report
    def __handle_report_metadata(self, rep_resourcepath):

        l_path_base_resource = "/rest/resource"
        l_path = self.j_url + l_path_base_resource
        logger.info( "metadata (begin) [path=%s%s]"  %( l_path ,rep_resourcepath) )

        resource_response = None
        try:
            resource_response = requests.get( "%s%s" %( l_path ,rep_resourcepath) , cookies = self.login_response.cookies)

        except Exception, e:
            self.__handle_exception(e, "REPORT_METADATA:CALL_ERROR", sys.exc_info())

        resource_response_dom = None
        try:
            # parse to dom and set parameters
            logger.debug( " - response [data=%s]"  %( resource_response.text) )
            resource_response_dom = ElementTree.fromstring(resource_response.text)

            datum = "" 
            for node in resource_response_dom.getiterator():
                datum = "%s<br />%s - %s" % (datum, node.tag, node.text)
            logger.debug( " - response [xml=%s]"  %( datum ) )

            #
            self.resource_response_payload= resource_response.text
            logger.info( "metadata (end) ")
        except Exception, e:
            logger.error( "metadata (error) [%s]" % (e))
            self.__handle_exception(e, "REPORT_METADATA:PARSE_ERROR", sys.exc_info())


    # 02: REPORT-PARAMS 
    def __add_report_params(self, metadata_text, params ):
        if(type(params) != dict):
            raise TypeError("Invalid parameters to report")
        else:
            logger.info( "add-params (begin) []" )
            #copy parameters
            l_params = {}
            for k,v in params.items():
                l_params[k]=v
            # get the payload metadata
            metadata_dom = ElementTree.fromstring(metadata_text)
            # add attributes to payload metadata
            root = metadata_dom #('report'):

            for k,v in l_params.items():
                param_dom_element = ElementTree.Element('parameter')
                param_dom_element.attrib["name"] = k
                param_dom_element.text = v
                root.append(param_dom_element)

            #
            metadata_modified_text =ElementTree.tostring(metadata_dom, encoding='utf8', method='xml')
            logger.info( "add-params (end) [payload-xml=%s]" %( metadata_modified_text )  )
            return metadata_modified_text



    # 03: REPORT-REQUEST-CALL 
    #   call to generate the report
    def __handle_report_request(self, rep_resourcepath, rep_format, rep_params):

        # add parameters
        self.resource_response_payload = self.__add_report_params(self.resource_response_payload,rep_params)

        # send report request

        l_path_base_genreport = "/rest/report"
        l_path = self.j_url + l_path_base_genreport
        logger.info( "report-request (begin) [path=%s%s]"  %( l_path ,rep_resourcepath) )

        genreport_response = None
        try:
            genreport_response = requests.put( "%s%s?RUN_OUTPUT_FORMAT=%s" %(l_path,rep_resourcepath,rep_format),data=self.resource_response_payload, cookies = self.login_response.cookies )
            logger.info( " - send-operation-result [value=%s]"  %( genreport_response.text) )
        except Exception,e:
            self.__handle_exception(e, "REPORT_REQUEST:CALL_ERROR", sys.exc_info())


        # parse the uuid of the requested report
        genreport_response_dom = None

        try:
            genreport_response_dom = ElementTree.fromstring(genreport_response.text)

            for node in genreport_response_dom.findall("uuid"):
                datum = "%s" % (node.text)

            genreport_uuid = datum      

            for node in genreport_response_dom.findall("file/[@type]"):
                datum = "%s" % (node.text)
            genreport_mime = datum

            logger.info( "report-request (end) [uuid=%s,mime=%s]"  %( genreport_uuid, genreport_mime) )

            return [genreport_uuid,genreport_mime]
        except Exception,e:
            self.__handle_exception(e, "REPORT_REQUEST:PARSE_ERROR", sys.exc_info())

    # 04: REPORT-RETRIEVE RESULTS 
    def __handle_report_reply(self, genreport_uuid ):


        l_path_base_getresult = "/rest/report"
        l_path = self.j_url + l_path_base_getresult 
        logger.info( "report-reply (begin) [uuid=%s,path=%s]"  %( genreport_uuid,l_path) )

        getresult_response = requests.get( "%s%s/%s?file=report" %(self.j_url,l_path_base_getresult,genreport_uuid),data=self.resource_response_payload, cookies = self.login_response.cookies )
        l_result_header_mime =getresult_response.headers['Content-Type']

        logger.info( "report-reply (end) [uuid=%s,mime=%s]"  %( genreport_uuid, l_result_header_mime) )
        return [l_result_header_mime, getresult_response.content]

    # public methods ---------------------------------------    

    # tries the authentication with jasperserver throug rest
    def login(self, j_url, j_user,j_pass):
        self.j_url= j_url

        l_path_base_auth = "/rest/login"
        l_path = self.j_url + l_path_base_auth

        logger.info( "login (begin) [path=%s]"  %( l_path) )

        try:
            self.login_response = requests.post(l_path , params = {
                    'j_username':j_user,
                    'j_password':j_pass
                })                  

            if( requests.codes.ok != self.login_response.status_code ):
                self.login_response.raise_for_status()

            logger.info( "login (end)" )
            return True
            # see http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/

        except Exception, e:
            logger.error("login (error) [e=%s]" % e )
            self.__handle_exception(e, "LOGIN:CALL_ERROR",sys.exc_info())
            #raise

    def generate_report(self, rep_resourcepath,rep_format,rep_params):
        self.__handle_report_metadata(rep_resourcepath)
        [uuid,mime] = self.__handle_report_request(rep_resourcepath, rep_format,rep_params)
        # TODO: how to handle async?
        [out_mime,out_data] = self.__handle_report_reply(uuid)
        return [uuid,out_mime,out_data]

    @staticmethod
    def create_client(j_url, j_user, j_pass):
        client = JasperServerClient()
        login_res = client.login( j_url, j_user, j_pass )
        return client


class JasperServerClientError(Exception):

    def __init__(self,exception_root,reason_id,reason_message=None):
        super(JasperServerClientError, self).__init__(str(reason_message))
        self.code = reason_id 
        self.description = str(exception_root) + " " + str(reason_message)
    def __str__(self):
        return self.code + " " + self.description

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

I wanted to add something to the answer already provided. maven-compiler-plugin by default will compile your project using Java 1.5 which is where m2e get's its information.

That's why you have to explicitly declare the maven-compiler-plugin in your project with something other then 1.5. Your effective pom.xml will implicitly use the default set in the maven-compiler-plugin pom.xml.

UIScrollView Scrollable Content Size Ambiguity

Swift 4+ approach:

1) Set UIScrollView top, bottom, left and right margins to 0

2) Inside the UIScrollView add a UIView and set top, bottom, leading, trailing margins to 0 ( equal to UIScrollView margins ).

3) The most important part is to set width and height, where height constraint should have a low priority.

private func setupConstraints() {

    // Constraints for scrollView
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    // Constraints for containerView
    containerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
    containerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
    containerView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
    containerView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
    containerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true

    let heightConstraint = containerView.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
    heightConstraint.priority = UILayoutPriority(rawValue: 250)
    heightConstraint.isActive = true
}

ORACLE and TRIGGERS (inserted, updated, deleted)

I've changed my code like this and it works:

CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR UPDATE OR DELETE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer 
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 

DECLARE
      Operation       NUMBER;
      CustomerCode    CHAR(10 BYTE);
BEGIN

IF DELETING THEN 
  Operation := 3;
  CustomerCode := :old_buffer.field1;
END IF;

IF INSERTING THEN 
  Operation := 1;
  CustomerCode := :new_buffer.field1;
END IF;

IF UPDATING THEN 
  Operation := 2;
  CustomerCode := :new_buffer.field1;
END IF;    

// DO SOMETHING ...

EXCEPTION
    WHEN OTHERS THEN ErrorCode := SQLCODE;

END;

What is difference between @RequestBody and @RequestParam?

@RequestParam annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:

request:

GET: http://someserver.org/path?name=John&surname=Smith

endpoint code:

public User getUser(@RequestParam(value = "name") String name, 
                    @RequestParam(value = "surname") String surname){ 
    ...  
    }

So basically, while @RequestBody maps entire user request (even for POST) to a String variable, @RequestParam does so with one (or more - but it is more complicated) request param to your method argument.

Convert string (without any separator) to list

Make a list(your_string).

>>> s = "mep"
>>> list(s)
['m', 'e', 'p']

Two values from one input in python?

If you need to take two integers say a,b in python you can use map function.
Suppose input is,

1
5 3
1 2 3 4 5

where 1 represent test case, 5 represent number of values and 3 represents a task value and in next line given 5 values, we can take such input using this method in PYTH 2.x Version.

testCases=int(raw_input())
number, taskValue = map(int, raw_input().split())
array = map(int, raw_input().split())

You can replace 'int' in map() with another datatype needed.

How to check if element in groovy array/hash/collection/list?

You can also use matches with regular expression like this:

boolean bool = List.matches("(?i).*SOME STRING HERE.*")

Display a jpg image on a JPanel

ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );

Relative paths based on file location instead of current working directory

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:


Linux / GNU readlink solution:

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

 scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")

Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.


Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):

If your script must run on any platform that:

  • has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

    • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
  • does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

The following solution, inspired by https://stackoverflow.com/a/1116890/45375, defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

  • If readlink is available, it is used (without options) - true on most modern platforms.

  • Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
    Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
    (Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)

  • An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

JSON, like xml and various other formats, is a tree-based serialization format. It won't love you if you have circular references in your objects, as the "tree" would be:

root B => child A => parent B => child A => parent B => ...

There are often ways of disabling navigation along a certain path; for example, with XmlSerializer you might mark the parent property as XmlIgnore. I don't know if this is possible with the json serializer in question, nor whether DatabaseColumn has suitable markers (very unlikely, as it would need to reference every serialization API)

Angular 6: How to set response type as text while making http call

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

Writing a dictionary to a csv file with one line for every 'key: value'

I've personally always found the csv module kind of annoying. I expect someone else will show you how to do this slickly with it, but my quick and dirty solution is:

with open('dict.csv', 'w') as f:  # This creates the file object for the context 
                                  # below it and closes the file automatically
    l = []
    for k, v in mydict.iteritems(): # Iterate over items returning key, value tuples
        l.append('%s: %s' % (str(k), str(v))) # Build a nice list of strings
    f.write(', '.join(l))                     # Join that list of strings and write out

However, if you want to read it back in, you'll need to do some irritating parsing, especially if it's all on one line. Here's an example using your proposed file format.

with open('dict.csv', 'r') as f: # Again temporary file for reading
    d = {}
    l = f.read().split(',')      # Split using commas
    for i in l:
        values = i.split(': ')   # Split using ': '
        d[values[0]] = values[1] # Any type conversion will need to happen here

adb remount permission denied, but able to access super user in shell -- android

you can use:

adb shell su -c "your command here"

only rooted devices with su works.

Breaking out of nested loops

Use itertools.product!

from itertools import product
for x, y in product(range(10), range(10)):
    #do whatever you want
    break

Here's a link to itertools.product in the python documentation: http://docs.python.org/library/itertools.html#itertools.product

You can also loop over an array comprehension with 2 fors in it, and break whenever you want to.

>>> [(x, y) for y in ['y1', 'y2'] for x in ['x1', 'x2']]
[
    ('x1', 'y1'), ('x2', 'y1'),
    ('x1', 'y2'), ('x2', 'y2')
]

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

How to open a file for both reading and writing?

Summarize the I/O behaviors

|          Mode          |  r   |  r+  |  w   |  w+  |  a   |  a+  |
| :--------------------: | :--: | :--: | :--: | :--: | :--: | :--: |
|          Read          |  +   |  +   |      |  +   |      |  +   |
|         Write          |      |  +   |  +   |  +   |  +   |  +   |
|         Create         |      |      |  +   |  +   |  +   |  +   |
|         Cover          |      |      |  +   |  +   |      |      |
| Point in the beginning |  +   |  +   |  +   |  +   |      |      |
|    Point in the end    |      |      |      |      |  +   |  +   |

and the decision branch

enter image description here

Update cordova plugins in one command

This is my Windows Batch version for update all plugins in one command

How to use:

From command line, in the same folder of project, run

c:\> batchNameFile

or

c:\> batchNameFile autoupdate

Where "batchNameFile" is the name of .BAT file, with the script below.

For only test ( first exmple ) or to force every update avaiable ( 2nd example )

@echo off

cls

set pluginListFile=update.plugin.list

if exist %pluginListFile% del %pluginListFile%

Echo "Reading installed Plugins"
Call cordova plugins > %pluginListFile%
echo.

for /F "tokens=1,2 delims= " %%a in ( %pluginListFile% ) do (
   Echo "Checking online version for %%a"

   for /F "delims=" %%I in ( 'npm info %%a version' ) do (
     Echo "Local : %%b"
     Echo "Online: %%I"
     if %%b LSS %%I Call :toUpdate %%a %~1
     :cont
     echo.
   )
)

if exist %pluginListFile% del %pluginListFile%

Exit /B

:toUpdate
Echo "Need Update !"
if '%~2' == 'autoupdate' Call :DoUpdate %~1
goto cont

:DoUpdate
Echo "Removing Plugin"
Call cordova plugin rm %~1
Echo "Adding Plugin"
Call cordova plugin add %~1
goto cont

This batch was only tested in Windows 10

#1071 - Specified key was too long; max key length is 1000 bytes

As @Devart says, the total length of your index is too long.

The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.

The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.

You can declare a prefix length per column as you define the index. For example:

...
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
...

But what's the best prefix length for a given column? Here's a method to find out:

SELECT
 ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
 ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
 ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
 ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;

It tells you the proportion of rows that have no more than a given string length in the menu_link column. You might see output like this:

+---------------+---------------+---------------+----------------+
| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
+---------------+---------------+---------------+----------------+
|         21.78 |         80.20 |        100.00 |         100.00 |
+---------------+---------------+---------------+----------------+

This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.

PS: The INT(1) and INT(32) data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL option.

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

How to create and add users to a group in Jenkins for authentication?

According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.

However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.

NTFS performance and large volumes of files and directories

For local access, large numbers of directories/files doesn't seem to be an issue. However, if you're accessing it across a network, there's a noticeable performance hit after a few hundred (especially when accessed from Vista machines (XP to Windows Server w/NTFS seemed to run much faster in that regard)).

How to get to a particular element in a List in java?

String[] is an array of Strings. Such an array is internally a class. Like all classes that don't explicitly extend some other class, it extends Object implicitly. The method toString() of class Object, by default, gives you the representation you see: the class name, followed by @, followed by the hash code in hex. Since the String[] class doesn't override the toString() method, you get that as a result.

Create some method that outputs the array elements for you. Iterate over the array and use System.out.print() (not print*ln*) on the elements.

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

So, @Vivek has got the solution to the problem through a dialogue in the Comments rather than through an actual answer.

"The file is being created by user oracle just noticed this in our development database. i'm getting this error because, the directory where i try to create the file doesn't have write access for others and user oracle comes under others category. "

Who says SO is a Q&A site not a forum? Er, me, amongst others. Anyway, in the absence of an accepted answer to this question I proffer a link to an answer of mine on the topic of UTL_FILE.FOPEN(). Find it here.

P.S. I'm marking this answer Community Wiki, because it's not a proper answer to this question, just a redirect to somewhere else.

How to add Drop-Down list (<select>) programmatically?

Here's an ES6 version, conversion to vanilla JS shouldn't be too hard but I already have jQuery anyways:

_x000D_
_x000D_
function select(options, selected) {_x000D_
  return Object.entries(options).reduce((r, [k, v]) => r.append($('<option>').val(k).text(v)), $('<select>')).val(selected);_x000D_
}_x000D_
$('body').append(select({'option1': 'label 1', 'option2': 'label 2'}, 'option2'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

Exploring Docker container's file system

I use another dirty trick that is aufs/devicemapper agnostic.

I look at the command that the container is running e.g. docker ps and if it's an apache or java i just do the following:

sudo -s
cd /proc/$(pgrep java)/root/

and voilá you're inside the container.

Basically you can as root cd into /proc/<PID>/root/ folder as long as that process is run by the container. Beware symlinks will not make sense wile using that mode.

Changing permissions via chmod at runtime errors with "Operation not permitted"

In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.

Char array declaration and initialization in C

Yes, this is a kind of inconsistency in the language.

The "=" in myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; it's an initialization of the array. There's no way for "late initialization".

You should just remember this rule.

Extracting time from POSIXct

You can use strftime to convert datetimes to any character format:

> t <- strftime(times, format="%H:%M:%S")
> t
 [1] "02:06:49" "03:37:07" "00:22:45" "00:24:35" "03:09:57" "03:10:41"
 [7] "05:05:57" "07:39:39" "06:47:56" "07:56:36"

But that doesn't help very much, since you want to plot your data. One workaround is to strip the date element from your times, and then to add an identical date to all of your times:

> xx <- as.POSIXct(t, format="%H:%M:%S")
> xx
 [1] "2012-03-23 02:06:49 GMT" "2012-03-23 03:37:07 GMT"
 [3] "2012-03-23 00:22:45 GMT" "2012-03-23 00:24:35 GMT"
 [5] "2012-03-23 03:09:57 GMT" "2012-03-23 03:10:41 GMT"
 [7] "2012-03-23 05:05:57 GMT" "2012-03-23 07:39:39 GMT"
 [9] "2012-03-23 06:47:56 GMT" "2012-03-23 07:56:36 GMT"

Now you can use these datetime objects in your plot:

plot(xx, rnorm(length(xx)), xlab="Time", ylab="Random value")

enter image description here


For more help, see ?DateTimeClasses

How do you create a custom AuthorizeAttribute in ASP.NET Core?

The modern way is AuthenticationHandlers

in startup.cs add

services.AddAuthentication("BasicAuthentication").AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);

public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        private readonly IUserService _userService;

        public BasicAuthenticationHandler(
            IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock,
            IUserService userService)
            : base(options, logger, encoder, clock)
        {
            _userService = userService;
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
                return AuthenticateResult.Fail("Missing Authorization Header");

            User user = null;
            try
            {
                var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
                var username = credentials[0];
                var password = credentials[1];
                user = await _userService.Authenticate(username, password);
            }
            catch
            {
                return AuthenticateResult.Fail("Invalid Authorization Header");
            }

            if (user == null)
                return AuthenticateResult.Fail("Invalid User-name or Password");

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username),
            };
            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return AuthenticateResult.Success(ticket);
        }
    }

IUserService is a service that you make where you have user name and password. basically it returns a user class that you use to map your claims on.

var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username),
            }; 

Then you can query these claims and her any data you mapped, ther are quite a few, have a look at ClaimTypes class

you can use this in an extension method an get any of the mappings

public int? GetUserId()
{
   if (context.User.Identity.IsAuthenticated)
    {
       var id=context.User.FindFirst(ClaimTypes.NameIdentifier);
       if (!(id is null) && int.TryParse(id.Value, out var userId))
            return userId;
     }
      return new Nullable<int>();
 }

This new way, i think is better than the old way as shown here, both work

public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.Headers.Authorization != null)
        {
            var authToken = actionContext.Request.Headers.Authorization.Parameter;
            // decoding authToken we get decode value in 'Username:Password' format
            var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
            // spliting decodeauthToken using ':'
            var arrUserNameandPassword = decodeauthToken.Split(':');
            // at 0th postion of array we get username and at 1st we get password
            if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))
            {
                // setting current principle
                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(arrUserNameandPassword[0]), null);
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
        else
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        }
    }

    public static bool IsAuthorizedUser(string Username, string Password)
    {
        // In this method we can handle our database logic here...
        return Username.Equals("test") && Password == "test";
    }
}

CSS Change List Item Background Color with Class

1) You can use the !important rule, like this:

.selected
{
  background-color:red !important;
}

See http://www.w3.org/TR/CSS2/cascade.html#important-rules for more info.

2) In your example you can also get the red background by using ul.nav li.selected instead of just .selected. This makes the selector more specific.

See http://www.w3.org/TR/CSS2/cascade.html#specificity for more info.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

What is this Javascript "require"?

I noticed that whilst the other answers explained what require is and that it is used to load modules in Node they did not give a full reply on how to load node modules when working in the Browser.

It is quite simple to do. Install your module using npm as you describe, and the module itself will be located in a folder usually called node_modules.

Now the simplest way to load it into your app is to reference it from your html with a script tag which points at this directory. i.e if your node_modules directory is in the root of the project at the same level as your index.html you would write this in your index.html:

<script src="node_modules/ng"></script>

That whole script will now be loaded into the page - so you can access its variables and methods directly.

There are other approaches which are more widely used in larger projects, such as a module loader like require.js. Of the two, I have not used Require myself, but I think it is considered by many people the way to go.

Eclipse Optimize Imports to Include Static Imports

Select the constant, type

Ctrl + 1  (quick fix)

Select "Convert to static import." from the drop down.

"Quick fix" has options even though it is not an error.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

For my list view am using custom Adapter which extends ArrayAdapter. in listiview i have 2 buttons one of the buttons as Custom AlertDialogBox. Ex: Activity parentActivity; Constructor for Adapter `

public CustomAdapter(ArrayList<Contact> data, Activity parentActivity,Context context) {
        super(context,R.layout.listdummy,data);
        this.mContext   =   context;
        this.parentActivity  =   parentActivity;
    }

` calling Adapter from MainActivty

_x000D_
_x000D_
adapter = new CustomAdapter(dataModels,MainActivity.this,this);
_x000D_
_x000D_
_x000D_

now write ur alertdialog inside ur button which is in the Adapter class

_x000D_
_x000D_
viewHolder.update.setOnClickListener(new View.OnClickListener() {_x000D_
            @Override_x000D_
            public void onClick(final View view) {_x000D_
            _x000D_
_x000D_
                AlertDialog.Builder alertDialog =   new AlertDialog.Builder(parentActivity);_x000D_
                alertDialog.setTitle("Updating");_x000D_
                alertDialog.setCancelable(false);_x000D_
_x000D_
                LayoutInflater layoutInflater   = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);_x000D_
                 @SuppressLint("InflateParams") final View view1   =   layoutInflater.inflate(R.layout.dialog,null);_x000D_
                alertDialog.setView(view1);_x000D_
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {_x000D_
                    @Override_x000D_
                    public void onClick(DialogInterface dialogInterface, int i) {_x000D_
                        dialogInterface.cancel();_x000D_
                    }_x000D_
                });_x000D_
                alertDialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {_x000D_
                    @Override_x000D_
                    public void onClick(DialogInterface dialogInterface, int i) {_x000D_
_x000D_
                    //ur logic_x000D_
                            }_x000D_
                    }_x000D_
                });_x000D_
                  alertDialog.create().show();_x000D_
_x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

Dynamic instantiation from string name of a class in dynamically imported module?

Use getattr to get an attribute from a name in a string. In other words, get the instance as

instance = getattr(modul, class_name)()

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

How to match "anything up until this sequence of characters" in a regular expression?

As @Jared Ng and @Issun pointed out, the key to solve this kind of RegEx like "matching everything up to a certain word or substring" or "matching everything after a certain word or substring" is called "lookaround" zero-length assertions. Read more about them here.

In your particular case, it can be solved by a positive look ahead: .+?(?=abc)

A picture is worth a thousand words. See the detail explanation in the screenshot.

Regex101 Screenshot

jQuery event to trigger action when a div is made visible

I changed the hide/show event trigger from Catalint based on Glenns idea. My problem was that I have a modular application. I change between modules showing and hiding divs parents. Then when I hide a module and show another one, with his method I have a visible delay when I change between modules. I only need sometimes to liten this event, and in some special childs. So I decided to notify only the childs with the class "displayObserver"

$.each(["show", "hide", "toggleClass", "addClass", "removeClass"], function () {
    var _oldFn = $.fn[this];
    $.fn[this] = function () {
        var hidden = this.find(".displayObserver:hidden").add(this.filter(":hidden"));
        var visible = this.find(".displayObserver:visible").add(this.filter(":visible"));
        var result = _oldFn.apply(this, arguments);
        hidden.filter(":visible").each(function () {
            $(this).triggerHandler("show");
        }); 
        visible.filter(":hidden").each(function () {
            $(this).triggerHandler("hide");
        });
        return result;
    }
});

Then when a child wants to listen for "show" or "hide" event I have to add him the class "displayObserver", and when It does not want to continue listen it, I remove him the class

bindDisplayEvent: function () {
   $("#child1").addClass("displayObserver");
   $("#child1").off("show", this.onParentShow);
   $("#child1").on("show", this.onParentShow);
},

bindDisplayEvent: function () {
   $("#child1").removeClass("displayObserver");
   $("#child1").off("show", this.onParentShow);
},

I wish help

Filter Extensions in HTML form upload

You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.

You can start with something like this:

<form name="someform"enctype="multipart/form-data" action="uploader.php" method="POST">
<input type=file name="file1" />
<input type=button onclick="val()" value="xxxx" />
</form>
<script>
function val() {
    alert(document.someform.file1.value)
}
</script>

I agree with alexmac - do it server-side as well.

Iterator Loop vs index loop

Iterators are first choice over operator[]. C++11 provides std::begin(), std::end() functions.

As your code uses just std::vector, I can't say there is much difference in both codes, however, operator [] may not operate as you intend to. For example if you use map, operator[] will insert an element if not found.

Also, by using iterator your code becomes more portable between containers. You can switch containers from std::vector to std::list or other container freely without changing much if you use iterator such rule doesn't apply to operator[].

Dump all documents of Elasticsearch

We can use elasticdump to take the backup and restore it, We can move data from one server/cluster to another server/cluster.

1. Commands to move one index data from one server/cluster to another using elasticdump.

# Copy an index from production to staging with analyzer and mapping:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=analyzer
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=data

2. Commands to move all indices data from one server/cluster to another using multielasticdump.

Backup

multielasticdump \
  --direction=dump \
  --match='^.*$' \
  --limit=10000 \
  --input=http://production.es.com:9200 \
  --output=/tmp 

Restore

multielasticdump \
  --direction=load \
  --match='^.*$' \
  --limit=10000 \
  --input=/tmp \
  --output=http://staging.es.com:9200 

Note:

  • If the --direction is dump, which is the default, --input MUST be a URL for the base location of an ElasticSearch server (i.e. http://localhost:9200) and --output MUST be a directory. Each index that does match will have a data, mapping, and analyzer file created.

  • For loading files that you have dumped from multi-elasticsearch, --direction should be set to load, --input MUST be a directory of a multielasticsearch dump and --output MUST be a Elasticsearch server URL.

  • The 2nd command will take a backup of settings, mappings, template and data itself as JSON files.

  • The --limit should not be more than 10000 otherwise, it will give an exception.

  • Get more details here.

How to convert hex string to Java string?

Try the following code:

public static byte[] decode(String hex){

        String[] list=hex.split("(?<=\\G.{2})");
        ByteBuffer buffer= ByteBuffer.allocate(list.length);
        System.out.println(list.length);
        for(String str: list)
            buffer.put(Byte.parseByte(str,16));

        return buffer.array();

}

To convert to String just create a new String with the byte[] returned by the decode method.

Phone number validation Android

We can use pattern to validate it.

android.util.Patterns.PHONE

public class GeneralUtils {

    private static boolean isValidPhoneNumber(String phoneNumber) {
        return !TextUtils.isEmpty(phoneNumber) && android.util.Patterns.PHONE.matcher(phoneNumber).matches();
    }

}

Converting to upper and lower case in Java

I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)

/**
 * Converts the given string to title case, where the first
 * letter is capitalized and the rest of the string is in
 * lower case.
 * 
 * @param s a string with unknown capitalization
 * @return a title-case version of the string
 */
public static String toTitleCase(String s)
{
    if (s.isEmpty())
    {
        return s;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.

How can I sanitize user input with PHP?

No, there is not.

First of all, SQL injection is an input filtering problem, and XSS is an output escaping one - so you wouldn't even execute these two operations at the same time in the code lifecycle.

Basic rules of thumb

  • For SQL query, bind parameters (as with PDO) or use a driver-native escaping function for query variables (such as mysql_real_escape_string())
  • Use strip_tags() to filter out unwanted HTML
  • Escape all other output with htmlspecialchars() and be mindful of the 2nd and 3rd parameters here.

How to keep footer at bottom of screen

Perhaps the easiest is to use position: absolute to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.

css:

<style>
  body {
    margin: 0 0 20px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    height: 20px;
    background: #f0f0f0;
    width: 100%;
  }
</style>

Here is the html main content.

<div class="footer"> Here is the footer. </div>

Why are hexadecimal numbers prefixed with 0x?

Short story: The 0 tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x is an arbitrary choice.

Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).

The BCPL language used the syntax 8 1234 for octal numbers. When Ken Thompson created B from BCPL, he used the 0 prefix instead. This is great because

  1. an integer constant now always consists of a single token,
  2. the parser can still tell right away it's got a constant,
  3. the parser can immediately tell the base (0 is the same in both bases),
  4. it's mathematically sane (00005 == 05), and
  5. no precious special characters are needed (as in #123).

When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x was arbitrarily chosen (00 was probably ruled out as awkward).

C# is a descendant of C, so it inherits the syntax.

Failed to locate the winutils binary in the hadoop binary path

If we directly take the binary distribution of Apache Hadoop 2.2.0 release and try to run it on Microsoft Windows, then we'll encounter ERROR util.Shell: Failed to locate the winutils binary in the hadoop binary path.

The binary distribution of Apache Hadoop 2.2.0 release does not contain some windows native components (like winutils.exe, hadoop.dll etc). These are required (not optional) to run Hadoop on Windows.

So you need to build windows native binary distribution of hadoop from source codes following "BUILD.txt" file located inside the source distribution of hadoop. You can follow the following posts as well for step by step guide with screen shot

Build, Install, Configure and Run Apache Hadoop 2.2.0 in Microsoft Windows OS

ERROR util.Shell: Failed to locate the winutils binary in the hadoop binary path

MSBUILD : error MSB1008: Only one project can be specified

If you are using Any CPU you may need to put it in single quotes.

Certainly when running in a Dockerfile, I had to use single quotes:

# Fails. Gives: MSBUILD : error MSB1008: Only one project can be specified.
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform="Any CPU" 

# Passes. Gives: Successfully built 40163c3e0121
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform='Any CPU' 

What does -z mean in Bash?

test -z returns true if the parameter is empty (see man sh or man test).

Adding a custom header to HTTP request using angular.js

You are just adding a header which server does not allow.

eg - your server is set up CORS to allow these headers only (accept,cache-control,pragma,content-type,origin)

and in your http request you are adding like this

 headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        'x-testing': 'testingValue'
    }

then the Server will reject this request since (Authorization and x-testing) are not allowed.

This is server side configuration.

And there is nothing to do with HTTP Options, it is just a preflight to server which is from different domain to check if server will allow actual call or not.

Is there a way to specify a default property value in Spring XML?

The default value can be followed with a : after the property key, e.g.

<property name="port" value="${my.server.port:8080}" />

Or in java code:

@Value("${my.server.port:8080}")
private String myServerPort;

See:

BTW, the Elvis Operator is only available within Spring Expression Language (SpEL),
e.g.: https://stackoverflow.com/a/37706167/537554

Trying to get property of non-object MySQLi result

The cause of your problem is simple. So many people will run into the same problem, Because I did too and it took me hour to figure out. Just in case, someone else stumbles, The problem is in your query, your select statement is calling $dbname instead of table name. So its not found whereby returning false which is boolean. Good luck.

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Python - Move and overwrite files and folders

You can use this to copy directory overwriting existing files:

import shutil
shutil.copytree("src", "dst", dirs_exist_ok=True)

dirs_exist_ok argument was added in Python 3.8.

See docs: https://docs.python.org/3/library/shutil.html#shutil.copytree

The import org.apache.commons cannot be resolved in eclipse juno

You could also add the external jar file to the project. Go to your project-->properties-->java build path-->libraries, add external JARS. Then add your downloaded jar file.

Java read file and store text in an array

int count = -1;
String[] content = new String[200];
while(inFile1.hasNext()){

    content[++count] = inFile1.nextLine();
}

EDIT

Looks like you want to create a float array, for that create a float array

int count = -1;
Float[] content = new Float[200];
while(inFile1.hasNext()){

    content[++count] = Float.parseFloat(inFile1.nextLine());
}

then your float array would look like

content[0] = 70.3
content[1] = 70.8
content[2] = 73.8
content[3] = 77.0 and so on

How to find and replace string?

// replaced text will be in buffer.
void Replace(char* buffer, const char* source, const char* oldStr,  const char* newStr)
{
    if(buffer==NULL || source == NULL || oldStr == NULL || newStr == NULL) return; 

    int slen = strlen(source);
    int olen = strlen(oldStr);
    int nlen = strlen(newStr);

    if(olen>slen) return;
    int ix=0;

    for(int i=0;i<slen;i++)
    {
        if(oldStr[0] == source[i])
        {
            bool found = true;
            for(int j=1;j<olen;j++)
            {
                if(source[i+j]!=oldStr[j])
                {
                    found = false;
                    break;
                }
            }

            if(found)
            {
                for(int j=0;j<nlen;j++)
                    buffer[ix++] = newStr[j];

                i+=(olen-1);
            }
            else
            {
                buffer[ix++] = source[i];
            }
        }
        else
        {
            buffer[ix++] = source[i];
        }
    }
}

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

I ran into the same issue and the above answers didn't help. I need to debug and find it.

 <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.6.0-cdh5.13.1</version>
        <exclusions>
            <exclusion>
                <artifactId>jsp-api</artifactId>
                <groupId>javax.servlet.jsp</groupId>
            </exclusion>
        </exclusions>
    </dependency>

After excluding the jsp-api, it worked for me.

How line ending conversions work with git core.autocrlf between different operating systems

Did some tests both on linux and windows. I use a test file containing lines ending in LF and also lines ending in CRLF.
File is committed , removed and then checked out. The value of core.autocrlf is set before commit and also before checkout. The result is below.

commit core.autocrlf false, remove, checkout core.autocrlf false: LF=>LF   CRLF=>CRLF  
commit core.autocrlf false, remove, checkout core.autocrlf input: LF=>LF   CRLF=>CRLF  
commit core.autocrlf false, remove, checkout core.autocrlf true : LF=>LF   CRLF=>CRLF  
commit core.autocrlf input, remove, checkout core.autocrlf false: LF=>LF   CRLF=>LF  
commit core.autocrlf input, remove, checkout core.autocrlf input: LF=>LF   CRLF=>LF  
commit core.autocrlf input, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF  
commit core.autocrlf true, remove, checkout core.autocrlf false: LF=>LF   CRLF=>LF  
commit core.autocrlf true, remove, checkout core.autocrlf input: LF=>LF   CRLF=>LF  
commit core.autocrlf true,  remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF  

Finish all activities at a time

close the app

Intent intent = new Intent(getApplicationContext(), Splash_Screen.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("EXIT", true);
                startActivity(intent);

put this in the oncreate and onResume of the very first activity that is opened. ex. is on splash screen activity

if (getIntent().getBooleanExtra("EXIT", false)) {
            this.finish();
            System.exit(0);
        }

Inconsistent accessibility: property type is less accessible

Your class Delivery has no access modifier, which means it defaults to internal. If you then try to expose a property of that type as public, it won't work. Your type (class) needs to have the same, or higher access as your property.

More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

Proper MIME type for OTF fonts

As from March 2013 IANA.ORG recommends for .otf:
application/font-sfnt

Other fonts:

.eot  ->  application/vnd.ms-fontobject (as from December 2005)
.otf  ->  application/font-sfnt         (as from March 2013)
.svg  ->  image/svg+xml                 (as from August 2011)
.ttf  ->  application/font-sfnt         (as from March 2013)
.woff ->  application/font-woff         (as from January 2013)

See more...

Static Classes In Java

What's happening when a members inside a class is declared as static..? That members can be accessed without instantiating the class. Therefore making outer class(top level class) static has no meaning. Therefore it is not allowed.

But you can set inner classes as static (As it is a member of the top level class). Then that class can be accessed without instantiating the top level class. Consider the following example.

public class A {
    public static class B {

    }
}

Now, inside a different class C, class B can be accessed without making an instance of class A.

public class C {
    A.B ab = new A.B();
}

static classes can have non-static members too. Only the class gets static.

But if the static keyword is removed from class B, it cannot be accessed directly without making an instance of A.

public class C {
    A a = new A();
    A.B ab = a. new B();
}

But we cannot have static members inside a non-static inner class.

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

You need to use an Angular form directive on the select. You can do that with ngModel. For example

@Component({
  selector: 'my-app',
  template: `
    <h2>Select demo</h2>
    <select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" >
      <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
    </select>
  `
})
class App {
  cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
  selectedCity = this.cities[1];

  onChange(city) {
    alert(city.name);
  }
}

The (ngModelChange) event listener emits events when the selected value changes. This is where you can hookup your callback.

Note you will need to make sure you have imported the FormsModule into the application.

Here is a Plunker

iOS detect if user is on an iPad

I don't think any of these answers meet my need, unless I am fundamentally misunderstanding something.

I have an app (originally an iPad app) that I want to run both on an iPad and on the Mac, under Catalyst. I'm using the plist option to scale the Mac interface to match the iPad, but would like to migrate to AppKit if that is reasonable. When running on a Mac, I believe that all of the aforementioned approaches tell me that I'm on an iPad. The Catalyst fake-out is pretty thorough.

For most concerns I indeed understand that the code should pretend it's on an iPad when thus running on a Mac. One exception is that the rolling picker is not available on the Mac under Catalyst, but is on the iPad. I want to figure out whether to create a UIPickerView or to do something different, at run time. Run-time selection is crucial because I want to use a single binary to run both on the iPad and Mac in the long term, while making the best use of the supported UI standards on each.

The APIs give potentially misleading results to the casual pre-Catalyst reader. For example, [UIDevice currentDevice].model returns @"iPad" when running under Catalyst on a Mac. The user interface idiom APIs sustain the same illusion.

I found that you really need to look deeper. I start with this information:

NSString *const deviceModel = [UIDevice currentDevice].model;
NSProcessInfo *const processInfo = [[NSProcessInfo alloc] init];
const bool isIosAppOnMac = processInfo.iOSAppOnMac;  // Note: this will be "no" under Catalyst
const bool isCatalystApp = processInfo.macCatalystApp;

Then you can combine these queries with expressions like [deviceModel hasPrefix: @"iPad"] to sort out the kinds of subtleties I'm facing. For my case, I explicitly want to avoid making a UIPickerView if the indicated isCatalystApp is true, independent of "misleading" information about the interface idiom, or the illusions sustained by isIosAppOnMac and deviceModel.

Now I'm curious what happens if I move the Mac app to run over on my iPad sidecar...

Length of array in function argument

The array decays to a pointer when passed.

Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.


That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).

Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?


Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.

You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.

How many bits is a "word"?

The second quote is correct, the size of a word varies from computer to computer. The ARM NEON architecture is an example of an architecture with 32-bit words, where 64-bit quantities are referred to as "doublewords" and 128-bit quantities are referred to as "quadwords":

A NEON operand can be a vector or a scalar. A NEON vector can be a 64-bit doubleword vector or a 128-bit quadword vector.

Normally speaking, 16-bit words are only found on 16-bit systems, like the Amiga 500.

How to implement a SQL like 'LIKE' operator in java?

Every SQL reference I can find says the "any single character" wildcard is the underscore (_), not the question mark (?). That simplifies things a bit, since the underscore is not a regex metacharacter. However, you still can't use Pattern.quote() for the reason given by mmyers. I've got another method here for escaping regexes when I might want to edit them afterward. With that out of the way, the like() method becomes pretty simple:

public static boolean like(final String str, final String expr)
{
  String regex = quotemeta(expr);
  regex = regex.replace("_", ".").replace("%", ".*?");
  Pattern p = Pattern.compile(regex,
      Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
  return p.matcher(str).matches();
}

public static String quotemeta(String s)
{
  if (s == null)
  {
    throw new IllegalArgumentException("String cannot be null");
  }

  int len = s.length();
  if (len == 0)
  {
    return "";
  }

  StringBuilder sb = new StringBuilder(len * 2);
  for (int i = 0; i < len; i++)
  {
    char c = s.charAt(i);
    if ("[](){}.*+?$^|#\\".indexOf(c) != -1)
    {
      sb.append("\\");
    }
    sb.append(c);
  }
  return sb.toString();
}

If you really want to use ? for the wildcard, your best bet would be to remove it from the list of metacharacters in the quotemeta() method. Replacing its escaped form -- replace("\\?", ".") -- wouldn't be safe because there might be backslashes in the original expression.

And that brings us to the real problems: most SQL flavors seem to support character classes in the forms [a-z] and [^j-m] or [!j-m], and they all provide a way to escape wildcard characters. The latter is usually done by means of an ESCAPE keyword, which lets you define a different escape character every time. As you can imagine, this complicates things quite a bit. Converting to a regex is probably still the best option, but parsing the original expression will be much harder--in fact, the first thing you would have to do is formalize the syntax of the LIKE-like expressions themselves.

How to catch a unique constraint error in a PL/SQL block?

As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */ in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.

Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME which has a unique constraint on a column called IDX_COL_NAME.

INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */ 
INTO TABLE_NAME(
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n)
SELECT 
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n);

This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

You can do it from Visual Studio during debugging without writing any code, not even a catch block.

Just add a watch with the name:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

The watch expression $exception displays any exception thrown in the current context, even if it has not been caught and assigned to a variable.

Based on http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/

CSS3 gradient background set on body doesn't stretch but instead repeats?

Here's what I did to solve this problem... it will show the gradient for the full length of the content, then simply fallback to the background color (normally the last color in the gradient).

_x000D_
_x000D_
   html {_x000D_
     background: #cbccc8;_x000D_
   }_x000D_
   body {_x000D_
     background-repeat: no-repeat;_x000D_
     background: #cbccc8;_x000D_
     background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbccc8));_x000D_
     background: -moz-linear-gradient(top, #fff, #cbccc8);_x000D_
     filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#cbccc8');_x000D_
   }
_x000D_
<body>_x000D_
  <h1>Hello world!</h1>_x000D_
</body>
_x000D_
_x000D_
_x000D_

I've tested this in FireFox 3.6, Safari 4, and Chrome, I keep the background-color in the body for any browsers that for some reason don't support styling the HTML tag.

List all the files and folders in a Directory with PHP recursive function

To whom needs list files first than folders (with alphabetical older).

Can use following function. This is not self calling function. So you will have directory list, directory view, files list and folders list as seperated array also.

I spend two days for this and do not want someone will wast his time for this also, hope helps someone.

function dirlist($dir){
    if(!file_exists($dir)){ return $dir.' does not exists'; }
    $list = array('path' => $dir, 'dirview' => array(), 'dirlist' => array(), 'files' => array(), 'folders' => array());

    $dirs = array($dir);
    while(null !== ($dir = array_pop($dirs))){
        if($dh = opendir($dir)){
            while(false !== ($file = readdir($dh))){
                if($file == '.' || $file == '..') continue;
                $path = $dir.DIRECTORY_SEPARATOR.$file;
                $list['dirlist_natural'][] = $path;
                if(is_dir($path)){
                    $list['dirview'][$dir]['folders'][] = $path;
                    // Bos klasorler while icerisine tekrar girmeyecektir. Klasorun oldugundan emin olalim.
                    if(!isset($list['dirview'][$path])){ $list['dirview'][$path] = array(); }
                    $dirs[] = $path;
                    //if($path == 'D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-content\upgrade'){ press($path); press($list['dirview']); die; }
                }
                else{
                    $list['dirview'][$dir]['files'][] = $path;
                }
            }
            closedir($dh);
        }
    }

    // if(!empty($dirlist['dirlist_natural']))  sort($dirlist['dirlist_natural'], SORT_LOCALE_STRING); // delete safe ama gerek kalmadi.

    if(!empty($list['dirview'])) ksort($list['dirview']);

    // Dosyalari dogru siralama yaptiriyoruz. Deniz P. - info[at]netinial.com
    foreach($list['dirview'] as $path => $file){
        if(isset($file['files'])){
            $list['dirlist'][] = $path;
            $list['files'] = array_merge($list['files'], $file['files']);
            $list['dirlist'] = array_merge($list['dirlist'], $file['files']);
        }
        // Add empty folders to the list
        if(is_dir($path) && array_search($path, $list['dirlist']) === false){
            $list['dirlist'][] = $path;
        }
        if(isset($file['folders'])){
            $list['folders'] = array_merge($list['folders'], $file['folders']);
        }
    }

    //press(array_diff($list['dirlist_natural'], $list['dirlist'])); press($list['dirview']); die;

    return $list;
}

will output something like this.

[D:\Xampp\htdocs\exclusiveyachtcharter.localhost] => Array
                (
                    [files] => Array
                        (
                            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\.htaccess
                            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\index.php
                            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\license.txt
                            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\php.php
                            [4] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\readme.html
                            [5] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-activate.php
                            [6] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-blog-header.php
                            [7] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-comments-post.php
                            [8] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config-sample.php
                            [9] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config.php
                            [10] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-cron.php
                            [11] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-links-opml.php
                            [12] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-load.php
                            [13] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-login.php
                            [14] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-mail.php
                            [15] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-settings.php
                            [16] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-signup.php
                            [17] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-trackback.php
                            [18] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\xmlrpc.php
                        )

                    [folders] => Array
                        (
                            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql
                            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-admin
                            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-content
                            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-includes
                        )

                )

dirview output

    [dirview] => Array
        (
            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\.htaccess
            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\index.php
            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\license.txt
            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\php.php
            [4] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\readme.html
            [5] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-activate.php
            [6] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-blog-header.php
            [7] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-comments-post.php
            [8] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config-sample.php
            [9] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config.php
            [10] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-cron.php
            [11] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-links-opml.php
            [12] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-load.php
            [13] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-login.php
            [14] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-mail.php
            [15] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-settings.php
            [16] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-signup.php
            [17] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-trackback.php
            [18] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\xmlrpc.php
            [19] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost
            [20] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql\exclusiv_excluwl.sql
            [21] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql\exclusiv_excluwl.sql.zip
            [22] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql
)

Updates were rejected because the tip of your current branch is behind its remote counterpart

I had this issue when trying to push after a rebase through Visual Studio Code, my issue was solved by just copying the command from the git output window and executing it from the terminal window in Visual Studio Code.

In my case the command was something like:

git push origin NameOfMyBranch:NameOfMyBranch

Use superscripts in R axis labels

The other option in this particular case would be to type the degree symbol: °

R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.

How do I change the font-size of an <option> element within <select>?

.service-small option {
    font-size: 14px;
    padding: 5px;
    background: #5c5c5c;
}

I think it because you used .styled-select in start of the class code.

Most popular screen sizes/resolutions on Android phones

There is now official Device Metrics on the Material Design site, those metrics are a hand picked devices list, not an actual statistics, but it too can be really helpful: https://material.io/devices/

react hooks useEffect() cleanup for only componentWillUnmount?

you can use more than one useEffect

for example if my variable is data1 i can use all of this in my component

useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

So far, the accepted answer has worked best for me. However, my concern has always been that there is a likely scenario where I might refactor the notebooks directory into subdirectories, requiring to change the module_path in every notebook. I decided to add a python file within each notebook directory to import the required modules.

Thus, having the following project structure:

project
|__notebooks
   |__explore
      |__ notebook1.ipynb
      |__ notebook2.ipynb
      |__ project_path.py
   |__ explain
       |__notebook1.ipynb
       |__project_path.py
|__lib
   |__ __init__.py
   |__ module.py

I added the file project_path.py in each notebook subdirectory (notebooks/explore and notebooks/explain). This file contains the code for relative imports (from @metakermit):

import sys
import os

module_path = os.path.abspath(os.path.join(os.pardir, os.pardir))
if module_path not in sys.path:
    sys.path.append(module_path)

This way, I just need to do relative imports within the project_path.py file, and not in the notebooks. The notebooks files would then just need to import project_path before importing lib. For example in 0.0-notebook.ipynb:

import project_path
import lib

The caveat here is that reversing the imports would not work. THIS DOES NOT WORK:

import lib
import project_path

Thus care must be taken during imports.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

What is the difference between bottom-up and top-down?

Dynamic programming problems can be solved using either bottom-up or top-down approaches.

Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.

But you can also have bottom-up and top-down approaches using recursion as shown below.

Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.

int n = 5;
fibBottomUp(1, 1, 2, n);

private int fibBottomUp(int i, int j, int count, int n) {
    if (count > n) return 1;
    if (count == n) return i + j;
    return fibBottomUp(j, i + j, count + 1, n);
}

Top-Down: Start with the final condition and recursively get the result of its sub-problems.

int n = 5;
fibTopDown(n);

private int fibTopDown(int n) {
    if (n <= 1) return 1;
    return fibTopDown(n - 1) + fibTopDown(n - 2);
}

How to get child element by index in Jquery?

Doesn't nth-child return siblings rather than children?

var $selFirst = $(".second:nth-child(1)");

will return the first element with the class '.second'.

var $selFirst = $(".selector:nth-child(1)");

should give you the first sibling of class '.selector'

List(of String) or Array or ArrayList

Sometimes I don't want to add items to a list when I instantiate it.

Instantiate a blank list

Dim blankList As List(Of String) = New List(Of String)

Add to the list

blankList.Add("Dis be part of me list") 'blankList is no longer blank, but you get the drift

Loop through the list

For Each item in blankList
  ' write code here, for example:
  Console.WriteLine(item)
Next

Deleting all files in a directory with Python

Use os.chdir to change directory . Use glob.glob to generate a list of file names which end it '.bak'. The elements of the list are just strings.

Then you could use os.unlink to remove the files. (PS. os.unlink and os.remove are synonyms for the same function.)

#!/usr/bin/env python
import glob
import os
directory='/path/to/dir'
os.chdir(directory)
files=glob.glob('*.bak')
for filename in files:
    os.unlink(filename)

How should I throw a divide by zero exception in Java without actually dividing by zero?

There are two ways you could do this. Either create your own custom exception class to represent a divide by zero error or throw the same type of exception the java runtime would throw in this situation.

Define custom exception

public class DivideByZeroException() extends ArithmeticException {
}

Then in your code you would check for a divide by zero and throw this exception:

if (divisor == 0) throw new DivideByZeroException();

Throw ArithmeticException

Add to your code the check for a divide by zero and throw an arithmetic exception:

if (divisor == 0) throw new java.lang.ArithmeticException("/ by zero");

Additionally, you could consider throwing an illegal argument exception since a divisor of zero is an incorrect argument to pass to your setKp() method:

if (divisor == 0) throw new java.lang.IllegalArgumentException("divisor == 0");

SQL query to find Nth highest salary from a salary table

For 4th highest salary:

select min(salary) from (select distinct salary from hibernatepractice.employee e order by salary desc limit 4) as e1;

For n th highest salary:

select min(salary) from (select distinct salary from hibernatepractice.employee e order by salary desc limit n) as e1;

How to delete a localStorage item when the browser window/tab is closed?

Use with window global keyword:-

 window.localStorage.removeItem('keyName');

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

How can I change the image of an ImageView?

If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
  >

  <ImageView
      android:id="@+id/image"
      android:layout_width="50dip"
      android:layout_height="fill_parent" 
      android:src="@drawable/icon"
      android:layout_marginLeft="3dip"
      android:scaleType="center"/>

</LinearLayout>

Step 2: create an Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

Solution 2:

If you created imageview from Java Class

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);

HTML character codes for this ? or this ?

Check this page http://www.alanwood.net/unicode/geometric_shapes.html, first is "9650 ? 25B2 BLACK UP-POINTING TRIANGLE (present in WGL4)" and 2nd "9660 ? 25BC BLACK DOWN-POINTING TRIANGLE (present in WGL4)".

How to set proxy for wget?

In Debian Linux wget can be configured to use a proxy both via environment variables and via wgetrc. In both cases the variable names to be used for HTTP and HTTPS connections are

http_proxy=hostname_or_IP:portNumber
https_proxy=hostname_or_IP:portNumber

Note that the file /etc/wgetrc takes precedence over the environment variables, hence if your system has a proxy configured there and you try to use the environment variables, they would seem to have no effect!

Best Practices for Custom Helpers in Laravel 5

in dir bootstrap\autoload.php

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add

add this file

app\Helpers\function.php

How to convert a timezone aware string to datetime in Python without dateutil?

Here is the Python Doc for datetime object using dateutil package..

from dateutil.parser import parse

get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj

TypeError: $.ajax(...) is not a function?

For anyone trying to run this in nodejs: It won't work out of the box, since jquery needs a browser (or similar)! I was just trying to get the import to run and was logging console.log($) which wrote [Function] and then also console.log($.ajax) which returned undefined. I had no tsc errors and had autocomplete from intellij, so I was wondering what's going on.

Then at some point I realised that node might be the problem and not typescript. I tried the same code in the browser and it worked. To make it work you need to run:

require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

(credits: https://stackoverflow.com/a/4129032/3022127)

How to delete a line from a text file in C#?

I extended what Markus Olsson suggested, and came up with this class that adds multiple search strings and a couple of event:

public static class TextLineRemover
{
    public static void RemoveTextLines(IList<string> linesToRemove, string filename, string tempFilename)
    {
        // Initial values
        int lineNumber = 0;
        int linesRemoved = 0;
        DateTime startTime = DateTime.Now;

        // Read file
        using (var sr = new StreamReader(filename))
        {
            // Write new file
            using (var sw = new StreamWriter(tempFilename))
            {
                // Read lines
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    lineNumber++;
                    // Look for text to remove
                    if (!ContainsString(line, linesToRemove))
                    {
                        // Keep lines that does not match
                        sw.WriteLine(line);
                    }
                    else
                    {
                        // Ignore lines that DO match
                        linesRemoved++;
                        InvokeOnRemovedLine(new RemovedLineArgs { RemovedLine = line, RemovedLineNumber = lineNumber});
                    }
                }
            }
        }
        // Delete original file
        File.Delete(filename);

        // ... and put the temp file in its place.
        File.Move(tempFilename, filename);

        // Final calculations
        DateTime endTime = DateTime.Now;
        InvokeOnFinished(new FinishedArgs {LinesRemoved = linesRemoved, TotalLines = lineNumber, TotalTime = endTime.Subtract(startTime)});
    }

    private static bool ContainsString(string line, IEnumerable<string> linesToRemove)
    {
        foreach (var lineToRemove in linesToRemove)
        {
            if(line.Contains(lineToRemove))
                return true;
        }
        return false;
    }

    public static event RemovedLine OnRemovedLine;
    public static event Finished OnFinished;

    public static void InvokeOnFinished(FinishedArgs args)
    {
        Finished handler = OnFinished;
        if (handler != null) handler(null, args);
    }

    public static void InvokeOnRemovedLine(RemovedLineArgs args)
    {
        RemovedLine handler = OnRemovedLine;
        if (handler != null) handler(null, args);
    }
}

public delegate void Finished(object sender, FinishedArgs args);

public class FinishedArgs
{
    public int TotalLines { get; set; }
    public int LinesRemoved { get; set; }
    public TimeSpan TotalTime { get; set; }
}

public delegate void RemovedLine(object sender, RemovedLineArgs args);

public class RemovedLineArgs
{
    public string RemovedLine { get; set; }
    public int RemovedLineNumber { get; set; }
}

Usage:

TextLineRemover.OnRemovedLine += (o, removedLineArgs) => Console.WriteLine(string.Format("Removed \"{0}\" at line {1}", removedLineArgs.RemovedLine, removedLineArgs.RemovedLineNumber));
TextLineRemover.OnFinished += (o, finishedArgs) => Console.WriteLine(string.Format("{0} of {1} lines removed. Time used: {2}", finishedArgs.LinesRemoved, finishedArgs.TotalLines, finishedArgs.TotalTime.ToString()));
TextLineRemover.RemoveTextLines(new List<string> { "aaa", "bbb" }, fileName, fileName + ".tmp");

Add/Delete table rows dynamically using JavaScript

You can add a row to a table in the most easiest way like this :-

I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .

row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;

Here #table_body is the id of the table body tag .

Generate insert script for selected records?

I ended up doing this in 2 steps. Selected the records I want into a new table in the database then generated a SQL data only script in SSMS. I did find and replace on the generated script and removed the table.

Find a file in python

The answer is very similar to existing ones, but slightly optimized.

So you can find any files or folders by pattern:

def iter_all(pattern, path):
    return (
        os.path.join(root, entry)
        for root, dirs, files in os.walk(path)
        for entry in dirs + files
        if pattern.match(entry)
    )

either by substring:

def iter_all(substring, path):
    return (
        os.path.join(root, entry)
        for root, dirs, files in os.walk(path)
        for entry in dirs + files
        if substring in entry
    )

or using a predicate:

def iter_all(predicate, path):
    return (
        os.path.join(root, entry)
        for root, dirs, files in os.walk(path)
        for entry in dirs + files
        if predicate(entry)
    )

to search only files or only folders - replace “dirs + files”, for example, with only “dirs” or only “files”, depending on what you need.

Regards.

Drawing circles with System.Drawing

You should use DrawEllipse:

//
// Summary:
//     Draws an ellipse defined by a bounding rectangle specified by coordinates
//     for the upper-left corner of the rectangle, a height, and a width.
//
// Parameters:
//   pen:
//     System.Drawing.Pen that determines the color, width,
//      and style of the ellipse.
//
//   x:
//     The x-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   y:
//     The y-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   width:
//     Width of the bounding rectangle that defines the ellipse.
//
//   height:
//     Height of the bounding rectangle that defines the ellipse.
//
// Exceptions:
//   System.ArgumentNullException:
//     pen is null.
public void DrawEllipse(Pen pen, int x, int y, int width, int height);

How to Identify port number of SQL server

  1. Open Run in your system.

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

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

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

  5. Click the Properties button.

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

enter image description here

Best way to get the max value in a Spark dataframe column

Remark: Spark is intended to work on Big Data - distributed computing. The size of the example DataFrame is very small, so the order of real-life examples can be altered with respect to the small ~ example.

Slowest: Method_1, because .describe("A") calculates min, max, mean, stddev, and count (5 calculations over the whole column)

Medium: Method_4, because, .rdd (DF to RDD transformation) slows down the process.

Faster: Method_3 ~ Method_2 ~ method_5, because the logic is very similar, so Spark's catalyst optimizer follows very similar logic with minimal number of operations (get max of a particular column, collect a single-value dataframe); (.asDict() adds a little extra-time comparing 3,2 to 5)

import pandas as pd
import time

time_dict = {}

dfff = self.spark.createDataFrame([(1., 4.), (2., 5.), (3., 6.)], ["A", "B"])
#--  For bigger/realistic dataframe just uncomment the following 3 lines
#lst = list(np.random.normal(0.0, 100.0, 100000))
#pdf = pd.DataFrame({'A': lst, 'B': lst, 'C': lst, 'D': lst})
#dfff = self.sqlContext.createDataFrame(pdf)

tic1 = int(round(time.time() * 1000))
# Method 1: Use describe()
max_val = float(dfff.describe("A").filter("summary = 'max'").select("A").collect()[0].asDict()['A'])
tac1 = int(round(time.time() * 1000))
time_dict['m1']= tac1 - tic1
print (max_val)

tic2 = int(round(time.time() * 1000))
# Method 2: Use SQL
dfff.registerTempTable("df_table")
max_val = self.sqlContext.sql("SELECT MAX(A) as maxval FROM df_table").collect()[0].asDict()['maxval']
tac2 = int(round(time.time() * 1000))
time_dict['m2']= tac2 - tic2
print (max_val)

tic3 = int(round(time.time() * 1000))
# Method 3: Use groupby()
max_val = dfff.groupby().max('A').collect()[0].asDict()['max(A)']
tac3 = int(round(time.time() * 1000))
time_dict['m3']= tac3 - tic3
print (max_val)

tic4 = int(round(time.time() * 1000))
# Method 4: Convert to RDD
max_val = dfff.select("A").rdd.max()[0]
tac4 = int(round(time.time() * 1000))
time_dict['m4']= tac4 - tic4
print (max_val)

tic5 = int(round(time.time() * 1000))
# Method 4: Convert to RDD
max_val = dfff.agg({"A": "max"}).collect()[0][0]
tac5 = int(round(time.time() * 1000))
time_dict['m5']= tac5 - tic5
print (max_val)

print time_dict

Result on an edge-node of a cluster in milliseconds (ms):

small DF (ms) : {'m1': 7096, 'm2': 205, 'm3': 165, 'm4': 211, 'm5': 180}

bigger DF (ms): {'m1': 10260, 'm2': 452, 'm3': 465, 'm4': 916, 'm5': 373}

Toggle Checkboxes on/off

//this toggles the checkbox, and fires its event if it has    

$('input[type=checkbox]').trigger('click'); 
//or
$('input[type=checkbox]').click(); 

Getting the absolute path of the executable, using C#?

AppDomain.CurrentDomain.BaseDirectory

Where can I find Android source code online?

gitweb will allow you to browse through the code (and changes) via a browser.

http://git.or.cz/gitwiki/Gitweb

(Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)

How to obtain the number of CPUs/cores in Linux from the command line?

For the total number of physical cores:

grep '^core id' /proc/cpuinfo |sort -u|wc -l

On multiple-socket machines (or always), multiply the above result by the number of sockets:

echo $(($(grep "^physical id" /proc/cpuinfo | awk '{print $4}' | sort -un | tail -1)+1))

@mklement0 has quite a nice answer below using lscpu. I have written a more succinct version in the comments

How do I UPDATE from a SELECT in SQL Server?

Using alias:

UPDATE t
   SET t.col1 = o.col1
  FROM table1 AS t
         INNER JOIN 
       table2 AS o 
         ON t.id = o.id

How do I do multiple CASE WHEN conditions using SQL Server 2008?

There are two formats of case expression. You can do CASE with many WHEN as;

CASE  WHEN Col1 = 1 OR Col3 = 1  THEN 1 
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

Or a Simple CASE expression

CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END

Or CASE within CASE as;

CASE  WHEN Col1 < 2 THEN  
                    CASE Col2 WHEN 'X' THEN 10 ELSE 11 END
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

Why doesn't git recognize that my file has been changed, therefore git add not working

I had this issue. Mine wasn't working because I was putting my files in the .git folder inside my project.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

What is the canonical way to check for errors using the CUDA runtime API?

talonmies' answer above is a fine way to abort an application in an assert-style manner.

Occasionally we may wish to report and recover from an error condition in a C++ context as part of a larger application.

Here's a reasonably terse way to do that by throwing a C++ exception derived from std::runtime_error using thrust::system_error:

#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
#include <sstream>

void throw_on_cuda_error(cudaError_t code, const char *file, int line)
{
  if(code != cudaSuccess)
  {
    std::stringstream ss;
    ss << file << "(" << line << ")";
    std::string file_and_line;
    ss >> file_and_line;
    throw thrust::system_error(code, thrust::cuda_category(), file_and_line);
  }
}

This will incorporate the filename, line number, and an English language description of the cudaError_t into the thrown exception's .what() member:

#include <iostream>

int main()
{
  try
  {
    // do something crazy
    throw_on_cuda_error(cudaSetDevice(-1), __FILE__, __LINE__);
  }
  catch(thrust::system_error &e)
  {
    std::cerr << "CUDA error after cudaSetDevice: " << e.what() << std::endl;

    // oops, recover
    cudaSetDevice(0);
  }

  return 0;
}

The output:

$ nvcc exception.cu -run
CUDA error after cudaSetDevice: exception.cu(23): invalid device ordinal

A client of some_function can distinguish CUDA errors from other kinds of errors if desired:

try
{
  // call some_function which may throw something
  some_function();
}
catch(thrust::system_error &e)
{
  std::cerr << "CUDA error during some_function: " << e.what() << std::endl;
}
catch(std::bad_alloc &e)
{
  std::cerr << "Bad memory allocation during some_function: " << e.what() << std::endl;
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
catch(...)
{
  std::cerr << "Some other kind of error during some_function" << std::endl;

  // no idea what to do, so just rethrow the exception
  throw;
}

Because thrust::system_error is a std::runtime_error, we can alternatively handle it in the same manner of a broad class of errors if we don't require the precision of the previous example:

try
{
  // call some_function which may throw something
  some_function();
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}

OR condition in Regex

I think what you need might be simply:

\d( \w)?

Note that your regex would have worked too if it was written as \d \w|\d instead of \d|\d \w.

This is because in your case, once the regex matches the first option, \d, it ceases to search for a new match, so to speak.

How to use filter, map, and reduce in Python 3

Here are the examples of Filter, map and reduce functions.

numbers = [10,11,12,22,34,43,54,34,67,87,88,98,99,87,44,66]

//Filter

oddNumbers = list(filter(lambda x: x%2 != 0, numbers))

print(oddNumbers)

//Map

multiplyOf2 = list(map(lambda x: x*2, numbers))

print(multiplyOf2)

//Reduce

The reduce function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools module, so you can do:

from functools import reduce

sumOfNumbers = reduce(lambda x,y: x+y, numbers)

print(sumOfNumbers)

How to distinguish between left and right mouse click with jQuery

$("body").on({
    click: function(){alert("left click");},
    contextmenu: function(){alert("right click");}   
});

How to convert C++ Code to C

There is indeed such a tool, Comeau's C++ compiler. . It will generate C code which you can't manually maintain, but that's no problem. You'll maintain the C++ code, and just convert to C on the fly.

Load CSV file with Spark

If you are having any one or more row(s) with less or more number of columns than 2 in the dataset then this error may arise.

I am also new to Pyspark and trying to read CSV file. Following code worked for me:

In this code I am using dataset from kaggle the link is: https://www.kaggle.com/carrie1/ecommerce-data

1. Without mentioning the schema:

from pyspark.sql import SparkSession  
scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example: Reading CSV file without mentioning schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",")
sdfData.show()

Now check the columns: sdfData.columns

Output will be:

['InvoiceNo', 'StockCode','Description','Quantity', 'InvoiceDate', 'CustomerID', 'Country']

Check the datatype for each column:

sdfData.schema
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,StringType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,StringType,true),StructField(CustomerID,StringType,true),StructField(Country,StringType,true)))

This will give the data frame with all the columns with datatype as StringType

2. With schema: If you know the schema or want to change the datatype of any column in the above table then use this (let's say I am having following columns and want them in a particular data type for each of them)

from pyspark.sql import SparkSession  
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
    schema = StructType([\
        StructField("InvoiceNo", IntegerType()),\
        StructField("StockCode", StringType()), \
        StructField("Description", StringType()),\
        StructField("Quantity", IntegerType()),\
        StructField("InvoiceDate", StringType()),\
        StructField("CustomerID", DoubleType()),\
        StructField("Country", StringType())\
    ])

scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL example: Reading CSV file with schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",", schema=schema)

Now check the schema for datatype of each column:

sdfData.schema

StructType(List(StructField(InvoiceNo,IntegerType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(CustomerID,DoubleType,true),StructField(Country,StringType,true)))

Edited: We can use the following line of code as well without mentioning schema explicitly:

sdfData = scSpark.read.csv("data.csv", header=True, inferSchema = True)
sdfData.schema

The output is:

StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,DoubleType,true),StructField(CustomerID,IntegerType,true),StructField(Country,StringType,true)))

The output will look like this:

sdfData.show()

+---------+---------+--------------------+--------+--------------+----------+-------+
|InvoiceNo|StockCode|         Description|Quantity|   InvoiceDate|CustomerID|Country|
+---------+---------+--------------------+--------+--------------+----------+-------+
|   536365|   85123A|WHITE HANGING HEA...|       6|12/1/2010 8:26|      2.55|  17850|
|   536365|    71053| WHITE METAL LANTERN|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84406B|CREAM CUPID HEART...|       8|12/1/2010 8:26|      2.75|  17850|
|   536365|   84029G|KNITTED UNION FLA...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84029E|RED WOOLLY HOTTIE...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|    22752|SET 7 BABUSHKA NE...|       2|12/1/2010 8:26|      7.65|  17850|
|   536365|    21730|GLASS STAR FROSTE...|       6|12/1/2010 8:26|      4.25|  17850|
|   536366|    22633|HAND WARMER UNION...|       6|12/1/2010 8:28|      1.85|  17850|
|   536366|    22632|HAND WARMER RED P...|       6|12/1/2010 8:28|      1.85|  17850|
|   536367|    84879|ASSORTED COLOUR B...|      32|12/1/2010 8:34|      1.69|  13047|
|   536367|    22745|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22748|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22749|FELTCRAFT PRINCES...|       8|12/1/2010 8:34|      3.75|  13047|
|   536367|    22310|IVORY KNITTED MUG...|       6|12/1/2010 8:34|      1.65|  13047|
|   536367|    84969|BOX OF 6 ASSORTED...|       6|12/1/2010 8:34|      4.25|  13047|
|   536367|    22623|BOX OF VINTAGE JI...|       3|12/1/2010 8:34|      4.95|  13047|
|   536367|    22622|BOX OF VINTAGE AL...|       2|12/1/2010 8:34|      9.95|  13047|
|   536367|    21754|HOME BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21755|LOVE BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21777|RECIPE BOX WITH M...|       4|12/1/2010 8:34|      7.95|  13047|
+---------+---------+--------------------+--------+--------------+----------+-------+
only showing top 20 rows

Playing a MP3 file in a WinForm application

  1. first go to the properties of your project
  2. click on add references
  3. add the library under COM object for window media player then type your code where you want


    Source:

        WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
    
        wplayer.URL = @"C:\Users\Adil M\Documents\Visual Studio 2012\adil.mp3";
        wplayer.controls.play();
    

Using success/error/finally/catch with Promises in AngularJS

In Angular $http case, the success() and error() function will have response object been unwrapped, so the callback signature would be like $http(...).success(function(data, status, headers, config))

for then(), you probably will deal with the raw response object. such as posted in AngularJS $http API document

$http({
        url: $scope.url,
        method: $scope.method,
        cache: $templateCache
    })
    .success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    })
    .error(function(data, status) {
        $scope.data = data || 'Request failed';
        $scope.status = status;
    });

The last .catch(...) will not need unless there is new error throw out in previous promise chain.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to generate auto increment field in select query

If it is MySql you can try

SELECT @n := @n + 1 n,
       first_name, 
       last_name
  FROM table1, (SELECT @n := 0) m
 ORDER BY first_name, last_name

SQLFiddle

And for SQLServer

SELECT row_number() OVER (ORDER BY first_name, last_name) n,
       first_name, 
       last_name 
  FROM table1 

SQLFiddle

How to show android checkbox at right side?

You can do

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right|center"//or "center_vertical" for center text
android:layoutDirection="rtl"
android:text="hello" />

Following line is enough

android:layoutDirection="rtl"

How to convert Strings to and from UTF8 byte arrays in Java

//query is your json   

 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy=");

 StringEntity input = new StringEntity(query, "UTF-8");
 input.setContentType("application/json");
 postRequest.setEntity(input);   
 HttpResponse response=response = httpClient.execute(postRequest);

Tkinter understanding mainloop

I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).

In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!

As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.

import Tkinter as tk

class Window(tk.Frame):
    def __init__(self, master=None, view=None ):
        tk.Frame.__init__( self, master )
        self.view_ = view       
        """ Setup window linking it to the view... """

class GuiView( MyViewSuperClass ):

    def open( self ):
        self.tkRoot_ = tk.Tk()
        self.window_ = Window( master=None, view=self )
        self.window_.pack()
        self.refresh()
        self.onOpen()
        self.tkRoot_.mainloop()         

    def onOpen( self ):        
        """ Do some initial tasks... """

    def refresh( self ):        
        self.tkRoot_.update()

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

The transaction manager has disabled its support for remote/network transactions

I was having this issue with a linked server in SSMS while trying to create a stored procedure.

On the linked server, I changed the server option "Enable Promotion on Distributed Transaction" to False.

Screenshot of Server Options

How to update a pull request from forked repo?

I did it using below steps:

  1. git reset --hard <commit key of the pull request>
  2. Did my changes in code I wanted to do
  3. git add
  4. git commit --amend
  5. git push -f origin <name of the remote branch of pull request>

Parse error: Syntax error, unexpected end of file in my PHP code

Avoid this as well <? } ?> make sure you put <?php } ?>

Removing numbers from string

And, just to throw it in the mix, is the oft-forgotten str.translate which will work a lot faster than looping/regular expressions:

For Python 2:

from string import digits

s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'

For Python 3:

from string import digits

s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'

Code coverage with Mocha

You need an additional library for code coverage, and you are going to be blown away by how powerful and easy istanbul is. Try the following, after you get your mocha tests to pass:

npm install nyc

Now, simply place the command nyc in front of your existing test command, for example:

{
  "scripts": {
    "test": "nyc mocha"
  }
}

Best way to change the background color for an NSView

Think I figured out how to do it:

- (void)drawRect:(NSRect)dirtyRect {
    // Fill in background Color
    CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
    CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}

if A vs if A is not None:

The statement

if A:

will call A.__nonzero__() (see Special method names documentation) and use the return value of that function. Here's the summary:

object.__nonzero__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __nonzero__(), all its instances are considered true.

On the other hand,

if A is not None:

compares only the reference A with None to see whether it is the same or not.

Removing whitespace from strings in Java

public static void main(String[] args) {        
    String s = "name=john age=13 year=2001";
    String t = s.replaceAll(" ", "");
    System.out.println("s: " + s + ", t: " + t);
}

Output:
s: name=john age=13 year=2001, t: name=johnage=13year=2001

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

In Servlet technology if you want to pass any input to a particular servlet then you need to pass in init param like below code.

 <servlet>
    <servlet-name>DBController</servlet-name>
    <servlet-class>com.test.controller.DBController</servlet-class>
    <init-param>
        <param-name>username</param-name>
        <param-value>John</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>DBController</servlet-name>
    <url-pattern>/DBController</url-pattern>
</servlet-mapping>

If you want to pass some in put that is common for all servlets then that time you need to configure context param. Example

 <context-param>
    <param-name>email</param-name>
    <param-value>[email protected]</param-value>
</context-param>

SO exactly like this when ever we are working with Spring MVC we need to provide some information to Predefined servlet provided by Spring that is DispatcherServlet through init param. So the configuration is as fallows, here we are providing the spring-servlet.xml as init parameter to DispatcherServlet.

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>Spring MVC App</display-name>

    <servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
</web-app>

Again we need some context param. That is applicable for whole application. So we can provide the root context that is applicationcontext.xml The configuration is like this:

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationcontext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

"rm -rf" equivalent for Windows?

There is also deltree if you're on an older version of windows.

You can learn more about it from here: SS64: DELTREE - Delete all subfolders and files.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.

For an array:

var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();

As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.

But as we all know JavaScript is strange, so here are some weird bits:

array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!

This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.

So what are Objects?

Objects in JavaScript are just like arrays but the "index" can be any string.

var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK

You can even opt to not use the square brackets when working with objects!

console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";

You can go even further and define objects like so:

var newObject = {
    a: 2,
};
newObject.a === 2; // true

brew install mysql on macOS

I had the same issue after I tried to restart mysql.

I use the following two aliases in my .profile for convenience

alias mysql-stop='launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist'
alias mysql-start='launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist' 

After stoping mysql and then trying to restart I experienced the issue you were having. I looked into the launchctl load and it was reporting a “nothing found to load” error.

After a quick search I found this..

http://www.daveoncode.com/2013/02/01/solve-mac-osx-launchctl-nothing-found-to-load-error/

So I updated me mysql-start alias as follows

alias mysql-start='launchctl load -w -F ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist'

This solved my issue which may be useful for you.

C/C++ include header file order

First include the header corresponding to the .cpp... in other words, source1.cpp should include source1.h before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h before anything else.

Reasoning: Including the source1.h before any other files ensures that it can stand alone without it's dependencies. If source1.h takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h. This in turn ensures that headers can be included in any order by their dependants.

Example:

source1.h

class Class1 {
    Class2 c2;    // a dependency which has not been forward declared
};

source1.cpp

#include "source1.h"    // now compiler will alert you saying that Class2 is undefined
                    // so you can forward declare Class2 within source1.h
...

MSVC users: I strongly recommend using pre-compiled headers. So, move all #include directives for standard headers (and other headers which are never going to change) to stdafx.h.

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Change your Tomcat port address to 8084 and Shut Down Port to 8025. This will resolve your problem.

In other cases antivirus programs may cause problems. I had this problem with K7 total security. In my case K7 Firewall was blocking the 8084 port. The simple solution is to add an exception to Netbeans in K7 Firewall list.

In order to do that, open K7 and goto Settings -> Firewall Settings -> select Applications tab and find Netbeans.

Select Netbeans and click on edit link. On next screen select Grant Full Network access radio button.

Now goto Netbeans and start the server.

Difference between decimal, float and double in .NET?

Integers, as was mentioned, are whole numbers. They can't store the point something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a different type of variable. You can use the double type or the float type. You set these types of variables up in exactly the same way: instead of using the word int, you type double or float. Like this:

float myFloat;
double myDouble;

(float is short for "floating point", and just means a number with a point something on the end.)

The difference between the two is in the size of the numbers that they can hold. For float, you can have up to 7 digits in your number. For doubles, you can have up to 16 digits. To be more precise, here's the official size:

float:  1.5 × 10^-45  to 3.4 × 10^38  
double: 5.0 × 10^-324 to 1.7 × 10^308

float is a 32-bit number, and double is a 64-bit number.

Double click your new button to get at the code. Add the following three lines to your button code:

double myDouble;
myDouble = 0.007;
MessageBox.Show(myDouble.ToString());

Halt your program and return to the coding window. Change this line:

myDouble = 0.007;
myDouble = 12345678.1234567;

Run your programme and click your double button. The message box correctly displays the number. Add another number on the end, though, and C# will again round up or down. The moral is if you want accuracy, be careful of rounding!

Determine Whether Two Date Ranges Overlap

You can try this:

//custom date for example
$d1 = new DateTime("2012-07-08");
$d2 = new DateTime("2012-07-11");
$d3 = new DateTime("2012-07-08");
$d4 = new DateTime("2012-07-15");

//create a date period object
$interval = new DateInterval('P1D');
$daterange = iterator_to_array(new DatePeriod($d1, $interval, $d2));
$daterange1 = iterator_to_array(new DatePeriod($d3, $interval, $d4));
array_map(function($v) use ($daterange1) { if(in_array($v, $daterange1)) print "Bingo!";}, $daterange);

Converting an int to a binary string representation in Java?

Convert Integer to Binary:

import java.util.Scanner;

public class IntegerToBinary {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter Integer: ");
        String integerString =input.nextLine();

        System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
    }

}

Output:

Enter Integer:

10

Binary Number: 1010

How to customize <input type="file">?

  <label for="fusk">dsfdsfsd</label>
  <input id="fusk" type="file" name="photo" style="display: none;">

why not? ^_^

See the example here

Disabling Controls in Bootstrap

try

$('#xxx').attr('disabled', true);

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

Count the number of occurrences of each letter in string

#include<stdio.h>
#include<string.h>

#define filename "somefile.txt"

int main()
{
    FILE *fp;
    int count[26] = {0}, i, c;  
    char ch;
    char alpha[27] = "abcdefghijklmnopqrstuwxyz";
    fp = fopen(filename,"r");
    if(fp == NULL)
        printf("file not found\n");
    while( (ch = fgetc(fp)) != EOF) {
        c = 0;
        while(alpha[c] != '\0') {

            if(alpha[c] == ch) {
                count[c]++; 
            }
            c++;
        }
    }
    for(i = 0; i<26;i++) {
        printf("character %c occured %d number of times\n",alpha[i], count[i]);
    }
    return 0;
}

Opening a CHM file produces: "navigation to the webpage was canceled"

There are apparently different levels of authentication. Most articles I read tell you to set the MaxAllowedZone to '1' which means that local machine zone and intranet zone are allowed but '4' allows access for 'all' zones.

For more info, read this article: https://support.microsoft.com/en-us/kb/892675

This is how my registry looks (I wasn't sure it would work with the wild cards but it seems to work for me):

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000004

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"UrlAllowList"="\\\\<network_path_root>;\\\\<network_path_root>\*;\\ies-inc.local;http://www.*;http://*;https://www.*;https://*;"

As an additional note, weirdly the "UrlAllowList" key was required to make this work on another PC but not my test one. It's probably not required at all but when I added it, it fixed the problem. The user may have not closed the original file or something like that. So just a consideration. I suggest try the least and test it, then add if needed. Once you confirm, you can deploy if needed. Good Luck!

Edit: P.S. Another method that worked was mapping the path to the network locally by using mklink /d (symbolic linking in Windows 7 or newer) but mapping a network drive letter (Z: for testing) did not work. Just food for thought and I did not have to 'Unblock' any files. Also the accepted 'Solution' did not resolve the issue for me.

video as site background? HTML 5

I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):

Put the video right after the body-tag with style="width:100%;". Right afterwords, put a "bodydummy"-tag:

<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
    <source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
    <source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
    <source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>    
</video>

<img id="bgImg" src="videos/poster.png" />

<!-- This image stretches exactly to the browser width/height and lies behind the video-->

<div id="bodyDummy">

Put all your content inside the bodydummy-div and put the z-indexes correctly in CSS like this:

#bgImg{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
}

#bgVideo{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
}

#bodyDummy{ 
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    overflow: auto;
    width: 100%;
    height: 100%;
}

Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.

Convert String XML fragment to Document Node in Java

Try jcabi-xml, with a one liner:

Node node = new XMLDocument("<node>value</node>").node();

How to extract file name from path?

I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.

Function FileNameFromPath(strFullPath As String) As String

    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))

End Function

http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.

HQL "is null" And "!= null" on an Oracle column

If you do want to use null values with '=' or '<>' operators you may find the

answer from @egallardo hier

very useful.

Short example for '=': The expression

WHERE t.field = :param

you refactor like this

WHERE ((:param is null and t.field is null) or t.field = :param)

Now you can set the parameter param either to some non-null value or to null:

query.setParameter("param", "Hello World"); // Works
query.setParameter("param", null);          // Works also

Stopping Docker containers by image name - Ubuntu

Adding on top of @VonC superb answer, here is a ZSH function that you can add into your .zshrc file:

dockstop() {
  docker rm $(docker stop $(docker ps -a -q --filter ancestor="$1" --format="{{.ID}}"))
}

Then in your command line, simply do dockstop myImageName and it will stop and remove all containers that were started from an image called myImageName.

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

Functional style of Java 8's Optional.ifPresent and if-not-Present?

There isn't a great way to do it out of the box. If you want to be using your cleaner syntax on a regular basis, then you can create a utility class to help out:

public class OptionalEx {
    private boolean isPresent;

    private OptionalEx(boolean isPresent) {
        this.isPresent = isPresent;
    }

    public void orElse(Runnable runner) {
        if (!isPresent) {
            runner.run();
        }
    }

    public static <T> OptionalEx ifPresent(Optional<T> opt, Consumer<? super T> consumer) {
        if (opt.isPresent()) {
            consumer.accept(opt.get());
            return new OptionalEx(true);
        }
        return new OptionalEx(false);
    }
}

Then you can use a static import elsewhere to get syntax that is close to what you're after:

import static com.example.OptionalEx.ifPresent;

ifPresent(opt, x -> System.out.println("found " + x))
    .orElse(() -> System.out.println("NOT FOUND"));

Why are C++ inline functions in the header?

The c++ inline keyword is misleading, it doesn't mean "inline this function". If a function is defined as inline, it simply means that it can be defined multiple times as long as all definitions are equal. It's perfectly legal for a function marked inline to be a real function that is called instead of getting code inlined at the point where it's called.

Defining a function in a header file is needed for templates, since e.g. a templated class isn't really a class, it's a template for a class which you can make multiple variations of. In order for the compiler to be able to e.g. make a Foo<int>::bar() function when you use the Foo template to create a Foo class, the actual definition of Foo<T>::bar() must be visible.

When is "java.io.IOException:Connection reset by peer" thrown?

To expand on BalusC's answer, any scenario where the sender continues to write after the peer has stopped reading and closed its socket will produce this exception, as will the peer closing while it still had unread data in its own socket receive buffer. In other words, an application protocol error. For example, if you write something to the peer that the peer doesn't understand, and then it closes its socket in protest, and you then continue to write, the peer's TCP stack will issue an RST, which results in this exception and message at the sender.

Is it possible to log all HTTP request headers with Apache?

In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.

<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time  "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>

Print very long string completely in pandas dataframe

Use pd.set_option('display.max_colwidth', None) for automatic linebreaks and multi-line cells.

This is a great resource on how to use jupyters display with pandas to the fullest.


Edited: Used to be pd.set_option('display.max_colwidth', -1).

Convert bytes to bits in python

What about something like this?

>>> bin(int('ff', base=16))
'0b11111111'

This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.

As pointed out by a comment, if you need to get rid of the 0b prefix, you can do it this way:

>>> bin(int('ff', base=16)).lstrip('0b')
'11111111'

or this way:

>>> bin(int('ff', base=16))[2:]
'11111111'

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I tried everything suggested on here and many other sites, I eventually figured out that the problem was with Bitdefender blocking aapt....

If you have Bitdefender installed then you need to turn aapt & aapt2 "Application Access" on individually.

Hope this is of use.

How to suppress warnings globally in an R Script

You could use

options(warn=-1)

But note that turning off warning messages globally might not be a good idea.

To turn warnings back on, use

options(warn=0)

(or whatever your default is for warn, see this answer)

'react-scripts' is not recognized as an internal or external command

It is an error about react-scripts file missing in your node_modules/ directory at the time of installation.

Check your react-script dependency is avaliable or not in package.json.

If not available then add it manually via:

npm install react-scripts --save

Is it possible to delete an object's property in PHP?

unset($a->new_property);

This works for array elements, variables, and object attributes.

Example:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a);  // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a);  // -> stdClass::__set_state(array())

Maximum value for long integer

Long integers:

There is no explicitly defined limit. The amount of available address space forms a practical limit.
(Taken from this site). See the docs on Numeric Types where you'll see that Long integers have unlimited precision. In Python 2, Integers will automatically switch to longs when they grow beyond their limit:

>>> import sys
>>> type(sys.maxsize)
<type 'int'>
>>> type(sys.maxsize+1)
<type 'long'>


for integers we have

maxint and maxsize:

The maximum value of an int can be found in Python 2.x with sys.maxint. It was removed in Python 3, but sys.maxsize can often be used instead. From the changelog:

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

and, for anyone interested in the difference (Python 2.x):

sys.maxint The largest positive integer supported by Python’s regular integer type. This is at least 2**31-1. The largest negative integer is -maxint-1 — the asymmetry results from the use of 2’s complement binary arithmetic.

sys.maxsize The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.

and for completeness, here's the Python 3 version:

sys.maxsize An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2^31 - 1 on a 32-bit platform and 2^63 - 1 on a 64-bit platform.

floats:

There's float("inf") and float("-inf"). These can be compared to other numeric types:

>>> import sys
>>> float("inf") > sys.maxsize
True

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

I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.

How do I uninstall a package installed using npm link?

you can use unlink to remove the symlink.

For Example:

cd ~/projects/node-redis 
npm link                 
cd ~/projects/node-bloggy
npm link redis             # links to your local redis

To reinstall from your package.json:

npm unlink redis
npm install

https://www.tachyonstemplates.com/npm-cheat-sheet/#unlinking-a-npm-package-from-an-application

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

Generating a SHA-256 hash from the Linux command line

I believe that echo outputs a trailing newline. Try using -n as a parameter to echo to skip the newline.

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);