Programs & Examples On #Error console

How to prevent text in a table cell from wrapping

For Use with React / Material UI

In case you're here wondering how this works for Material UI when building in React, here's how you add this to your <TableHead> Component:

<TableHead style={{ whiteSpace: 'nowrap'}}>

Disable all table constraints in Oracle

This is another way for disabling constraints (it came from https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817)

WITH qry0 AS
       (SELECT    'ALTER TABLE '
               || child_tname
               || ' DISABLE CONSTRAINT '
               || child_cons_name
                 disable_fk
              ,   'ALTER TABLE '
               || parent_tname
               || ' DISABLE CONSTRAINT '
               || parent.parent_cons_name
                 disable_pk
          FROM (SELECT a.table_name child_tname
                      ,a.constraint_name child_cons_name
                      ,b.r_constraint_name parent_cons_name
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'
                GROUP BY a.table_name, a.constraint_name
                        ,b.r_constraint_name) child
              ,(SELECT a.constraint_name parent_cons_name
                      ,a.table_name parent_tname
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')
                GROUP BY a.table_name, a.constraint_name) parent
         WHERE child.parent_cons_name = parent.parent_cons_name
           AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))
SELECT DISTINCT disable_pk
  FROM qry0
UNION
SELECT DISTINCT disable_fk
  FROM qry0;

works like a charm

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

Handling warning for possible multiple enumeration of IEnumerable

The problem with taking IEnumerable as a parameter is that it tells callers "I wish to enumerate this". It doesn't tell them how many times you wish to enumerate.

I can change the objects parameter to be List and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle.

The goal of taking the highest object is noble, but it leaves room for too many assumptions. Do you really want someone to pass a LINQ to SQL query to this method, only for you to enumerate it twice (getting potentially different results each time?)

The semantic missing here is that a caller, who perhaps doesn't take time to read the details of the method, may assume you only iterate once - so they pass you an expensive object. Your method signature doesn't indicate either way.

By changing the method signature to IList/ICollection, you will at least make it clearer to the caller what your expectations are, and they can avoid costly mistakes.

Otherwise, most developers looking at the method might assume you only iterate once. If taking an IEnumerable is so important, you should consider doing the .ToList() at the start of the method.

It's a shame .NET doesn't have an interface that is IEnumerable + Count + Indexer, without Add/Remove etc. methods, which is what I suspect would solve this problem.

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I did it this way,

2D

% vectors I want to plot as rows (XSTART, YSTART) (XDIR, YDIR)
rays = [
  1 2   1 0 ;
  3 3   0 1 ;
  0 1   2 0 ;
  2 0   0 2 ;
] ;

% quiver plot
quiver( rays( :,1 ), rays( :,2 ), rays( :,3 ), rays( :,4 ) );

3D

% vectors I want to plot as rows (XSTART, YSTART, ZSTART) (XDIR, YDIR, ZDIR)
rays = [
  1 2 0  1 0 0;
  3 3 2  0 1 -1 ;
  0 1 -1  2 0 8;
  2 0 0  0 2 1;
] ;

% quiver plot
quiver3( rays( :,1 ), rays( :,2 ), rays( :,3 ), rays( :,4 ), rays( :,5 ), rays( :,6 ) );

Based on the quiver and quiver3 documentation

Shell script to check if file exists

One approach:

(
  shopt -s nullglob
  files=(/home/edward/bank1/fiche/Test*)
  if [[ "${#files[@]}" -gt 0 ]] ; then
    echo found one
  else
    echo found none
  fi
)

Explanation:

  • shopt -s nullglob will cause /home/edward/bank1/fiche/Test* to expand to nothing if no file matches that pattern. (Without it, it will be left intact.)
  • ( ... ) sets up a subshell, preventing shopt -s nullglob from "escaping".
  • files=(/home/edward/bank1/fiche/Test*) puts the file-list in an array named files. (Note that this is within the subshell only; files will not be accessible after the subshell exits.)
  • "${#files[@]}" is the number of elements in this array.

Edited to address subsequent question ("What if i also need to check that these files have data in them and are not zero byte files"):

For this version, we need to use -s (as you did in your question), which also tests for the file's existence, so there's no point using shopt -s nullglob anymore: if no file matches the pattern, then -s on the pattern will be false. So, we can write:

(
  found_nonempty=''
  for file in /home/edward/bank1/fiche/Test* ; do
    if [[ -s "$file" ]] ; then
      found_nonempty=1
    fi
  done
  if [[ "$found_nonempty" ]] ; then
    echo found one
  else
    echo found none
  fi
)

(Here the ( ... ) is to prevent file and found_file from "escaping".)

merge one local branch into another local branch

  1. git checkout [branchYouWantToReceiveBranch] - checkout branch you want to receive branch
  2. git merge [branchYouWantToMergeIntoBranch]

unsigned int vs. size_t

The size_t type is the type returned by the sizeof operator. It is an unsigned integer capable of expressing the size in bytes of any memory range supported on the host machine. It is (typically) related to ptrdiff_t in that ptrdiff_t is a signed integer value such that sizeof(ptrdiff_t) and sizeof(size_t) are equal.

When writing C code you should always use size_t whenever dealing with memory ranges.

The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic. For example, on many older PC type computers the value sizeof(size_t) would be 4 (bytes) but sizeof(int) would be 2 (byte). 16 bit arithmetic was faster than 32 bit arithmetic, though the CPU could handle a (logical) memory space of up to 4 GiB.

Use the int type only when you care about efficiency as its actual precision depends strongly on both compiler options and machine architecture. In particular the C standard specifies the following invariants: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) placing no other limitations on the actual representation of the precision available to the programmer for each of these primitive types.

Note: This is NOT the same as in Java (which actually specifies the bit precision for each of the types 'char', 'byte', 'short', 'int' and 'long').

Database Structure for Tree Data Structure

If anyone using MS SQL Server 2008 and higher lands on this question: SQL Server 2008 and higher has a new "hierarchyId" feature designed specifically for this task.

More info at https://docs.microsoft.com/en-us/sql/relational-databases/hierarchical-data-sql-server

How to show google.com in an iframe?

This used to work because I used it to create custom Google searches with my own options. Google made changes on their end and broke my private customized search page :( No longer working sample below. It was very useful for complex search patterns.

<form method="get" action="http://www.google.com/search" target="main"><input name="q" value="" type="hidden"> <input name="q" size="40" maxlength="2000" value="" type="text">

web

I guess the better option is to just use Curl or similar.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

How to set default value to all keys of a dict object in python?

Not after creating it, no. But you could use a defaultdict in the first place, which sets default values when you initialize it.

Escape double quotes in Java

Escaping the double quotes with backslashes is the only way to do this in Java.

Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)

One other option would be to put the String into some kind of text file that you would then read at runtime

Native query with named parameter fails with "Not all named parameters have been set"

Named parameters are not supported by JPA in native queries, only for JPQL. You must use positional parameters.

Named parameters follow the rules for identifiers defined in Section 4.4.1. The use of named parameters applies to the Java Persistence query language, and is not defined for native queries. Only positional parameter binding may be portably used for native queries.

So, use this

Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");

While JPA specification doesn't support named parameters in native queries, some JPA implementations (like Hibernate) may support it

Native SQL queries support positional as well as named parameters

However, this couples your application to specific JPA implementation, and thus makes it unportable.

ASP.NET Web Site or ASP.NET Web Application?

This may sound a bit obvious, but I think it's something that is misunderstood because Visual Studio 2005 only shipped with the web site originally. If your project deals with a website that is fairly limited and doesn't have a lot of logical or physical separation, the website is fine. However if it is truly a web application with different modules where many users add and update data, you are better off with the web application.

The biggest pro of the website model is that anything in the app_code section is dynamically compiled. You can make C# file updates without a full redeploy. However this comes at a great sacrifice. A lot of things happen under the covers that are difficult to control. Namespaces are difficult to control and specific DLL usage goes out the window by default for anything under app_code since everything is dynamically compiled.

The web application model does not have dynamic compilation, but you gain control over the things that I have mentioned.

If you are doing n-tier development, I highly recommend the web application model. If you are doing a limited web site or a quick and dirty implementation, the web site model may have advantages.

More detailed analysis can be found in:

File path to resource in our war/WEB-INF folder?

I know this is late, but this is how I normally do it,

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();           
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");

jQuery UI DatePicker - Change Date Format

Here complete code for date picker with date format (yy/mm/dd).

Copy link below and paste in head tag :

   <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>  
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>  
   <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> 

   <script type="text/javascript">
       $(function() {
               $("#datepicker").datepicker({ dateFormat: "yy-mm-dd" }).val()
       });
   </script>

Copy below code and paste between body tag :

      Date: <input type="text" id="datepicker" size="30"/>    

If you would like two(2) input type text like Start Date and End Date then use this script and change date format.

   <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>  
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>  
   <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> 

   <script type="text/javascript">
       $(function() {
               $("#startdate").datepicker({ dateFormat: "dd-mm-yy" }).val()
               $("#enddate").datepicker({ dateFormat: "dd-mm-yy" }).val()
       });

   </script>  

Two input text like :

      Start Date: <input type="text" id="startdate" size="30"/>    
      End Date: <input type="text" id="enddate" size="30"/>

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

How to loop through array in jQuery?

Use jQuery each(). There are other ways but each is designed for this purpose.

$.each(substr, function(index, value) { 
  alert(value); 
});

And do not put the comma after the last number.

How to create a JQuery Clock / Timer

    var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'signal1';
    var total_signal = 1;

    $(document).ready(function () {
        for (var i = 1; i <= total_signal; i++) {
            var timer = (i == 1) ? timeInterval : (timeInterval * (i - 1));

            var str_html = '<div id="signal' + i + '">' +
                           '<span class="float_left">Signal ' + i + ' : </span>' +
                           '<div class="red float_left"></div>' +
                           '<div class="yellow float_left"></div>' +
                           '<div class="green float_left"></div>' +
                           '<div class="timer float_left">' + timer + '</div>' +
                           '<div style="clear: both;"></div>' +
                           '</div><div class="div_separate"></div>';

            $('.div_demo').append(str_html);
        }

        $('.div_demo .green').eq(0).css('background-color', 'green');
        $('.div_demo .red').css('background-color', 'red');
        $('.div_demo .red').eq(0).css('background-color', 'white');

        setInterval(function () {
            manageSignals();
        }, 1000);
    });

    function manageSignals() {
        var obj_timer = {};

        var temp_i = parseInt(open_signal.substr(6));
        if ($('#' + open_signal + ' .timer').html() == '0')
            open_signal = (temp_i == total_signal) ? 'signal1' : 'signal' + (temp_i + 1);

        for (var i = 1; i <= total_signal; i++) {
            var next_signal = (i == total_signal) ? 'signal1' : 'signal' + (i + 1);

            obj_timer['signal' + i] = parseInt($('#signal' + i + ' .timer').html()) - 1;

            if (obj_timer['signal' + i] == -1 && open_signal == next_signal && total_signal!=1) {
                obj_timer['signal' + i] = (timeInterval * (total_signal - 1)) - 1;

                $('#signal' + i + ' .red').css('background-color', 'red');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
            }
            else if (obj_timer['signal' + i] == -1 && open_signal == 'signal' + i) {
                obj_timer['signal' + i] = (timeInterval - 1);

                $('#signal' + i + ' .red').css('background-color', 'white');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
                $('#signal' + i + ' .green').css('background-color', 'green');
            }
            else if (obj_timer['signal' + i] == blinkTime && open_signal == 'signal' + i) {
                $('#signal' + i + ' .yellow').css('background-color', 'yellow');
                $('#signal' + i + ' .green').css('background-color', 'white');
            }

            $('#signal' + i + ' .timer').html(obj_timer['signal' + i]);
        }
    }
</script>

Trim characters in Java

Here is another non-regexp, non-super-awesome, non-super-optimized, however very easy to understand non-external-lib solution:

public static String trimStringByString(String text, String trimBy) {
    int beginIndex = 0;
    int endIndex = text.length();

    while (text.substring(beginIndex, endIndex).startsWith(trimBy)) {
        beginIndex += trimBy.length();
    } 

    while (text.substring(beginIndex, endIndex).endsWith(trimBy)) {
        endIndex -= trimBy.length();
    }

    return text.substring(beginIndex, endIndex);
}

Usage:

String trimmedString = trimStringByString(stringToTrim, "/");

Difference between left join and right join in SQL Server

Select * from Table1 t1 Left Join Table2 t2 on t1.id=t2.id By definition: Left Join selects all columns mentioned with the "select" keyword from Table 1 and the columns from Table 2 which matches the criteria after the "on" keyword.

Similarly,By definition: Right Join selects all columns mentioned with the "select" keyword from Table 2 and the columns from Table 1 which matches the criteria after the "on" keyword.

Referring to your question, id's in both the tables are compared with all the columns needed to be thrown in the output. So, ids 1 and 2 are common in the both the tables and as a result in the result you will have four columns with id and name columns from first and second tables in order.

*select * from Table1 left join Table2 on Table1.id = Table2.id

The above expression,it takes all the records (rows) from table 1 and columns, with matching id's from table 1 and table 2, from table 2.

select * from Table2 right join Table1 on Table1.id = Table2.id**

Similarly from the above expression,it takes all the records (rows) from table 1 and columns, with matching id's from table 1 and table 2, from table 2. (remember, this is a right join so all the columns from table2 and not from table1 will be considered).

How to place a div on the right side with absolute position

I'm assuming that your container element is probably position:relative;. This is will mean that the dialog box will be positioned accordingly to the container, not the page.

Can you change the markup to this?

<html>
<body>
    <!-- Need to place this div at the top right of the page-->
        <div class="ajax-message">
            <div class="row">
                <div class="span9">
                    <div class="alert">
                        <a class="close icon icon-remove"></a>
                        <div class="message-content">
                            Some message goes here
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <div class="container">
        <!-- Page contents starts here. These are dynamic-->
        <div class="row">
            <div class="span12 inner-col">
                <h2>Documents</h2>
            </div>
        </div>
    </div>
</body>
</html>

With the dialog box outside the main container then you can use absolute positioning relative to the page.

Capture event onclose browser

You're looking for the onclose event.

see: https://developer.mozilla.org/en/DOM/window.onclose

note that not all browsers support this (for example firefox 2)

Git add and commit in one command

I have this function in my .bash_profile or .profile or .zprofile or whatever gets sourced in login shells:

function gac () {
  # Usage: gac [files] [message]
  # gac (git add commit) stages files specified by the first argument
  # and commits the changes with a message specified by the second argument.
  # Using quotes one can add multiple files at once: gac "file1 file2" "Message".
  git add $1 && git commit -m "$2"
}

How to access a mobile's camera from a web app?

Safari & Chrome on iOS 6+ and Android 2.2+ support HTML Media Capture which allows you to take pictures with your device's camera or select an existing one:

<input type="file" accept="image/*">

Here's how it works on iOS 10:

enter image description here

Android 3.0+ and Safari on iOS10.3+ also support the capture attribute which is used to jump straight to the camera.

<input type="file" accept="image/*" capture>

capture="camera" (String) and accept="image/*;capture=camera" (Parameter) were part of old specs and were replaced by capture (Boolean) the W3C Candidate Recommendation.

Support documentation: this 2013 O'Reilly book and my testing

Identify if a string is a number

UPDATE of Kunal Noel Answer

stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.

But, for this case we have that empty strings will pass that test, so, you can:

if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
   // Do your logic here
}

Google Maps API v3 adding an InfoWindow to each marker

Try this:

for (var i in tracks[racer_id].data.points) {
    values = tracks[racer_id].data.points[i];                
    point = new google.maps.LatLng(values.lat, values.lng);
    if (values.qst) {
        var marker = new google.maps.Marker({map: map, position: point, clickable: true});
        tracks[racer_id].markers[i] = marker;
        var info = new google.maps.InfoWindow({
            content: '<b>Speed:</b> ' + values.inst + ' knots'
        });
        tracks[racer_id].info[i] = info;
        google.maps.event.addListener(tracks[racer_id].markers[i], 'click', function() {
            tracks[racer_id].info[i].open(map, tracks[racer_id].markers[i]);
        });
    }
    track_coordinates.push(point);
    bd.extend(point);
}

Ruby on Rails: How do I add placeholder text to a f.text_field?

I tried the solutions above and it looks like on rails 5.* the second agument by default is the value of the input form, what worked for me was:

text_field_tag :attr, "", placeholder: "placeholder text"

What is the difference between Python and IPython?

Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

You can install Ipython using pip - pip install ipython

You can run Ipython by typing ipython in your terminal window.

How can I get my Android device country code without using GPS?

The checked answer has deprecated code. You need to implement this:

String locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
    locale = context.getResources().getConfiguration().locale.getCountry();
}

How to convert 2D float numpy array to 2D int numpy array?

Use the astype method.

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> x.astype(int)
array([[1, 2],
       [1, 2]])

Most Pythonic way to provide global configuration variables in config.py?

How about just using the built-in types like this:

config = {
    "mysql": {
        "user": "root",
        "pass": "secret",
        "tables": {
            "users": "tb_users"
        }
        # etc
    }
}

You'd access the values as follows:

config["mysql"]["tables"]["users"]

If you are willing to sacrifice the potential to compute expressions inside your config tree, you could use YAML and end up with a more readable config file like this:

mysql:
  - user: root
  - pass: secret
  - tables:
    - users: tb_users

and use a library like PyYAML to conventiently parse and access the config file

Generating a random & unique 8 character string using MySQL

For generate random string, you can use:

SUBSTRING(MD5(RAND()) FROM 1 FOR 8)

You recieve smth like that:

353E50CC

How do browser cookie domains work?

For an extensive coverage review the contents of RFC2965. Of course that doesn't necessarily mean that all browsers behave exactly the same way.

However in general the rule for default Path if none specified in the cookie is the path in the URL from which the Set-Cookie header arrived. Similarly the default for the Domain is the full host name in the URL from which the Set-Cookie arrived.

Matching rules for the domain require the cookie Domain to match the host to which the request is being made. The cookie can specify a wider domain match by include *. in the domain attribute of Set-Cookie (this one area that browsers may vary). Matching the path (assuming the domain matches) is a simple matter that the requested path must be inside the path specified on the cookie. Typically session cookies are set with path=/ or path=/applicationName/ so the cookie is available to all requests into the application.


Response to Added:

  • Will a cookie for .example.com be available for www.example.com? Yes
  • Will a cookie for .example.com be available for example.com? Don't Know
  • Will a cookie for example.com be available for www.example.com? Shouldn't but... *
  • Will a cookie for example.com be available for anotherexample.com? No
  • Will www.example.com be able to set cookie for example.com? Yes
  • Will www.example.com be able to set cookie for www2.example.com? No (Except via .example.com)
  • Will www.example.com be able to set cookie for .com? No (Can't set a cookie this high up the namespace nor can you set one for something like .co.uk).

* I'm unable to test this right now but I have an inkling that at least IE7/6 would treat the path example.com as if it were .example.com.

Laravel 5 Clear Views Cache

in Ubuntu system try to run below command:

sudo php artisan cache:clear

sudo php artisan view:clear

sudo php artisan config:cache

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

Here is a modified version of @ntoskrnl's code featuring isRestrictedCryptography check by actual Cipher.getMaxAllowedKeyLength, slf4j logging and support of singleton initialization from application bootstrap like this:

static {
    UnlimitedKeyStrengthJurisdictionPolicy.ensure();
}

This code would correctly stop mangling with reflection when unlimited policy becomes available by default in Java 8u162 as @cranphin's answer predicts.


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.NoSuchAlgorithmException;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Map;

// https://stackoverflow.com/questions/1179672/how-to-avoid-installing-unlimited-strength-jce-policy-files-when-deploying-an
public class UnlimitedKeyStrengthJurisdictionPolicy {

    private static final Logger log = LoggerFactory.getLogger(UnlimitedKeyStrengthJurisdictionPolicy.class);

    private static boolean isRestrictedCryptography() throws NoSuchAlgorithmException {
        return Cipher.getMaxAllowedKeyLength("AES/ECB/NoPadding") <= 128;
    }

    private static void removeCryptographyRestrictions() {
        try {
            if (!isRestrictedCryptography()) {
                log.debug("Cryptography restrictions removal not needed");
                return;
            }
            /*
             * Do the following, but with reflection to bypass access checks:
             *
             * JceSecurity.isRestricted = false;
             * JceSecurity.defaultPolicy.perms.clear();
             * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
             */
            Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
            Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
            Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");

            Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
            isRestrictedField.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
            isRestrictedField.set(null, false);

            Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
            defaultPolicyField.setAccessible(true);
            PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

            Field perms = cryptoPermissions.getDeclaredField("perms");
            perms.setAccessible(true);
            ((Map<?, ?>) perms.get(defaultPolicy)).clear();

            Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
            instance.setAccessible(true);
            defaultPolicy.add((Permission) instance.get(null));

            log.info("Successfully removed cryptography restrictions");
        } catch (Exception e) {
            log.warn("Failed to remove cryptography restrictions", e);
        }
    }

    static {
        removeCryptographyRestrictions();
    }

    public static void ensure() {
        // just force loading of this class
    }
}

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

expected constructor, destructor, or type conversion before ‘(’ token

You are missing the std namespace reference in the cc file. You should also call nom.c_str() because there is no implicit conversion from std::string to const char * expected by ifstream's constructor.

Polygone::Polygone(std::string nom) {
    std::ifstream fichier (nom.c_str(), std::ifstream::in);
    // ...
}

Execute CMD command from code

Are you asking how to bring up a command windows? If so, you can use the Process object ...

Process.Start("cmd");

How to install Openpyxl with pip

For me it worked as Kumar Jaggal but: steps 1, 2, 3, the same 4. py -m setup.py install

Two color borders

Have you tried the different border styles available within the CSS spec? There's already two border styles that might accommodate your need:

border-style: ridge;

Or

border-style: groove;

Updating and committing only a file's permissions using git version control

Not working for me.

The mode is true, the file perms have been changed, but git says there's no work to do.

git init
git add dir/file
chmod 440 dir/file
git commit -a

The problem seems to be that git recognizes only certain permission changes.

How do I send a POST request as a JSON?

In the lastest requests package, you can use json parameter in requests.post() method to send a json dict, and the Content-Type in header will be set to application/json. There is no need to specify header explicitly.

import requests

payload = {'key': 'value'}
requests.post(url, json=payload)

How can I use jQuery to make an input readonly?

simply add the following attribute

// for disabled i.e. cannot highlight value or change
disabled="disabled"

// for readonly i.e. can highlight value but not change
readonly="readonly"

jQuery to make the change to the element (substitute disabled for readonly in the following for setting readonly attribute).

$('#fieldName').attr("disabled","disabled") 

or

$('#fieldName').attr("disabled", true) 

NOTE: As of jQuery 1.6, it is recommended to use .prop() instead of .attr(). The above code will work exactly the same except substitute .attr() for .prop().

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

My docker container has no internet

I was stumped when this happened randomly for me for one of my containers, while the other containers were fine. The container was attached to at least one non-internal network, so there was nothing wrong with the Compose definition. Restarting the VM / docker daemon did not help. It was also not a DNS issue because the container could not even ping an external IP. What solved it for me was to recreate the docker network(s). In my case, docker-compose down && docker-compose up worked.

Compose

This forces the recreation of all networks of all the containers:

docker-compose down && docker-compose up

Swarm mode

I suppose you just remove and recreate the service, which recreates the service's network(s):

docker service rm some-service

docker service create ...

If the container's network(s) are external

Simply remove and recreate the external networks of that service:

docker network rm some-external-network

docker network create some-external-network

How to extend / inherit components?

Angular 2 version 2.3 was just released, and it includes native component inheritance. It looks like you can inherit and override whatever you want, except for templates and styles. Some references:

How to call external url in jquery?

I think the only way is by using internel PHP code like MANOJ and Fernando suggest.

curl post/get in php file on your server --> call this php file with ajax

The PHP file let say (fb.php):

$commentdata=$_GET['commentdata'];
$fbUrl="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
curl_setopt($ch, CURLOPT_URL,$fbUrl);
curl_setopt($ch, CURLOPT_POST, 1);
// POST data here
curl_setopt($ch, CURLOPT_POSTFIELDS,
        "message=".$commentdata);

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);

Than use AJAX GET to

fb.php?commentmeta=your comment goes here

from your server.

Or do this with simple HTML and JavaScript from externel server:

Message: <input type="text" id="message">
<input type="submit" onclick='PostMessage()'>
<script>
function PostMessage() {
var comment = document.getElementById('message').value;
    window.location.assign('http://yourdomain.tld/fb.php?commentmeta='+comment)
}
</script>

Get the position of a spinner in Android

The way to get the selection of the spinner is:

  spinner1.getSelectedItemPosition();

Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()

However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.

So you could change that line to:

TestProjectActivity.this.number = position + 1;

If that does not fix the problem, please post the error message generated when your app crashes.

Using Linq to get the last N elements of a collection?

Honestly I'm not super proud of the answer, but for small collections you could use the following:

var lastN = collection.Reverse().Take(n).Reverse();

A bit hacky but it does the job ;)

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

how to open a page in new tab on button click in asp.net?

Per Open a URL in a new tab (and not a new window) using JavaScript

Nothing an author can do can choose to open in a new tab instead of a new window.

The browser decides between opening a new tab or opening a new window. You cannot control this as a developer.

Accessing JPEG EXIF rotation data in JavaScript on the client side

Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)

There is also a bug to implement this in Chrome.

Beware that this property is only supported by Firefox and is likely to be deprecated.

difference between primary key and unique key

If your Database design is such that their is no need of foreign key, then you can go with Unique key( but remember unique key allow single null value ).

If you database demand foreign key then you leave with no choice you have to go with primary key.

To see the difference between unique and primary key visit here

How to delete file from public folder in laravel 5.1

Follow the steps carefully to get the image first=>

    $img = DB::table('students')->where('id',$id)->first();
    $image_path = $img->photo;
    
    unlink($image_path);
    DB::table('students')->where('id',$id)->delete();

syntax error when using command line in python

Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.

Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.

Phone validation regex

First test the length of the string to see if it is between 9 and 15.

Then use this regex to validate:

^\+?\d+(-\d+)*$

This is yet another variation of the normal* (special normal*)* pattern, with normal being \d and special being -.

What are the use cases for selecting CHAR over VARCHAR in SQL?

It's the classic space versus performance tradeoff.

In MS SQL 2005, Varchar (or NVarchar for lanuagues requiring two bytes per character ie Chinese) are variable length. If you add to the row after it has been written to the hard disk it will locate the data in a non-contigious location to the original row and lead to fragmentation of your data files. This will affect performance.

So, if space is not an issue then Char are better for performance but if you want to keep the database size down then varchars are better.

jQuery .live() vs .on() method for adding a click event after loading dynamic html

If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:

$('#parent').on("click", "#child", function() {});

The event handler will be attached to the #parent object and anytime a click event bubbles up to it that originated on #child, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).

It's done this way because you can attach the event to the #parent object even when the #child object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the #parent object, it will see that it originated on #child and there is an event handler for a click on #child and fire your event.

Get User's Current Location / Coordinates

To get a user's current location you need to declare:

let locationManager = CLLocationManager()

In viewDidLoad() you have to instantiate the CLLocationManager class, like so:

// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization() 

// For use in foreground
self.locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
}

Then in CLLocationManagerDelegate method you can get user's current location coordinates:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

In the info.plist you will have to add NSLocationAlwaysUsageDescription and your custom alert message like; AppName(Demo App) would like to use your current location.

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

I recently ran into this problem again. It's been a while since I last worked with submodules and having learned more about git I realized that simply checking out the branch you want to commit on is sufficient. Git will keep the working tree even if you don't stash it.

git checkout existing_branch_name

If you want to work on a new branch this should work for you:

git checkout -b new_branch_name

The checkout will fail if you have conflicts in the working tree, but that should be quite unusual and if it happens you can just stash it, pop it and resolve the conflict.

Compared to the accepted answer, this answer will save you the execution of two commands, that don't really take that long to execute anyway. Therefore I will not accept this answer, unless it miraculously gets more upvotes (or at least close) than the currently accepted answer.

Python: convert string to byte array

Just use a bytearray() which is a list of bytes.

Python2:

s = "ABCD"
b = bytearray()
b.extend(s)

Python3:

s = "ABCD"
b = bytearray()
b.extend(map(ord, s))

By the way, don't use str as a variable name since that is builtin.

Error: free(): invalid next size (fast):

I encountered such a situation where code was circumventing STL's api and writing to the array unsafely when someone resizes it. Adding the assert here caught it:

void Logo::add(const QVector3D &v, const QVector3D &n)
{
 GLfloat *p = m_data.data() + m_count;
 *p++ = v.x();
 *p++ = v.y();
 *p++ = v.z();
 *p++ = n.x();
 *p++ = n.y();
 *p++ = n.z();
 m_count += 6;
 Q_ASSERT( m_count <= m_data.size() );
}

Regular Expression to reformat a US phone number in Javascript

thinking backwards

Take the last digits only (up to 10) ignoring first "1".

function formatUSNumber(entry = '') {
  const match = entry
    .replace(/\D+/g, '').replace(/^1/, '')
    .match(/([^\d]*\d[^\d]*){1,10}$/)[0]
  const part1 = match.length > 2 ? `(${match.substring(0,3)})` : match
  const part2 = match.length > 3 ? ` ${match.substring(3, 6)}` : ''
  const part3 = match.length > 6 ? `-${match.substring(6, 10)}` : ''    
  return `${part1}${part2}${part3}`
}

example input / output as you type

formatUSNumber('+1333')
// (333)

formatUSNumber('333')
// (333)

formatUSNumber('333444')
// (333) 444

formatUSNumber('3334445555')
// (333) 444-5555

How to install Android Studio on Ubuntu?

Don't forget to run:

/opt/android-studio/bin/studio.sh

when you are done installing.

Convert array into csv

A slight adaptation to the solution above by kingjeffrey for when you want to create and echo the CSV within a template (Ie - most frameworks will have output buffering enabled and you are required to set headers etc in controllers.)

// Create Some data
<?php
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );


// Create a stream opening it with read / write mode
$stream = fopen('data://text/plain,' . "", 'w+');

// Iterate over the data, writting each line to the text stream
foreach ($data as $val) {
    fputcsv($stream, $val);
}

// Rewind the stream
rewind($stream);

// You can now echo it's content
echo stream_get_contents($stream);

// Close the stream 
fclose($stream);

Credit to Kingjeffrey above and also to this blog post where I found the information about creating text streams.

C# "No suitable method found to override." -- but there is one

You need to inherit from the base class.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

SQL Server - INNER JOIN WITH DISTINCT

Try this:

select distinct a.FirstName, a.LastName, v.District
from AddTbl a 
  inner join ValTbl v
  on a.LastName = v.LastName
order by a.FirstName;

Or this (it does the same, but the syntax is different):

select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;

How to clear gradle cache?

Command: rm -rf ~/.gradle/caches/

POI setting Cell Background to a Custom Color

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

WordPress - Check if user is logged in

This problem is from the lazy update data request of Chrome. At the first time you go to homepage. Chrome request with empty data. Then you go to the login page and logged in. When you back home page Chrome lazy to update the cookie data request because this domain is the same with the first time you access. Solution: Add parameter for home url. That helps Chrome realizes that this request need to update cookie to call to the server.

add at dashboard page

<?php 
$track = '?track='.uniqid();
?>
<a href="<?= get_home_url(). $track ?>"> <img src="/img/logo.svg"></a>

Getting Image from API in Angular 4/5+?

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

Angular 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Angular 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

Important: Since Angular 5+ you should use the new HttpClient.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

See the working example for Angular 5+ here.

How to take column-slices of dataframe in pandas

Another way to get a subset of columns from your DataFrame, assuming you want all the rows, would be to do:
data[['a','b']] and data[['c','d','e']]
If you want to use numerical column indexes you can do:
data[data.columns[:2]] and data[data.columns[2:]]

Git fetch remote branch

Let's say that your remote is [email protected] and you want its random_branch branch. The process should be as follows:

  1. First check the list of your remotes by

    git remote -v

  2. If you don't have the [email protected] remote in the above command's output, you would add it by

    git remote add xyz [email protected]

  3. Now you can fetch the contents of that remote by

    git fetch xyz

  4. Now checkout the branch of that remote by

    git checkout -b my_copy_random_branch xyz/random_branch

  5. Check the branch list by

    git branch -a

The local branch my_copy_random_branch would be tracking the random_branch branch of your remote.

Waiting for another flutter command to release the startup lock

For Newbies

The simplest solution, although a little time consuming would be to restart your computer or simple logout from the current user and login again.

How to make a dropdown readonly using jquery?

Easiest option for me was to make select as readonly and add:

onmousedown="return false" onkeydown="return false"

You don't need to write any extra logic. No hidden inputs or disabled and then re-enabled on form submit.

How to get everything after a certain character?

The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.

$data = "123_String";    
$whatIWant = substr($data, strpos($data, "_") + 1);    
echo $whatIWant;

If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:

if (($pos = strpos($data, "_")) !== FALSE) { 
    $whatIWant = substr($data, $pos+1); 
}

What does "dereferencing" a pointer mean?

I think all the previous answers are wrong, as they state that dereferencing means accessing the actual value. Wikipedia gives the correct definition instead: https://en.wikipedia.org/wiki/Dereference_operator

It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer.

That said, we can dereference the pointer without ever accessing the value it points to. For example:

char *p = NULL;
*p;

We dereferenced the NULL pointer without accessing its value. Or we could do:

p1 = &(*p);
sz = sizeof(*p);

Again, dereferencing, but never accessing the value. Such code will NOT crash: The crash happens when you actually access the data by an invalid pointer. However, unfortunately, according the the standard, dereferencing an invalid pointer is an undefined behaviour (with a few exceptions), even if you don't try to touch the actual data.

So in short: dereferencing the pointer means applying the dereference operator to it. That operator just returns an l-value for your future use.

SQL Format as of Round off removing decimals

SELECT CONVERT(INT, 11.4)

RESULT: 11

SELECT CONVERT(INT, 11.6)

RESULT: 11

Convert a tensor to numpy array in Tensorflow?

Any tensor returned by Session.run or eval is a NumPy array.

>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>

Or:

>>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

Or, equivalently:

>>> sess = tf.Session()
>>> with sess.as_default():
>>>    print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

EDIT: Not any tensor returned by Session.run or eval() is a NumPy array. Sparse Tensors for example are returned as SparseTensorValue:

>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

Posting JSON Data to ASP.NET MVC

In MVC3 they've added this.

But whats even more nice is that since MVC source code is open you can grab the ValueProvider and use it yourself in your own code (if youre not on MVC3 yet).

You will end up with something like this

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())

Eclipse error: 'Failed to create the Java Virtual Machine'

  1. Open the ecplise.ini file which is located in the eclipse installation folder.

  2. Find & Replace the line -vmargs with -vm D:\jdk1.6.0_23\bin\javaw.exe OR just remove the line -vmargs and save it . Now the problem is getting solved

Keyboard shortcut to comment lines in Sublime Text 3

I prefer pressing Ctrl + / to (un)comment the current line. Plus, I want the cursor to move down one line, thus this way I can (un)comment several lines easily. If you install the "Chain of Command" plugin, you can combine these two operations:

[
    { 
        "keys": ["ctrl+keypad_divide"], 
        "command": "chain",
        "args": {
            "commands": [
                ["toggle_comment", { "block": false }],
                ["move", {"by": "lines", "forward": true}]
            ]
        }
    }
]

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

Vertically centering a div inside another div

Vertically centering div items inside another div

Just set the container to display:table and then the inner items to display:table-cell. Set a height on the container, and then set vertical-align:middle on the inner items. This has broad compatibility back as far as the days of IE9.

Just note that the vertical alignment will depend on the height of the parent container.

_x000D_
_x000D_
.cn_x000D_
{_x000D_
display:table;_x000D_
height:80px;_x000D_
background-color:#555;_x000D_
}_x000D_
_x000D_
.inner_x000D_
{_x000D_
display:table-cell;_x000D_
vertical-align:middle;_x000D_
color:#FFF;_x000D_
padding-left:10px;_x000D_
padding-right:10px;_x000D_
}
_x000D_
<div class="cn">_x000D_
  <div class="inner">Item 1</div>_x000D_
  <div class="inner">Item 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

dynamic_cast and static_cast in C++

The following is not really close to what you get from C++'s dynamic_cast in terms of type checking but maybe it will help you understand its purpose a little bit better:

struct Animal // Would be a base class in C++
{
    enum Type { Dog, Cat };
    Type type;
};

Animal * make_dog()
{
   Animal * dog = new Animal;
   dog->type = Animal::Dog;
   return dog;
}
Animal * make_cat()
{
   Animal * cat = new Animal;
   cat->type = Animal::Cat;
   return cat;
}

Animal * dyn_cast(AnimalType type, Animal * animal)
{
    if(animal->type == type)
        return animal;
    return 0;
}

void bark(Animal * dog)
{
    assert(dog->type == Animal::Dog);

    // make "dog" bark
}

int main()
{
    Animal * animal;
    if(rand() % 2)
        animal = make_dog();
    else
        animal = make_cat();

    // At this point we have no idea what kind of animal we have
    // so we use dyn_cast to see if it's a dog

    if(dyn_cast(Animal::Dog, animal))
    {
        bark(animal); // we are sure the call is safe
    }

    delete animal;
}

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

I got this problem too. I have solved this issue already. If u are using Wamp then perform the following steps.

  1. Go to wamp64/www/bin/php/php* (where * is the php version you are using)
  2. Edit file php and uncomment this line by removing the semicolon:
;extension=pdo_pgsql to extension=pdo_pgsql
  1. Save and restart your Wamp server

If it does not work, please check your .env and config/database again.

How to Calculate Jump Target Address and Branch Target Address?

(In the diagrams and text below, PC is the address of the branch instruction itself. PC+4 is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)

1. Branch Address Calculation

In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.

We also limit the branch distance to -2^15 to +2^15 - 1 instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.

So step by step :

  • Sign extend the 16 bit offset value to preserve its value.
  • Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.
  • Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.

Branch address calculation


2. Jump Address Calculation

For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.

Again step by step:

  • Multiply 26 bit value with 4.
  • Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.
  • Resulting address is the jump value.

In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.

enter image description here

Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)

Source: Bilkent University CS 224 Course Slides

How can I delete Docker's images?

The image could be currently used by a running container, so you first have to stop and remove the container(s).

docker stop <container-name>
docker rm <container-id>

Then you could try deleting the image:

docker rmi <image-id>

You must be sure that this image doesn't depend on other images (otherwise you must delete them first).

I had a strange case in which I had no more containers still alive (docker ps -a returned nothing) but I couldn't manage to delete the image and its image-dependency.

To solve these special cases you could force the image removal with this:

docker rmi -f <image-id>

Find out time it took for a python script to complete execution

Use the timeit module. It's very easy. Run your example.py file so it is active in the Python Shell, you should now be able to call your function in the shell. Try it out to check it works

>>>fun(input)
output

Good, that works, now import timeit and set up a timer

>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>

Now we have our timer set up we can see how long it takes

>>>t.timeit(number=1)
some number here

And there we go, it will tell you how many seconds (or less) it took to execute that function. If it's a simple function then you can increase it to t.timeit(number=1000) (or any number!) and then divide the answer by the number to get the average.

I hope this helps.

What are the differences between delegates and events?

What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a class, or an interface does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.

Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:

In typical usage, the TypeSpec (if present) identifies a delegate whose signature matches the arguments passed to the event’s fire method.

However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a List or a Dictionary or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

How to get href value using jQuery?

It's worth mentioning that

$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always

I have Python on my Ubuntu system, but gcc can't find Python.h

locate Python.h

If the output is empty, then find your python version

python --version

lets say it is X.x i.e 2.7 or 3.6, 3.7, 3.8 Then with the same version install header files and static libraries for python

sudo apt-get install pythonX.x-dev

What is the difference between :focus and :active?

Active is when the user activating that point (Like mouse clicking, if we use tab from field-to-field there is no sign from active style. Maybe clicking need more time, just try hold click on that point), focus is happened after the point is activated. Try this :

<style type="text/css">
  input { font-weight: normal; color: black; }
  input:focus { color: green; outline: 1px solid green; }
  input:active { color: red; outline: 1px solid red; }
</style>

<input type="text"/>
<input type="text"/>

What is the correct syntax of ng-include?

Maybe this will help for beginners

<!doctype html>
<html lang="en" ng-app>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="custom.css">
  </head>
  <body>
    <div ng-include src="'view/01.html'"></div>
    <div ng-include src="'view/02.html'"></div>
    <script src="angular.min.js"></script>
  </body>
</html>

How to implement the Android ActionBar back button?

Following Steps are much enough to back button:

Step 1: This code should be in Manifest.xml

<activity android:name=".activity.ChildActivity"
        android:parentActivityName=".activity.ParentActivity"
        android:screenOrientation="portrait">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.ParentActivity" /></activity>

Step 2: You won't give

finish();

in your Parent Activity while starting Child Activity.

Step 3: If you need to come back to Parent Activity from Child Activity, Then you just give this code for Child Activity.

startActivity(new Intent(ParentActivity.this, ChildActivity.class));

How can I change IIS Express port for a site

Deploy your application in the IIS with the default port. Try to debug it using visual studio. It's a good practice. If you use visual studio, it will keep changing the port number most of the time. So better deploy the application in the IIS first and Open the same in visual studio and Debug it.

How to run php files on my computer

If you have apache running, put your file in server folder for html files and then call it from web-browser (Like http://localhost/myfile.php ).

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

Calling Member Functions within Main C++

On an informal note, you can also call non-static member functions on temporaries:

MyClass().printInformation();

(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))

Reading a binary input stream into a single byte array in Java

Max value for array index is Integer.MAX_INT - it's around 2Gb (2^31 / 2 147 483 647). Your input stream can be bigger than 2Gb, so you have to process data in chunks, sorry.

        InputStream is;
        final byte[] buffer = new byte[512 * 1024 * 1024]; // 512Mb
        while(true) {
            final int read = is.read(buffer);
            if ( read < 0 ) {
                break;
            }
            // do processing 
        }

How to set the component size with GridLayout? Is there a better way?

In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.

First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.

JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));

I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.

for (int i = 0; i < numberOfParams; ++i) {
    yourSettingsPanel.add(labels[i]);
    yourSettingsPanel.add(components[i]);
}

To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.

JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);

Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.

JScrollPane scroll = new JScrollPane(northOnlyPanel,
                                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:

window.add(scroll, BorderLayout.CENTER);

In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.

JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);

JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);

Eclipse does not start when I run the exe?

Kindly check the following:

1) Your eclipse version,whether it is compatible with what version of java. Have that.

2)Check the operating system specific BIT requirements either 32/64 with eclipse version.

3)Usually java will be installed in ProgramFiles for Java if both OS & Java are 64 bit else it will be in ProgramFiles(x86) if java is 32bit and OS is 64Bit.

4)Last but not least check the environment variables for Java whether it meets the requirements of your eclipse version.

Hope this Helps you!

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'   
                                         ^^^^^

The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

Javascript replace with reference to matched group?

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';
})

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")

EDIT by Liran H: For six other people including myself, $1 did not work, whereas \1 did.

How do I get class name in PHP?

To get class name you can use ReflectionClass

class MyClass {
    public function myNameIs(){
        return (new \ReflectionClass($this))->getShortName();
    }
}

Turn a single number into single digits Python

The easiest way is to turn the int into a string and take each character of the string as an element of your list:

>>> n = 43365644 
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits)  # use the extends method if you want to add the list to another

It involves a casting operation, but it's readable and acceptable if you don't need extreme performance.

How to set Toolbar text and back arrow color

Inside Activity, you can use

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));

If you love to choose xml for both title color & back arrow white just add this style in style.xml .

 <style name="ToolBarStyle" parent="Theme.AppCompat">
    <item name="android:textColorPrimary">@android:color/white</item>
    <item name="android:textColorSecondary">@android:color/white</item>
    <item name="actionMenuTextColor">@android:color/white</item>
</style>

And toolbar look like :

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        app:theme="@style/ToolBarStyle"
        android:layout_height="?attr/actionBarSize"
  />

How do I connect to a Websphere Datasource with a given JNDI name?

You need to define a resource reference in your application and then map that logical resource reference to the physical resource (data source) during deployment.

In your web.xml, add the following configuration (modifying the names and properties as appropriate):

<resource-ref>
    <description>Resource reference to my database</description>
    <res-ref-name>jdbc/MyDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

Then, during application deployment, WAS will prompt you to map this resource reference (jdbc/MyDB) to the data source you created in WAS.

In your code, you can obtain the DataSource similar to how you've shown it in your example; however, the JNDI name you'll use to look it up should actually be the resource reference's name you defined (res-ref-name), rather than the JNDI name of the physical data source. Also, you'll need to prefix the res-ref-name with the application naming context (java:comp/env/).

Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");

Using awk to print all columns from the nth to the last

This is what I preferred from all the recommendations:

Printing from the 6th to last column.

ls -lthr | awk '{out=$6; for(i=7;i<=NF;i++){out=out" "$i}; print out}'

or

ls -lthr | awk '{ORS=" "; for(i=6;i<=NF;i++) print $i;print "\n"}'

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards

Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.

Align two inline-blocks left and right on same line

I think one possible solution to this is to use display: table:

.header {
  display: table;
  width: 100%;
  box-sizing: border-box;
}

.header > * {
  display: table-cell;
}

.header > *:last-child {
  text-align: right;  
}

h1 {
  font-size: 32px;
}

nav {
  vertical-align: baseline;
}

JSFiddle: http://jsfiddle.net/yxxrnn7j/1/

Use -notlike to filter out multiple strings in PowerShell

don't use -notLike, -notMatch with Regular-Expression works in one line:

Get-MailBoxPermission -id newsletter | ? {$_.User -NotMatch "NT-AUTORIT.*|.*-Admins|.*Administrators|.*Manage.*"}

How to properly upgrade node using nvm

if you have 4.2 and want to install 5.0.0 then

nvm install v5.0.0 --reinstall-packages-from=4.2

the answer of gabrielperales is right except that he missed the "=" sign at the end. if you don't put the "=" sign then new node version will be installed but the packages won't be installed.

source: sitepoint

How to insert values in two dimensional array programmatically?

In case you don't know in advance how many elements you will have to handle it might be a better solution to use collections instead (https://en.wikipedia.org/wiki/Java_collections_framework). It would be possible also to create a new bigger 2-dimensional array, copy the old data over and insert the new items there, but the collection framework handles this for you automatically.

In this case you could use a Map of Strings to Lists of Strings:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyClass {
    public static void main(String args[]) {
        Map<String, List<String>> shades = new HashMap<>();

        ArrayList<String> shadesOfGrey = new ArrayList<>();
        shadesOfGrey.add("lightgrey");
        shadesOfGrey.add("dimgray");
        shadesOfGrey.add("sgi gray 92");

        ArrayList<String> shadesOfBlue = new ArrayList<>();
        shadesOfBlue.add("dodgerblue 2");
        shadesOfBlue.add("steelblue 2");
        shadesOfBlue.add("powderblue");

        ArrayList<String> shadesOfYellow = new ArrayList<>();
        shadesOfYellow.add("yellow 1");
        shadesOfYellow.add("gold 1");
        shadesOfYellow.add("darkgoldenrod 1");

        ArrayList<String> shadesOfRed = new ArrayList<>();
        shadesOfRed.add("indianred 1");
        shadesOfRed.add("firebrick 1");
        shadesOfRed.add("maroon 1");

        shades.put("greys", shadesOfGrey);
        shades.put("blues", shadesOfBlue);
        shades.put("yellows", shadesOfYellow);
        shades.put("reds", shadesOfRed);

        System.out.println(shades.get("greys").get(0)); // prints "lightgrey"
    }
}

How to clear mysql screen console in windows?

mysql console can cleared out on windows by using shortcut key

CTRL + L

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

Display an image into windows forms

I display images in windows forms when I put it in Load event like this:

    private void Form1_Load( object sender , EventArgs e )
    {
        pictureBox1.ImageLocation = "./image.png"; //path to image
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
    }

How to reload or re-render the entire page using AngularJS

I got this working code for removing cache and reloading the page

View

        <a class="btn" ng-click="reload()">
            <i class="icon-reload"></i> 
        </a>

Controller

Injectors: $scope,$state,$stateParams,$templateCache

       $scope.reload = function() { // To Reload anypage
            $templateCache.removeAll();     
            $state.transitionTo($state.current, $stateParams, { reload: true, inherit: true, notify: true });
        };

Parse RSS with jQuery

(function(url, callback) {
    jQuery.ajax({
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
        dataType: 'json',
        success: function(data) {
            callback(data.responseData.feed);
        }
    });
})('http://news.hitb.org/rss.xml', function(feed){ // Change to desired URL
    var entries = feed.entries, feedList = '';
    for (var i = 0; i < entries.length; i++) {
        feedList +='<li><a href="' + entries[i].link + '">' + entries[i].title + '</a></li>';
    }
    jQuery('.feed > ul').append(feedList);
});


<div class="feed">
        <h4>Hacker News</h4>
        <ul></ul>
</div>

How should I use try-with-resources with JDBC?

Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:

try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
    PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
    try {
        PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
        s.setInt(1, userid);
        return s;
    } catch (SQLException e) { throw new RuntimeException(e); }
    }).get();
    ResultSet resultSet = stmt.executeQuery()) {
}

How to close a Tkinter window by pressing a Button?

With minimal editing to your code (Not sure if they've taught classes or not in your course), change:

def close_window(root): 
    root.destroy()

to

def close_window(): 
    window.destroy()

and it should work.


Explanation:

Your version of close_window is defined to expect a single argument, namely root. Subsequently, any calls to your version of close_window need to have that argument, or Python will give you a run-time error.

When you created a Button, you told the button to run close_window when it is clicked. However, the source code for Button widget is something like:

# class constructor
def __init__(self, some_args, command, more_args):
    #...
    self.command = command
    #...

# this method is called when the user clicks the button
def clicked(self):
    #...
    self.command() # Button calls your function with no arguments.
    #...

As my code states, the Button class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:

def close_window(): 
    root.destroy()

That's not right, though, either, because root is never assigned a value. It would be like typing in print(x) when you haven't defined x, yet.

Looking at your code, I figured you wanted to call destroy on window, so I changed root to window.

How can I create a simple message box in Python?

You can use pyautogui or pymsgbox:

import pyautogui
pyautogui.alert("This is a message box",title="Hello World")

Using pymsgbox is the same as using pyautogui:

import pymsgbox
pymsgbox.alert("This is a message box",title="Hello World")

Oracle - How to create a readonly user

It is not strictly possible in default db due to the many public executes that each user gains automatically through public.

How to install pip for Python 3 on Mac OS X?

On MacOS 10.12

download pip: pip as get-pip.py

download python3: python3

  1. install python3
  2. open terminal: python3 get-pip.py
  3. pip3 is available

Get local IP address

There is a more accurate way when there are multi ip addresses available on local machine. Connect a UDP socket and read its local endpoint:

string localIP;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
    socket.Connect("8.8.8.8", 65530);
    IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
    localIP = endPoint.Address.ToString();
}

Connect on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.

So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.

Programmatically change the src of an img tag

Maybe because you have a tag like a parent of the tag. That why you have to click two time the images.

For me the solution is this: http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb

Efficient way to rotate a list in python

def solution(A, K):
    if len(A) == 0:
        return A

    K = K % len(A)

    return A[-K:] + A[:-K]

# use case
A = [1, 2, 3, 4, 5, 6]
K = 3
print(solution(A, K))

For example, given

A = [3, 8, 9, 7, 6]
K = 3

the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]

For another example, given

A = [0, 0, 0]
K = 1

the function should return [0, 0, 0]

Given

A = [1, 2, 3, 4]
K = 4

the function should return [1, 2, 3, 4]

Class Diagrams in VS 2017

In addition to @ericgol's answer: In the French version of Visual Studio Community 2017, type "Concepteur de classes" in the search bar.

How to change the Title of the window in Qt?

system("title WhateverYouWantToNameIt");

How do I compare two strings in Perl?

The obvious subtext of this question is:

why can't you just use == to check if two strings are the same?

Perl doesn't have distinct data types for text vs. numbers. They are both represented by the type "scalar". Put another way, strings are numbers if you use them as such.

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7

Since text and numbers aren't differentiated by the language, we can't simply overload the == operator to do the right thing for both cases. Therefore, Perl provides eq to compare values as text:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true

In short:

  • Perl doesn't have a data-type exclusively for text strings
  • use == or !=, to compare two operands as numbers
  • use eq or ne, to compare two operands as text

There are many other functions and operators that can be used to compare scalar values, but knowing the distinction between these two forms is an important first step.

Prevent scroll-bar from adding-up to the Width of page on Chrome

Webkit browsers like Safari and Chrome subtract the scroll bar width from the visible page width when calculating width: 100% or 100vw. More at DM Rutherford's Scrolling and Page Width.

Try using overflow-y: overlay instead.

Converting an integer to a string in PHP

$amount = 2351.25;
$str_amount = "2351.25";

$strCorrectAmount = "$amount";
echo gettype($strCorrectAmount);    //string

So the echo will be return string.

R not finding package even after package installation

So the package will be downloaded in a temp folder C:\Users\U122337.BOSTONADVISORS\AppData\Local\Temp\Rtmp404t8Y\downloaded_packages from where it will be installed into your library folder, e.g. C:\R\library\zoo

What you have to do once install command is done: Open Packages menu -> Load package...

You will see your package on the list. You can automate this: How to load packages in R automatically?

Usage of MySQL's "IF EXISTS"

SELECT IF((
     SELECT count(*) FROM gdata_calendars 
     WHERE `group` =  ? AND id = ?)
,1,0);

For Detail explanation you can visit here

What is the right way to check for a null string in Objective-C?

if ([strpass isEqual:[NSNull null]] || strpass==nil || [strpass isEqualToString:@"<null>"] || [strpass isEqualToString:@"(null)"] || strpass.length==0 || [strpass isEqualToString:@""])
{
    //string is blank  
}

Android Shared preferences for creating one time activity (example)

public class Preferences {

public static final String PREF_NAME = "your preferences name";

@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;

public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";

public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";

public static void writeBoolean(Context context, String key, boolean value) {
    getEditor(context).putBoolean(key, value).commit();
}

public static boolean readBoolean(Context context, String key,
        boolean defValue) {
    return getPreferences(context).getBoolean(key, defValue);
}

public static void writeInteger(Context context, String key, int value) {
    getEditor(context).putInt(key, value).commit();

}

public static int readInteger(Context context, String key, int defValue) {
    return getPreferences(context).getInt(key, defValue);
}

public static void writeString(Context context, String key, String value) {
    getEditor(context).putString(key, value).commit();

}

public static String readString(Context context, String key, String defValue) {
    return getPreferences(context).getString(key, defValue);
}

public static void writeFloat(Context context, String key, float value) {
    getEditor(context).putFloat(key, value).commit();
}

public static float readFloat(Context context, String key, float defValue) {
    return getPreferences(context).getFloat(key, defValue);
}

public static void writeLong(Context context, String key, long value) {
    getEditor(context).putLong(key, value).commit();
}

public static long readLong(Context context, String key, long defValue) {
    return getPreferences(context).getLong(key, defValue);
}

public static SharedPreferences getPreferences(Context context) {
    return context.getSharedPreferences(PREF_NAME, MODE);
}

public static Editor getEditor(Context context) {
    return getPreferences(context).edit();
}

}

****Use Preferences to Write value using:-****

Preferences.writeString(getApplicationContext(),
                    Preferences.NAME, "dev");

****Use Preferences to Read value using:-****

Preferences.readString(getApplicationContext(), Preferences.NAME,
                    "");

How to cd into a directory with space in the name?

try

DOCS="/cygdrive/c/Users/my\ dir/Documents";

cd "$DOCS"

Is there a portable way to get the current username in Python?

I wrote the plx module some time ago to get the user name in a portable way on Unix and Windows (among other things): http://www.decalage.info/en/python/plx

Usage:

import plx

username = plx.get_username()

(it requires win32 extensions on Windows)

How do I set browser width and height in Selenium WebDriver?

Here is how I do it in Python with Selenium 2.48.0:

from selenium.webdriver import Firefox
driver = Firefox()
driver.set_window_position(0, 0)
driver.set_window_size(1024, 768)

How to change the current URL in javascript?

Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST

function nextImage (){
url = url + 1;  
location.href='http://mywebsite.com/' + url+'.html';
}

How do I change the default application icon in Java?

    /** Creates new form Java Program1*/
    public Java Program1() 


    Image im = null;
    try {
    im = ImageIO.read(getClass().getResource("/image location"));
    } catch (IOException ex) {
    Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);
    }
    setIconImage(im);

This is what I used in the GUI in netbeans and it worked perfectly

.attr('checked','checked') does not work

Why not try IS?

$('selector').is(':checked') /* result true or false */

Look a FAQ: jQuery .is() enjoin us ;-)

How to delete rows in tables that contain foreign keys to other tables

Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table

Link a .css on another folder

I think what you want to do is

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
_x000D_
_x000D_

Mockito How to mock and assert a thrown exception?

Make the exception happen like this:

when(obj.someMethod()).thenThrow(new AnException());

Verify it has happened either by asserting that your test will throw such an exception:

@Test(expected = AnException.class)

Or by normal mock verification:

verify(obj).someMethod();

The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

I'd like to amend PsychoCoders answer: as the user wants to get all controls of a certain type we could use generics in the following way:

    public IEnumerable<T> FindControls<T>(Control control) where T : Control
    {
        // we can't cast here because some controls in here will most likely not be <T>
        var controls = control.Controls.Cast<Control>();

        return controls.SelectMany(ctrl => FindControls<T>(ctrl))
                                  .Concat(controls)
                                  .Where(c => c.GetType() == typeof(T)).Cast<T>();
    }

This way, we can call the function as follows:

private void Form1_Load(object sender, EventArgs e)
{
    var c = FindControls<TextBox>(this);
    MessageBox.Show("Total Controls: " + c.Count());
}

How To limit the number of characters in JTextField?

Just put this code in KeyTyped event:

    if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
        evt.consume();
    }

Where "20" is the maximum number of characters that you want.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

How to create Java gradle project

I just tried with with Eclipse Neon.1 and Gradle:

------------------------------------------------------------
Gradle 3.2.1
------------------------------------------------------------

Build time:   2016-11-22 15:19:54 UTC
Revision:     83b485b914fd4f335ad0e66af9d14aad458d2cc5

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_112 (Oracle Corporation 25.112-b15)
OS:           Windows 10 10.0 amd64

enter image description here

On windows 10 with Java Version:

C:\FDriveKambiz\repo\gradle-gen-project>java -version
java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b15, mixed mode)

And it failed miserably as you can see in Eclipse. But sailed like a soaring eagle in Intellij...I dont know Intellij, and a huge fan of eclipse, but common dudes, this means NO ONE teste Neon.1 for the simplest of use cases...to import a gradle project. That is not good enough. I am switching to Intellij for gradle projects:

enter image description here

Intent.putExtra List

Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)

Here is a skeleton of the code you need:

  1. Declare List

    private List<String> test;
    
  2. Init List at appropriate place

    test = new ArrayList<String>();
    

    and add data as appropriate to test.

  3. Pass to intent as follows:

    Intent intent = getIntent();  
    intent.putStringArrayListExtra("test", (ArrayList<String>) test);
    
  4. Retrieve data as follows:

    ArrayList<String> test = getIntent().getStringArrayListExtra("test");
    

Hope that helps.

CSS :selected pseudo class similar to :checked, but for <select> elements

This worked for me :

select option {
   color: black;
}
select:not(:checked) {
   color: gray;
}

ASP.NET MVC: Custom Validation by DataAnnotation

Background:

Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

public class EmployeeModel 
{
    [Required]
    [UniqueEmailAddress]
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}
}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
{
    private IEmployeeRepository _employeeRepository;
    [Inject]
    public IEmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository; }
        set
        {
            _employeeRepository = value;
        }
    }
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
    {
        var model = (EmployeeModel)validationContext.ObjectInstance;
        if(model.Field1 == null){
            return new ValidationResult("Field1 is null");
        }
        if(model.Field2 == null){
            return new ValidationResult("Field2 is null");
        }
        if(model.Field3 == null){
            return new ValidationResult("Field3 is null");
        }
        return ValidationResult.Success;
    }
}

Hope this helps. Cheers !

References

HttpURLConnection timeout settings

You can set timeout like this,

con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);

Which command do I use to generate the build of a Vue app?

The commands for what specific codes to run are listed inside your package.json file under scripts. Here is an example of mine:

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

If you are looking to run your site locally, you can test it with

npm serve

If you are looking to prep your site for production, you would use

npm build

This command will generate a dist folder that has a compressed version of your site.

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

  1. Declare the variable
  2. Set it by your command and add dynamic parts like use parameter values of sp(here @IsMonday and @IsTuesday are sp params)
  3. execute the command

    declare  @sql varchar (100)
    set @sql ='select * from #td1'
    
    if (@IsMonday+@IsTuesday !='')
    begin
    set @sql= @sql+' where PickupDay in ('''+@IsMonday+''','''+@IsTuesday+''' )'
    end
    exec( @sql)
    

AngularJS custom filter function

Additionally, if you want to use the filter in your controller the same way you do it here:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

You could do something like:

var filteredItems =  $scope.$eval('items | filter:filter:criteriaMatch(criteria)');

How do I get the entity that represents the current user in Symfony2?

Symfony 4+, 2019+ Approach

In symfony 4 (probably 3.3 also, but only real-tested in 4) you can inject the Security service via auto-wiring in the controller like this:

<?php

use Symfony\Component\Security\Core\Security;

class SomeClass
{
    /**
     * @var Security
     */
    private $security;

    public function __construct(Security $security)
    {
       $this->security = $security;
    }

    public function privatePage() : Response
    {
        $user = $this->security->getUser(); // null or UserInterface, if logged in
        // ... do whatever you want with $user
    }
}

Symfony 2- Approach

As @ktolis says, you first have to configure your /app/config/security.yml.

Then with

$user = $this->get('security.token_storage')->getToken()->getUser();
$user->getUsername();

should be enougth!

$user is your User Object! You don't need to query it again.

Find out the way to set up your providers in security.yml from Sf2 Documentation and try again.

Best luck!

Center an item with position: relative

Much simpler:

position: relative; 
left: 50%;
transform: translateX(-50%);

You are now centered in your parent element. You can do that vertically too.

How to animate button in android?

I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:

shake.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"          <!-- how long the animation lasts -->
    android:fromDegrees="-5"        <!-- how far to swing left -->
    android:pivotX="50%"            <!-- pivot from horizontal center -->
    android:pivotY="50%"            <!-- pivot from vertical center -->
    android:repeatCount="10"        <!-- how many times to swing back and forth -->
    android:repeatMode="reverse"    <!-- to make the animation go the other way -->
    android:toDegrees="5" />        <!-- how far to swing right -->

Class.java

Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);

This is just one way of doing what you want, there may be better methods out there.

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

C# windows application Event: CLR20r3 on application start

.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.

How to save user input into a variable in html and js

Like I use on PHP and JavaScript:

<input type="hidden" id="CatId" value="<?php echo $categoryId; ?>">

Update the JavaScript:

var categoryId = document.getElementById('CatId').value;

How to check if the given string is palindrome?

A simple Java solution:

public boolean isPalindrome(String testString) {
    StringBuffer sb = new StringBuffer(testString);
    String reverseString = sb.reverse().toString();

    if(testString.equalsIgnoreCase(reverseString)) {
        return true;
    else {
        return false;
    }
}

Check if string is neither empty nor space in shell script

Another quick test for a string to have something in it but space.

if [[ -n "${str// /}" ]]; then
    echo "It is not empty!"
fi

"-n" means non-zero length string.

Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.

You can read more about string manipulation in bash shell scripting here.

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

I had similar issue with selenium: I downgraded my selenium using NuGet and got the same error message. My solution was to remove the newer version lines from the app.config file.

Hash table runtime complexity (insert, search and delete)

Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).

Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I faced the same error and in my case, I change the Server Port Number to 3308 where previously it was 3306. This connect my project to the MySQL database.

enter image description here

Here we have to change the connection code also.

Class.forName("com.mysql.cj.jdbc.Driver");
cn=(java.sql.Connection)DriverManager.getConnection("jdbc:mysql://localhost:3308/test2?zeroDateTimeBehavior=convertToNull","root","");

Changing the port number in the connection code is also necessary as localhost:3308 to resolved the error.

Also, the admin properties in my case. enter image description here

Lodash - difference between .extend() / .assign() and .merge()

Lodash version 3.10.1

Methods compared

  • _.merge(object, [sources], [customizer], [thisArg])
  • _.assign(object, [sources], [customizer], [thisArg])
  • _.extend(object, [sources], [customizer], [thisArg])
  • _.defaults(object, [sources])
  • _.defaultsDeep(object, [sources])

Similarities

  • None of them work on arrays as you might expect
  • _.extend is an alias for _.assign, so they are identical
  • All of them seem to modify the target object (first argument)
  • All of them handle null the same

Differences

  • _.defaults and _.defaultsDeep processes the arguments in reverse order compared to the others (though the first argument is still the target object)
  • _.merge and _.defaultsDeep will merge child objects and the others will overwrite at the root level
  • Only _.assign and _.extend will overwrite a value with undefined

Tests

They all handle members at the root in similar ways.

_.assign      ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.merge       ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.defaults    ({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }
_.defaultsDeep({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }

_.assign handles undefined but the others will skip it

_.assign      ({}, { a: 'a'  }, { a: undefined }) // => { a: undefined }
_.merge       ({}, { a: 'a'  }, { a: undefined }) // => { a: "a" }
_.defaults    ({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
_.defaultsDeep({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }

They all handle null the same

_.assign      ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.merge       ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.defaults    ({}, { a: null }, { a: 'bb' }) // => { a: null }
_.defaultsDeep({}, { a: null }, { a: 'bb' }) // => { a: null }

But only _.merge and _.defaultsDeep will merge child objects

_.assign      ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "b": "bb" }}
_.merge       ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
_.defaults    ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a" }}
_.defaultsDeep({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}

And none of them will merge arrays it seems

_.assign      ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.merge       ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.defaults    ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }
_.defaultsDeep({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }

All modify the target object

a={a:'a'}; _.assign      (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.merge       (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaults    (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaultsDeep(a, {b:'bb'}); // a => { a: "a", b: "bb" }

None really work as expected on arrays

Note: As @Mistic pointed out, Lodash treats arrays as objects where the keys are the index into the array.

_.assign      ([], ['a'], ['bb']) // => [ "bb" ]
_.merge       ([], ['a'], ['bb']) // => [ "bb" ]
_.defaults    ([], ['a'], ['bb']) // => [ "a"  ]
_.defaultsDeep([], ['a'], ['bb']) // => [ "a"  ]

_.assign      ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.merge       ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.defaults    ([], ['a','b'], ['bb']) // => [ "a", "b"  ]
_.defaultsDeep([], ['a','b'], ['bb']) // => [ "a", "b"  ]

How to deep merge instead of shallow merge?

function isObject(obj) {
    return obj !== null && typeof obj === 'object';
}
const isArray = Array.isArray;

function isPlainObject(obj) {
    return isObject(obj) && (
        obj.constructor === Object  // obj = {}
        || obj.constructor === undefined // obj = Object.create(null)
    );
}

function mergeDeep(target, ...sources){
    if (!sources.length) return target;
    const source = sources.shift();

    if (isPlainObject(source) || isArray(source)) {
        for (const key in source) {
            if (isPlainObject(source[key]) || isArray(source[key])) {
                if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
                    target[key] = {};
                }else if (isArray(source[key]) && !isArray(target[key])) {
                    target[key] = [];
                }
                mergeDeep(target[key], source[key]);
            } else if (source[key] !== undefined && source[key] !== '') {
                target[key] = source[key];
            }
        }
    }

    return mergeDeep(target, ...sources);
}

// test...
var source = {b:333};
var source2 = {c:32, arr: [33,11]}
var n = mergeDeep({a:33}, source, source2);
source2.arr[1] = 22;
console.log(n.arr); // out: [33, 11]

jquery variable syntax

This is pure JavaScript.

There is nothing special about $. It is just a character that may be used in variable names.

var $ = 1;
var $$ = 2;
alert($ + $$);

jQuery just assigns it's core function to a variable called $. The code you have assigns this to a local variable called self and the results of calling jQuery with this as an argument to a global variable called $self.

It's ugly, dirty, confusing, but $, self and $self are all different variables that happen to have similar names.

How can I view array structure in JavaScript with alert()?

I'd recommend using toString().

Ex. alert(array.toString()), or console.log(array.toString())

Debugging Spring configuration

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

java -jar myapp.jar --debug

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

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

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

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

Make a simple fade in animation in Swift?

If you want repeatable fade animation you can do that by using CABasicAnimation like below :

First create handy UIView extension :

extension UIView {

    enum AnimationKeyPath: String {
        case opacity = "opacity"
    }

    func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
        let flash = CABasicAnimation(keyPath: animation.rawValue)
        flash.duration = duration
        flash.fromValue = 1 // alpha
        flash.toValue = 0 // alpha
        flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = repeatCount

        layer.add(flash, forKey: nil)
    }
}

How to use it:

    // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
    imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)

How to create a custom attribute in C#

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

Android Studio does not show layout preview

Changing the theme(near the android symbol for changing API version) from AppTheme to anything else like DeviceDefault or Holo fixed the problem easily.

Defining private module functions in python

This is an ancient question, but both module private (one underscore) and class-private (two underscores) mangled variables are now covered in the standard documentation:

The Python Tutorial » Classes » Private Variables

Split string into individual words Java

You can use split(" ") method of the String class and can get each word as code given below:

String s = "I want to walk my dog";
String []strArray=s.split(" ");
for(int i=0; i<strArray.length;i++) {
     System.out.println(strArray[i]);
}

JavaScript function in href vs. onclick

In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.

In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.

In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.


However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
    $('a#link').click(function(){ /* ... action ... */ })
</script>

How to fetch all Git branches

You can fetch all the branches by:

git fetch --all

or:

git fetch origin --depth=10000 $(git ls-remote -h -t origin)

The --depth=10000 parameter may help if you've shallowed repository.


To pull all the branches, use:

git pull --all

If above won't work, then precede the above command with:

git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'

as the remote.origin.fetch could support only a specific branch while fetching, especially when you cloned your repo with --single-branch. Check this by: git config remote.origin.fetch.

After that you should be able to checkout any branch.

See also:


To push all the branches to the remote, use:

git push --all

eventually --mirror to mirror all refs.


If your goal is to duplicate a repository, see: Duplicating a repository article at GitHub.

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

Align nav-items to right side in bootstrap-4

This should work for alpha 6. The key is the class "mr-auto" on the left nav, which will push the right nav to the right. You also need to add navbar-toggleable-md or it will stack in a column instead of a row. Note I didn't add the remaining toggle items (e.g. toggle button), I added just enough to get it to formatted as requested. Here are more complete examples https://v4-alpha.getbootstrap.com/examples/navbars/.

<!DOCTYPE html>
<html lang="en">
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
        <div class="container">
            <a class="navbar-brand" href="#">Navbar</a>
            <ul class="nav navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
            </ul>
            <ul class="nav navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="#">Link on the Right</a>
                </li>
            </ul>
        </div>
    </nav>
</body>

How do I search for an object by its ObjectId in the mongo console?

Simply do:

db.getCollection('test').find('4ecbe7f9e8c1c9092c000027');

Solve Cross Origin Resource Sharing with Flask

Note: The placement of cross_origin should be right and dependencies are installed. On the client side, ensure to specify kind of data server is consuming. For example application/json or text/html

For me the code written below did magic

from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app=Flask(__name__)
CORS(app, support_credentials=True)
@app.route('/api/test', methods=['POST', 'GET','OPTIONS'])
@cross_origin(supports_credentials=True)
def index():
    if(request.method=='POST'):
     some_json=request.get_json()
     return jsonify({"key":some_json})
    else:
        return jsonify({"GET":"GET"})


if __name__=="__main__":
    app.run(host='0.0.0.0', port=5000)

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

What size should apple-touch-icon.png be for iPad and iPhone?

The relevant documentation on Apple's site, Specifying a Webpage Icon for Web Clip.

There is no need to put anything in the head of your document. If no icons are specified using a link element, the website root directory is searched for icons with the apple-touch-icon or apple-touch-icon-precomposed prefix.

For example, if the appropriate icon size for the device is 57 x 57, the system searches for filenames in the following order:

  • apple-touch-icon-57x57-precomposed.png
  • apple-touch-icon-57x57.png
  • apple-touch-icon-precomposed.png
  • apple-touch-icon.png

Google Maps API v3: How to remove all markers?

Here you can find an example of how to remove markers:

https://developers.google.com/maps/documentation/javascript/examples/marker-remove?hl=es

// Add a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}

// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
   }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
}

MongoDB or CouchDB - fit for production?

I'm the CTO of 10gen (developers of MongoDB) so I'm a bit biased, but I also manage a few sites that are using MongoDB in production.

businessinsider has been using mongo in production for over a year now. They are using it for everything from users and blog posts, to every image on the site.

shopwiki is using it for a few things including real time analytics and a caching layer. They are doing over 1000 writes per second to a fairly large database.

If you go to the mongodb Production Deployments page you'll see some people who are using mongo in production.

If you have any questions about the scale or scope of production deployments, post on our user list and we'll be more than happy to help.

Why is my toFixed() function not working?

Your conversion data is response[25] and follow the below steps.

var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34

Checking if an object is a given type in Swift

In Swift 2.2 - 5 you can now do:

if object is String
{
}

Then to filter your array:

let filteredArray = originalArray.filter({ $0 is Array })

If you have multiple types to check:

    switch object
    {
    case is String:
        ...

    case is OtherClass:
        ...

    default:
        ...
    }