Programs & Examples On #Nicedit

NicEdit is an open source inline WYSIWYG HTML editor

What killed my process and why?

In my case this was happening with a Laravel queue worker. The system logs did not mention any killing so I looked further and it turned out that the worker was basically killing itself because of a job that exceeded the memory limit (which is set to 128M by default).

Running the queue worker with --timeout=600 and --memory=1024 fixed the problem for me.

In an array of objects, fastest way to find the index of an object whose attributes match a search

I've created a tiny utility called super-array where you can access items in an array by a unique identifier with O(1) complexity. Example:

const SuperArray = require('super-array');

const myArray = new SuperArray([
  {id: 'ab1', name: 'John'},
  {id: 'ab2', name: 'Peter'},
]);

console.log(myArray.get('ab1')); // {id: 'ab1', name: 'John'}
console.log(myArray.get('ab2')); // {id: 'ab2', name: 'Peter'}

C# : changing listbox row color?

I think you have to draw the listitems yourself to achieve this.

Here's a post with the same kind of question.

Changing an AIX password via script?

Use GNU passwd stdin flag.

From the man page:

   --stdin
          This option is used to indicate that passwd should read the new password from standard input, which can be a pipe.

NOTE: Only for root user.

Example

$ adduser foo 
$ echo "NewPass" |passwd foo --stdin
Changing password for user foo.
passwd: all authentication tokens updated successfully.

Alternatively you can use expect, this simple code will do the trick:

#!/usr/bin/expect
spawn passwd foo
expect "password:"
send "Xcv15kl\r"
expect "Retype new password:"
send "Xcv15kl\r"
interact

Results

$ ./passwd.xp 
spawn passwd foo
Changing password for user foo.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.

Check if application is installed - Android

Try this:

public static boolean isAvailable(Context ctx, Intent intent) {
    final PackageManager mgr = ctx.getPackageManager();
    List<ResolveInfo> list =
        mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

https connection using CURL from command line

Simple solution

That's my everyday script:

curl --insecure -v https://www.google.com 2>&1 | awk 'BEGIN { cert=0 } /^\* Server certificate:/ { cert=1 } /^\*/ { if (cert) print }'

Output:

* Server certificate:
*    subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=www.google.com
*    start date: 2016-01-07 11:34:33 GMT
*    expire date: 2016-04-06 00:00:00 GMT
*    issuer: C=US; O=Google Inc; CN=Google Internet Authority G2
*    SSL certificate verify ok.
* Server GFE/2.0 is not blacklisted
* Connection #0 to host www.google.com left intact

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

OnItemCLickListener not working in listview

The thing that worked for me was to add the below code to every subview inside the layout of my row.xml file:

android:focusable="false"
android:focusableInTouchMode="false"

So in my case:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:id="@+id/testingId"
        android:text="Name"
       //other stuff 
        />

    <TextView
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:id="@+id/dummyId"
        android:text="icon"
        //other stuff 
        />

    <TextView
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:id="@+id/assignmentColor"
       //other stuff 
       />

    <TextView
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:id="@+id/testID"
        //other stuff 
        />

    <TextView
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="TextView"
        //other stuff 
        />

</android.support.constraint.ConstraintLayout>

And this is my setOnItemClickListener call in my Fragment subclass:

CustomListView = (PullToRefreshListCustomView) layout.findViewById(getListResourceID());
        CustomListView.setAdapter(customAdapter);
        CustomListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("Testing", "onitem click working");
              //  other code
            }

        });

I got the answer from here!

Bash Templating: How to build configuration files from templates with Bash?

Taking the answer from ZyX using pure bash but with new style regex matching and indirect parameter substitution it becomes:

#!/bin/bash
regex='\$\{([a-zA-Z_][a-zA-Z_0-9]*)\}'
while read line; do
    while [[ "$line" =~ $regex ]]; do
        param="${BASH_REMATCH[1]}"
        line=${line//${BASH_REMATCH[0]}/${!param}}
    done
    echo $line
done

how to use Spring Boot profiles

The @Profile annotation allows you to indicate that a component is eligible for registration when one or more specified profiles are active. Using our example above, we can rewrite the dataSource configuration as follows:

@Configuration
@Profile("dev")
public class StandaloneDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:com/bank/config/sql/schema.sql")
            .addScript("classpath:com/bank/config/sql/test-data.sql")
            .build();
    }
}

And other one:

@Configuration
@Profile("production")
public class JndiDataConfig {

    @Bean(destroyMethod="")
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
    }
}

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

Convert JSON String to JSON Object c#

This does't work in case of the JObject this works for the simple json format data. I have tried my data of the below json format data to deserialize in the type but didn't get the response.

For this Json

{
  "Customer": {
    "id": "Shell",
    "Installations": [
      {
        "id": "Shell.Bangalore",
        "Stations": [
          {
            "id": "Shell.Bangalore.BTM",
            "Pumps": [
              {
                "id": "Shell.Bangalore.BTM.pump1"
              },
              {
                "id": "Shell.Bangalore.BTM.pump2"
              },
              {
                "id": "Shell.Bangalore.BTM.pump3"
              }
            ]
          },
          {
            "id": "Shell.Bangalore.Madiwala",
            "Pumps": [
              {
                "id": "Shell.Bangalore.Madiwala.pump4"
              },
              {
                "id": "Shell.Bangalore.Madiwala.pump5"
              }
            ]
          }
        ]
      }
    ]
  }
}

How to check if X server is running?

You can use xdpyinfo (can be installed via apt-get install x11-utils).

How to upgrade Angular CLI project?

According to the documentation on here http://angularjs.blogspot.co.uk/2017/03/angular-400-now-available.html you 'should' just be able to run...

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save

I tried it and got a couple of errors due to my zone.js and ngrx/store libraries being older versions.

Updating those to the latest versions npm install zone.js@latest --save and npm install @ngrx/store@latest -save, then running the angular install again worked for me.

Input group - two inputs close to each other

My solution requires no additional css and works with any combination of input-addon, input-btn and form-control. It just uses pre-existing bootstrap classes

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
    <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MinVal">_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MaxVal">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

This will be inline if there is space and wrap for smaller screens.

Full Example ( input-addon, input-btn and form-control. )

jsfiddle

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <br>_x000D_
_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to use goto statement correctly

The Java keyword list specifies the goto keyword, but it is marked as "not used".

This was probably done in case it were to be added to a later version of Java.

If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

Changing background color of text box input not working when empty

<! DOCTYPE html>
<html>
<head></head>
<body>

    <input type="text" id="subEmail">


    <script type="text/javascript">

        window.onload = function(){

        var subEmail = document.getElementById("subEmail");

        subEmail.onchange = function(){

            if(subEmail.value == "")
            {
                subEmail.style.backgroundColor = "red";
            }
            else
            {
               subEmail.style.backgroundColor = "yellow"; 
            }
        };

    };



    </script>

</body>

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

How to select a node of treeview programmatically in c#?

treeViewMain.SelectedNode = treeViewMain.Nodes.Find(searchNode, true)[0];

where searchNode is the name of the node. I'm personally using a combo "Node + Panel" where Node name is Node + and the same tag is also set on panel of choice. With this command + scan of panels by tag i'm usually able to work a treeview+panel full menu set.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Maybe It is OpenJPA's bug, When rollback it reset the @Version field, but the pcVersionInit keep true. I have a AbstraceEntity which declared the @Version field. I can workaround it by reset the pcVersionInit field. But It is not a good idea. I think it not work when have cascade persist entity.

    private static Field PC_VERSION_INIT = null;
    static {
        try {
            PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
            PC_VERSION_INIT.setAccessible(true);
        } catch (NoSuchFieldException | SecurityException e) {
        }
    }

    public T call(final EntityManager em) {
                if (PC_VERSION_INIT != null && isDetached(entity)) {
                    try {
                        PC_VERSION_INIT.set(entity, false);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                    }
                }
                em.persist(entity);
                return entity;
            }

            /**
             * @param entity
             * @param detached
             * @return
             */
            private boolean isDetached(final Object entity) {
                if (entity instanceof PersistenceCapable) {
                    PersistenceCapable pc = (PersistenceCapable) entity;
                    if (pc.pcIsDetached() == Boolean.TRUE) {
                        return true;
                    }
                }
                return false;
            }

Difference between Math.Floor() and Math.Truncate()

Some examples:

Round(1.5) = 2
Round(2.5) = 2
Round(1.5, MidpointRounding.AwayFromZero) = 2
Round(2.5, MidpointRounding.AwayFromZero) = 3
Round(1.55, 1) = 1.6
Round(1.65, 1) = 1.6
Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6
Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7

Truncate(2.10) = 2
Truncate(2.00) = 2
Truncate(1.90) = 1
Truncate(1.80) = 1

Static array vs. dynamic array in C++

static is a keyword in C and C++, so rather than a general descriptive term, static has very specific meaning when applied to a variable or array. To compound the confusion, it has three distinct meanings within separate contexts. Because of this, a static array may be either fixed or dynamic.

Let me explain:

The first is C++ specific:

  • A static class member is a value that is not instantiated with the constructor or deleted with the destructor. This means the member has to be initialized and maintained some other way. static member may be pointers initialized to null and then allocated the first time a constructor is called. (Yes, that would be static and dynamic)

Two are inherited from C:

  • within a function, a static variable is one whose memory location is preserved between function calls. It is static in that it is initialized only once and retains its value between function calls (use of statics makes a function non-reentrant, i.e. not threadsafe)

  • static variables declared outside of functions are global variables that can only be accessed from within the same module (source code file with any other #include's)

The question (I think) you meant to ask is what the difference between dynamic arrays and fixed or compile-time arrays. That is an easier question, compile-time arrays are determined in advance (when the program is compiled) and are part of a functions stack frame. They are allocated before the main function runs. dynamic arrays are allocated at runtime with the "new" keyword (or the malloc family from C) and their size is not known in advance. dynamic allocations are not automatically cleaned up until the program stops running.

How to set the 'selected option' of a select dropdown list with jquery

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

optional parameters in SQL Server stored proc?

Yes, it is. Declare parameter as so:

@Sort varchar(50) = NULL

Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).

How to reset or change the passphrase for a GitHub SSH key?

You can change the passphrase for your private key by doing:

ssh-keygen -f ~/.ssh/id_rsa -p

Make Vim show ALL white spaces as a character

I was frustrated with all of the other answers to this question, because none of them highlight the space character in a useful way. Showing spaces as characters would particularly help for whitespace-formatted languages, where mixing tabs and spaces is harmful.

My solution is to show tabs and underline multiple spaces. It borrows from mrucci's answer and this tutorial. Because it uses syntax highlighting, it's persistent:

set list listchars=tab:\|\ 
highlight Whitespace cterm=underline gui=underline ctermbg=NONE guibg=NONE ctermfg=yellow guifg=yellow
autocmd ColorScheme * highlight Whitespace gui=underline ctermbg=NONE guibg=NONE ctermfg=yellow guifg=yellow
match Whitespace /  \+/

Using this, tabs are displayed as | and spaces as _, which makes it very easy to tell when I'm mixing code styles.

The only downside I've found is that this snippet doesn't adjust background color to match the context (like in a comment).

Using DateTime in a SqlParameter for Stored Procedure, format error

Just use:

 param.AddWithValue("@Date_Of_Birth",DOB);

That will take care of all your problems.

String replacement in java, similar to a velocity template

I use GroovyShell in java to parse template with Groovy GString:

Binding binding = new Binding();
GroovyShell gs = new GroovyShell(binding);
// this JSONObject can also be replaced by any Java Object
JSONObject obj = new JSONObject();
obj.put("key", "value");
binding.setProperty("obj", obj)
String str = "${obj.key}";
String exp = String.format("\"%s\".toString()", str);
String res = (String) gs.evaluate(exp);
// value
System.out.println(str);

Reset the Value of a Select Box

I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.

The easiest way to "reset" a select element is to set its selectedIndex property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:

function resetSelectElement(selectElement) {
    selecElement.selectedIndex = 0;  // first option is selected, or
                                     // -1 for no option selected
}

However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:

function resetSelectElement(selectElement) {
    var options = selectElement.options;

    // Look for a default selected option
    for (var i=0, iLen=options.length; i<iLen; i++) {

        if (options[i].defaultSelected) {
            selectElement.selectedIndex = i;
            return;
        }
    }

    // If no option is the default, select first or none as appropriate
    selectElement.selectedIndex = 0; // or -1 for no option selected
}

And beware of setting attributes rather than properties, they have different effects in different browsers.

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

MySQL server has gone away - in exactly 60 seconds

I had this problem recently. I stumbled across an option: default_authentication_plugin

For some reason it had set it to caching_sha2_password, but updating the value to mysql_native_password fixed it for me. I'm not sure what the differences are, though, so be careful!

Hope this helps someone!

IIS - can't access page by ip address instead of localhost

Check the settings of the browser proxy . For me it helped , traffic was directed outside.

What's the difference between Docker Compose vs. Dockerfile

"better" is relative. It all depends on what your needs are. Docker compose is for orchestrating multiple containers. If these images already exist in the docker registry, then it's better to list them in the compose file. If these images or some other images have to be built from files on your computer, then you can describe the processes of building those images in a Dockerfile.

I understand that Dockerfiles are used in Docker Compose, but I am not sure if it is good practice to put everything in one large Dockerfile with multiple FROM commands for the different images?

Using multiple FROM in a single dockerfile is not a very good idea because there is a proposal to remove the feature. 13026

If for instance, you want to dockerize an application which uses a database and have the application files on your computer, you can use a compose file together with a dockerfile as follows

docker-compose.yml

mysql:
  image: mysql:5.7
  volumes:
    - ./db-data:/var/lib/mysql
  environment:
    - "MYSQL_ROOT_PASSWORD=secret"
    - "MYSQL_DATABASE=homestead"
    - "MYSQL_USER=homestead"
  ports:
    - "3307:3306"
app:
  build:
    context: ./path/to/Dockerfile
    dockerfile: Dockerfile
  volumes:
    - ./:/app
  working_dir: /app
      

Dockerfile

FROM php:7.1-fpm 
RUN apt-get update && apt-get install -y libmcrypt-dev \
  mysql-client libmagickwand-dev --no-install-recommends \
  && pecl install imagick \
  && docker-php-ext-enable imagick \
  && docker-php-ext-install pdo_mysql \
  && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

What does '<?=' mean in PHP?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass.

Example:

$user_list = array(
    'dave' => 'apassword',
    'steve' => 'secr3t'
);

foreach ($user_list as $user => $pass) {
    echo "{$user}'s pass is: {$pass}\n";
}
// Prints: 
// "dave's pass is: apassword"
// "steve's pass is: secr3t"

Note that this can be used for numerically indexed arrays too.

Example:

$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
    echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw

WordPress is giving me 404 page not found for all pages except the homepage

after 2 long days, the solution was to add options +FollowSymLinks to the top of my .htaccess file.

sqlplus how to find details of the currently connected database session

select * from v$session
where sid = to_number(substr(dbms_session.unique_session_id,1,4),'XXXX')

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

How to turn NaN from parseInt into 0 for an empty string?

I was surprised to not see anyone mention using Number(). Granted it will parse decimals if provided, so will act differently than parseInt(), however it already assumes base 10 and will turn "" or even " " in to 0.

How to pass password automatically for rsync SSH command?

I got it to work like this:

sshpass -p "password" rsync -ae "ssh -p remote_port_ssh" /local_dir  remote_user@remote_host:/remote_dir

How to enable explicit_defaults_for_timestamp?

First you don't need to change anything yet.

Those nonstandard behaviors remain the default for TIMESTAMP but as of MySQL 5.6.6 are deprecated and this warning appears at startup

Now if you want to move to new behaviors you have to add this line in your my.cnf in the [mysqld] section.

explicit_defaults_for_timestamp = 1

The location of my.cnf (or other config files) vary from one system to another. If you can't find it refer to https://dev.mysql.com/doc/refman/5.7/en/option-files.html

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

It is the problem with your proxy setting in TortoiseSVN. Connect using a network which doesn't use proxy or configure your proxy settings properly.

Re-enabling window.alert in Chrome

I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536

Center a button in a Linear layout

As per the Android documentation for XML Attributes of android:layout_gravity, we can do it easily :)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton android:id="@+id/btnFindMe" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"

        android:layout_gravity="center"

        android:background="@drawable/findme"></ImageButton>

</LinearLayout>

How to execute a function when page has fully loaded?

If you need to use many onload use $(window).load instead (jQuery):

$(window).load(function() {
    //code
});

Printing string variable in Java

If you have tried all the other answers, and it still hasn't work, you can try skipping a line:

Scanner scan = new Scanner(System.in);
scan.nextLine();
String s = scan.nextLine();
System.out.println("String is " + s);

jQuery UI tabs. How to select a tab based on its id not based on index

As per UI Doc :

  1. First get index of tab which you want to activate.

    var index = $('#tabs a[href="'+id+'"]').parent().index();
    
  2. Activate it

    tabs.tabs( "option", "active", index );
    

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

How to import a single table in to mysql database using command line

-> mysql -h host -u user -p database_name table_name < test_table.sql

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

How do I read all classes from a Java package in the classpath?

  1. Bill Burke has written a (nice article about class scanning] and then he wrote Scannotation.

  2. Hibernate has this already written:

    • org.hibernate.ejb.packaging.Scanner
    • org.hibernate.ejb.packaging.NativeScanner
  3. CDI might solve this, but don't know - haven't investigated fully yet

.

@Inject Instance< MyClass> x;
...
x.iterator() 

Also for annotations:

abstract class MyAnnotationQualifier
extends AnnotationLiteral<Entity> implements Entity {}

Does MS Access support "CASE WHEN" clause if connect with ODBC?

I have had to use a multiple IIF statement to create a similar result in ACCESS SQL.

IIf([refi type] Like "FHA ST*","F",IIf([refi type]="VA IRRL","V"))

All remaining will stay Null.

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

How do I get a UTC Timestamp in JavaScript?

I want to make clear that new Date().getTime() does in fact return a UTC value, so it is a really helpful way to store and manage dates in a way that is agnostic to localized times.

In other words, don't bother with all the UTC javascript functions. Instead, just use Date.getTime().

More info on the explanation is here: If javascript "(new Date()).getTime()" is run from 2 different Timezones.

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

Changing the binding information in my web.config (or app.config) - while a "hack" in my view, allows you to move forward with your project after a NuGet package update whacks your application and gives you the System.Net.Http error.

Set oldVersion="0.0.0.0-4.1.1.0" and newVersion="4.0.0.0" as follows

<dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.0.0.0" />
</dependentAssembly>

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

Difference between Convert.ToString() and .ToString()

To understand both the methods let's take an example:

int i =0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i)); 

Here both the methods are used to convert the string but the basic difference between them is: Convert function handles NULL, while i.ToString() does not it will throw a NULL reference exception error. So as good coding practice using convert is always safe.

Let's see another example:

string s;
object o = null;
s = o.ToString(); 
//returns a null reference exception for s. 

string s;
object o = null;
s = Convert.ToString(o); 
//returns an empty string for s and does not throw an exception.

How can I add a box-shadow on one side of an element?

My self-made solution which is easy to edit:

HTML:

<div id="anti-shadow-div">
    <div id="shadow-div"></div>
</div>?

css:

#shadow-div{
    margin-right:20px; /* Set to 0 if you don't want shadow at the right side */
    margin-left:0px; /* Set to 20px if you want shadow at the left side */
    margin-top:0px; /* Set to 20px if you want shadow at the top side */
    margin-bottom:0px; /* Set to 20px if you want shadow at the bottom side */
    box-shadow: 0px 0px 20px black; 
    height:100px;
    width:100px;
    background: red;
}

#anti-shadow-div{
    margin:20px;
    display:table;
    overflow:hidden;
}?

Demo:
http://jsfiddle.net/jDyQt/103

Why I can't change directories using "cd"?

Jeremy Ruten's idea of using a symlink triggered a thought that hasn't crossed any other answer. Use:

CDPATH=:$HOME/projects

The leading colon is important; it means that if there is a directory 'dir' in the current directory, then 'cd dir' will change to that, rather than hopping off somewhere else. With the value set as shown, you can do:

cd java

and, if there is no sub-directory called java in the current directory, then it will take you directly to $HOME/projects/java - no aliases, no scripts, no dubious execs or dot commands.

My $HOME is /Users/jleffler; my $CDPATH is:

:/Users/jleffler:/Users/jleffler/mail:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work

Swift double to string

In swift 3 it is simple as given below

let stringDouble =  String(describing: double)

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

AngularJs $http.post() does not send data

By using very simple method, we can follow this:

 $http({
        url : "submit_form_adv.php",
        method : 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
            var str = [];
            for(var p in obj)
                str.push(encodeURIComponent(p)+' = '+encodeURIComponent(obj[p]));

            return str.join('&');
        },
        data : {sample_id : 100, sample_name: 'Abin John'},

    }).success(function(data, status, headers, config) {

    }).error(function(ata, status, headers, config) {

    });

Disable clipboard prompt in Excel VBA on workbook close

If I may add one more solution: you can simply cancel the clipboard with this command:

Application.CutCopyMode = False

When to use: Java 8+ interface default method, vs. abstract method

Remi Forax rule is You don't design with Abstract classes. You design your app with interfaces. Watever is the version of Java, whatever is the language. It is backed by the Interface segregation principle in SOLID principles.

You can later use Abstract classes to factorize code. Now with Java 8 you can do it directly in the interface. This is a facility, not more.

Date constructor returns NaN in IE, but works in Firefox and Chrome

Here's another approach that adds a method to the Date object

usage: var d = (new Date()).parseISO8601("1971-12-15");

    /**
     * Parses the ISO 8601 formated date into a date object, ISO 8601 is YYYY-MM-DD
     * 
     * @param {String} date the date as a string eg 1971-12-15
     * @returns {Date} Date object representing the date of the supplied string
     */
    Date.prototype.parseISO8601 = function(date){
        var matches = date.match(/^\s*(\d{4})-(\d{2})-(\d{2})\s*$/);

        if(matches){
            this.setFullYear(parseInt(matches[1]));    
            this.setMonth(parseInt(matches[2]) - 1);    
            this.setDate(parseInt(matches[3]));    
        }

        return this;
    };

How to fix "set SameSite cookie to none" warning?

I'm also in a "trial and error" for that, but this answer from Google Chrome Labs' Github helped me a little. I defined it into my main file and it worked - well, for only one third-party domain. Still making tests, but I'm eager to update this answer with a better solution :)

EDIT: I'm using PHP 7.4 now, and this syntax is working good (Sept 2020):

$cookie_options = array(
  'expires' => time() + 60*60*24*30,
  'path' => '/',
  'domain' => '.domain.com', // leading dot for compatibility or use subdomain
  'secure' => true, // or false
  'httponly' => false, // or false
  'samesite' => 'None' // None || Lax || Strict
);

setcookie('cors-cookie', 'my-site-cookie', $cookie_options);

If you have PHP 7.2 or lower (as Robert's answered below):

setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

If your host is already updated to PHP 7.3, you can use (thanks to Mahn's comment):

setcookie('cookieName', 'cookieValue', [
  'expires' => time()+(7*24*3600,
  'path' => '/',
  'domain' => 'domain.com',
  'samesite' => 'None',
  'secure' => true,
  'httponly' => true
]);

Another thing you can try to check the cookies, is to enable the flag below, which—in their own words—"will add console warning messages for every single cookie potentially affected by this change":

chrome://flags/#cookie-deprecation-messages

See the whole code at: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md, they have the code for same-site-cookies too.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

In my case it was issue of html. There was '\n' in json response causing the issue. So I removed that.

Chosen Jquery Plugin - getting selected values

I believe the problem occurs when targeting by ID, because Chosen will copy the ID from the original select onto it's newly created div, leaving you with 2 elements of the same (now not-unique) ID on the current page.

When targeting Chosen by ID, use a selector specific to the select:

$( 'select#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

...instead of...

$( '#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

This works because Chosen mirrors its selected items back to the original (now hidden) select element, even in multi-mode.

(It also continues to work with or without Chosen, say... if you decide to go a different direction in your application.)

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

There's now a simpler way with .NET Standard or .NET Core:

var client = new HttpClient();
var response = await client.PostAsync(uri, myRequestObject, new JsonMediaTypeFormatter());

NOTE: In order to use the JsonMediaTypeFormatter class, you will need to install the Microsoft.AspNet.WebApi.Client NuGet package, which can be installed directly, or via another such as Microsoft.AspNetCore.App.

Using this signature of HttpClient.PostAsync, you can pass in any object and the JsonMediaTypeFormatter will automatically take care of serialization etc.

With the response, you can use HttpContent.ReadAsAsync<T> to deserialize the response content to the type that you are expecting:

var responseObject = await response.Content.ReadAsAsync<MyResponseType>();

Does a `+` in a URL scheme/host/path represent a space?

use encodeURIComponent function to fix url, it works on Browser and node.js

res.redirect("/signin?email="+encodeURIComponent("[email protected]"));


> encodeURIComponent("http://a.com/a+b/c")
'http%3A%2F%2Fa.com%2Fa%2Bb%2Fc'

How to directly move camera to current location in Google Maps Android API v2?

The above answer is not according to what Google Doc Referred for Location Tracking in Google api v2.

I just followed the official tutorial and ended up with this class that is fetching the current location and centring the map on it as soon as i get that.

you can extend this class to have LocationReciever to have periodic Location Update. I just executed this code on api level 7

http://developer.android.com/training/location/retrieve-current.html

Here it goes.

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;


public class MainActivity extends FragmentActivity implements 
    GooglePlayServicesClient.ConnectionCallbacks, 
    GooglePlayServicesClient.OnConnectionFailedListener{

private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
/*
 * Define a request code to send to Google Play services
 * This code is returned in Activity.onActivityResult
 */
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {

    // Global field to contain the error dialog
    private Dialog mDialog;

    // Default constructor. Sets the dialog field to null
    public ErrorDialogFragment() {
        super();
        mDialog = null;
    }

    // Set the dialog to display
    public void setDialog(Dialog dialog) {
        mDialog = dialog;
    }

    // Return a Dialog to the DialogFragment.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    mLocationClient = new LocationClient(this, this, this);

    mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
    map = mapFragment.getMap();

    map.setMyLocationEnabled(true);

}

/*
 * Called when the Activity becomes visible.
 */
@Override
protected void onStart() {
    super.onStart();
    // Connect the client.
    if(isGooglePlayServicesAvailable()){
        mLocationClient.connect();
    }

}

/*
 * Called when the Activity is no longer visible.
 */
@Override
protected void onStop() {
    // Disconnecting the client invalidates it.
    mLocationClient.disconnect();
    super.onStop();
}

/*
 * Handle results returned to the FragmentActivity
 * by Google Play services
 */
@Override
protected void onActivityResult(
                int requestCode, int resultCode, Intent data) {
    // Decide what to do based on the original request code
    switch (requestCode) {

        case CONNECTION_FAILURE_RESOLUTION_REQUEST:
            /*
             * If the result code is Activity.RESULT_OK, try
             * to connect again
             */
            switch (resultCode) {
                case Activity.RESULT_OK:
                    mLocationClient.connect();
                    break;
            }

    }
}

private boolean isGooglePlayServicesAvailable() {
    // Check that Google Play services is available
    int resultCode =  GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status
        Log.d("Location Updates", "Google Play services is available.");
        return true;
    } else {
        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
                                                                                                              this,
                                                                                                              CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();
            errorFragment.setDialog(errorDialog);
            errorFragment.show(getSupportFragmentManager(), "Location Updates");
        }

        return false;
    }
}

/*
 * Called by Location Services when the request to connect the
 * client finishes successfully. At this point, you can
 * request the current location or start periodic updates
 */
@Override
public void onConnected(Bundle dataBundle) {
    // Display the connection status
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    Location location = mLocationClient.getLastLocation();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
    map.animateCamera(cameraUpdate);
}

/*
 * Called by Location Services if the connection to the
 * location client drops because of an error.
 */
@Override
public void onDisconnected() {
    // Display the connection status
    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();
}

/*
 * Called by Location Services if the attempt to
 * Location Services fails.
 */
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
            * Thrown if Google Play services canceled the original
            * PendingIntent
            */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
       Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
    }
}

}

How to convert Milliseconds to "X mins, x seconds" in Java?

Joda-Time

Using Joda-Time:

DateTime startTime = new DateTime();

// do something

DateTime endTime = new DateTime();
Duration duration = new Duration(startTime, endTime);
Period period = duration.toPeriod().normalizedStandard(PeriodType.time());
System.out.println(PeriodFormat.getDefault().print(period));

jQuery Ajax PUT with parameters

For others who wind up here like I did, you can use AJAX to do a PUT with parameters, but they are sent as the body, not as query strings.

Tensorflow import error: No module named 'tensorflow'

I had same issues on Windows 64-bit processor but manage to solve them. Check if your Python is for 32- or 64-bit installation. If it is for 32-bit, then you should download the executable installer (for e.g. you can choose latest Python version - for me is 3.7.3) https://www.python.org/downloads/release/python-373/ -> Scroll to the bottom in Files section and select “Windows x86-64 executable installer”. Download and install it.

The tensorflow installation steps check here : https://www.tensorflow.org/install/pip . I hope this helps somehow ...

rbind error: "names do not match previous names"

rbind() needs the two object names to be the same. For example, the first object names: ID Age, the next object names: ID Gender,if you want to use rbind(), it will print out:

names do not match previous names

How to fix error Base table or view not found: 1146 Table laravel relationship table?

This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin

How can a Java program get its own process ID?

In Scala:

import sys.process._
val pid: Long = Seq("sh", "-c", "echo $PPID").!!.trim.toLong

This should give you a workaround on Unix systems until Java 9 will be released. (I know, the question was about Java, but since there is no equivalent question for Scala, I wanted to leave this for Scala users who might stumble into the same question.)

Peak memory usage of a linux/unix process

(This is an already answered, old question.. but just for the record :)

I was inspired by Yang's script, and came up with this small tool, named memusg. I simply increased the sampling rate to 0.1 to handle much short living processes. Instead of monitoring a single process, I made it measure rss sum of the process group. (Yeah, I write lots of separate programs that work together) It currently works on Mac OS X and Linux. The usage had to be similar to that of time:

memusg ls -alR / >/dev/null

It only shows the peak for the moment, but I'm interested in slight extensions for recording other (rough) statistics.

It's good to have such simple tool for just taking a look before we start any serious profiling.

System.Net.WebException HTTP status code

Maybe something like this...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

When I tried to include the JSTL Core Library in my JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

I got the following error in Eclipse (Indigo):

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I went to the Project Properties -> Targeted Runtimes, and then checked the Server I was using (Geronimo 3.0). Most people would be using Tomcat. This solved my problem. Hope it helps!

Change the default base url for axios

Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.

To append 'api' to my baseURL, I have my default baseURL set as,

axios.defaults.baseURL = '/api/';

Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'

axios({
    method:'post',
    url:'logout',
    baseURL: '/',
   })
   .then(response => {
      window.location.reload();
   })
   .catch(error => {
       console.log(error);
   });

How do you properly use namespaces in C++?

I prefer using a top-level namespace for the application and sub namespaces for the components.

The way you can use classes from other namespaces is surprisingly very similar to the way in java. You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.

Android changing Floating Action Button color

You can use this code in case you want to change the color programmatically

floating.setBackgroundTintList(getResources().getColorStateList(R.color.vermelho));

AJAX Mailchimp signup form integration

Use jquery.ajaxchimp plugin to achieve that. It's dead easy!

<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
  <input type="text" name="EMAIL" placeholder="e-mail address" />
  <input type="submit" name="subscribe" value="subscribe!" />        
  <p class="result"></p>
</form>

JavaScript:

$(function() {
  $('form').ajaxChimp({
    callback: function(response) {
      $('form .result').text(response.msg);
    }
  });
})

What are the differences between struct and class in C++?

Here is a good explanation: http://carcino.gen.nz/tech/cpp/struct_vs_class.php

So, one more time: in C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.

Get table names using SELECT statement in MySQL

For fetching the name of all tables:

SELECT table_name 
FROM information_schema.tables;

If you need to fetch it for a specific database:

SELECT table_name 
FROM information_schema.tables
WHERE table_schema = 'your_db_name';

Output:

+--------------------+
| table_name         |
+--------------------+
| myapp              |
| demodb             |
| cliquein           |
+--------------------+
3 rows in set (0.00 sec)

How do I install the OpenSSL libraries on Ubuntu?

I found a detailed solution here: Install OpenSSL Manually On Linux

From the blog post...:

Steps to download, compile, and install are as follows (I'm installing version 1.0.1g below; please replace "1.0.1g" with your version number):

Step – 1 : Downloading OpenSSL:

Run the command as below :

$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz

Also, download the MD5 hash to verify the integrity of the downloaded file for just varifacation purpose. In the same folder where you have downloaded the OpenSSL file from the website :

$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz.md5
$ md5sum openssl-1.0.1g.tar.gz
$ cat openssl-1.0.1g.tar.gz.md5

Step – 2 : Extract files from the downloaded package:

$ tar -xvzf openssl-1.0.1g.tar.gz

Now, enter the directory where the package is extracted like here is openssl-1.0.1g

$ cd openssl-1.0.1g

Step – 3 : Configuration OpenSSL

Run below command with optional condition to set prefix and directory where you want to copy files and folder.

$ ./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl

You can replace “/usr/local/openssl” with the directory path where you want to copy the files and folders. But make sure while doing this steps check for any error message on terminal.

Step – 4 : Compiling OpenSSL

To compile openssl you will need to run 2 command : make, make install as below :

$ make

Note: check for any error message for verification purpose.

Step -5 : Installing OpenSSL:

$ sudo make install

Or without sudo,

$ make install

That’s it. OpenSSL has been successfully installed. You can run the version command to see if it worked or not as below :

$ /usr/local/openssl/bin/openssl version

OpenSSL 1.0.1g 7 Apr 2014

How to convert String to Date value in SAS?

As stated above, the simple answer is:

date = input(monyy,date9.);

with the addition of:

put date=yymmdd.;

The reason why this works, and what you did doesn't, is because of a common misunderstanding in SAS. DATE9. is an INFORMAT. In an INPUT statement, it provides the SAS interpreter with a set of translation commands it can send to the compiler to turn your text into the right numbers, which will then look like a date once the right FORMAT is applied. FORMATs are just visible representations of numbers (or characters). So by using YYMMDD., you confused the INPUT function by handing it a FORMAT instead of an INFORMAT, and probably got a helpful error that said:

Invalid argument to INPUT function at line... etc...

Which told you absolutely nothing about what to do next.

In summary, to represent your character date as a YYMMDD. In SAS you need to:

  1. change the INFORMAT - date = input(monyy,date9.);
  2. apply the FORMAT - put date=YYMMDD10.;

How to go back last page

Actually you can take advantage of the built-in Location service, which owns a "Back" API.

Here (in TypeScript):

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

@Component({
  // component's declarations here
})
class SomeComponent {

  constructor(private _location: Location) 
  {}

  backClicked() {
    this._location.back();
  }
}

Edit: As mentioned by @charith.arumapperuma Location should be imported from @angular/common so the import {Location} from '@angular/common'; line is important.

Excel VBA App stops spontaneously with message "Code execution has been halted"

Thanks to everyone for their input. This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office's native COM components and does stuff that REINSTALL doesn't. I expect the latter just goes through a checklist and sometimes accepts what's there if it's already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user's machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.

PyCharm import external library

Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.

My project is now behaving as I would expect.

These are the windows you would see while following the instructions

DateTime to javascript date

Try:

return DateTime.Now.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds

Edit: true UTC is better, but then we need to be consistent

return DateTime.UtcNow
               .Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc))
               .TotalMilliseconds;

Although, on second thoughts it does not matter, as long as both dates are in the same time zone.

How to connect to mysql with laravel?

I spent a lot of time trying to figure this one out. Finally, I tried shutting down my development server and booting it up again. Frustratingly, this worked for me. I came to the conclusion, that after editing the .env file in Laravel 5, you have to exit the server, and run php artisan serve again.

How to overlay images

Here's a good technique to display an overlay image that is centered with a semi-transparent background over an image link:

HTML

<div class="image-container">
    <a class="link" href="#" >  
        <img class="image" src="/img/thumbnail.png"/>
        <span class="overlay-image"><img src="/img/overlay.png"></span>
    </a>    
</div>

CSS

div.image-container{
    position: relative;
}
a.link{
    text-decoration: none;  
    position: relative;
    display: block;
}

a.link span.overlay-image{
    visibility: hidden;
    position: absolute;
    left: 0px;
    top: 0px;
    bottom: 0px;
    right: 0px;
    background-color: rgba(0,0,0,0.2); /* black background with 20% alpha */
}

a.link span.overlay-image:before {    /* create a full-height inline block pseudo=element */
    content: ' ';
    display: inline-block;
    vertical-align: middle;  /* vertical alignment of the inline element */
    height: 100%;   
}

a.link:hover span.overlay-image img{
    display: inline-block;  
    vertical-align: middle;     
}

a.link:hover span.overlay-image{
    visibility: visible;
}

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Inserting HTML into a div

I using "+" (plus) to insert div to html :

document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';

Hope this help.

SQL: Select columns with NULL values only

Here is the sql 2005 or later version: Replace ADDR_Address with your tablename.

declare @col varchar(255), @cmd varchar(max)

DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'ADDR_Address'

OPEN getinfo

FETCH NEXT FROM getinfo into @col

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ADDR_Address WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end'
    EXEC(@cmd)

    FETCH NEXT FROM getinfo into @col
END

CLOSE getinfo
DEALLOCATE getinfo

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

Create a custom callback in JavaScript

   function callback(e){
      return e;
   }
    var MyClass = {
       method: function(args, callback){
          console.log(args);
          if(typeof callback == "function")
          callback();
       }    
    }

==============================================

MyClass.method("hello",function(){
    console.log("world !");
});

==============================================

Result is:

hello world !

How do I set path while saving a cookie value in JavaScript?

See https://developer.mozilla.org/en/DOM/document.cookie for more documentation:

 setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
     if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
     var sExpires = "";  
     if (vEnd) {  
       switch (typeof vEnd) {  
         case "number": sExpires = "; max-age=" + vEnd; break;  
         case "string": sExpires = "; expires=" + vEnd; break;  
         case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;  
       }  
     }  
     document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  
   }

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

In my projects, this piece of code always worked as a default serializer which serializes the specified value as if there was no special converter:

serializer.Serialize(writer, value);

Finding all possible combinations of numbers to reach a given sum

Recommended as an answer:

Here's a solution using es2015 generators:

function* subsetSum(numbers, target, partial = [], partialSum = 0) {

  if(partialSum === target) yield partial

  if(partialSum >= target) return

  for(let i = 0; i < numbers.length; i++){
    const remaining = numbers.slice(i + 1)
        , n = numbers[i]

    yield* subsetSum(remaining, target, [...partial, n], partialSum + n)
  }

}

Using generators can actually be very useful because it allows you to pause script execution immediately upon finding a valid subset. This is in contrast to solutions without generators (ie lacking state) which have to iterate through every single subset of numbers

HTML button onclick event

You should all know this is inline scripting and is not a good practice at all...with that said you should definitively use javascript or jQuery for this type of thing:

HTML

<!DOCTYPE html> 
<html> 
 <head> 
    <meta charset="ISO-8859-1"> 
    <title>Online Student Portal</title> 
 </head> 
 <body> 
    <form action="">
         <input type="button" id="myButton" value="Add"/>
    </form> 
 </body> 
</html>

JQuery

var button_my_button = "#myButton";
$(button_my_button).click(function(){
 window.location.href='Students.html';
});

Javascript

  //get a reference to the element
  var myBtn = document.getElementById('myButton');

  //add event listener
  myBtn.addEventListener('click', function(event) {
    window.location.href='Students.html';
  });

See comments why avoid inline scripting and also why inline scripting is bad

Shorter syntax for casting from a List<X> to a List<Y>?

You can use List<Y>.ConvertAll<T>([Converter from Y to T]);

How can I post data as form data instead of a request payload?

Create an adapter service for post:

services.service('Http', function ($http) {

    var self = this

    this.post = function (url, data) {
        return $http({
            method: 'POST',
            url: url,
            data: $.param(data),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
    }

}) 

Use it in your controllers or whatever:

ctrls.controller('PersonCtrl', function (Http /* our service */) {
    var self = this
    self.user = {name: "Ozgur", eMail: null}

    self.register = function () {
        Http.post('/user/register', self.user).then(function (r) {
            //response
            console.log(r)
        })
    }

})

JFrame Maximize window

The way to set JFrame to full-screen, is to set MAXIMIZED_BOTH option which stands for MAXIMIZED_VERT | MAXIMIZED_HORIZ, which respectively set the frame to maximize vertically and horizontally

package Example;
import java.awt.GraphicsConfiguration;
import javax.swing.JFrame;
import javax.swing.JButton;

public class JFrameExample
{
    static JFrame frame;
    static GraphicsConfiguration gc;
    public static void main(String[] args)
    {
        frame = new JFrame(gc);
        frame.setTitle("Full Screen Example");
        frame.setExtendedState(MAXIMIZED_BOTH);

        JButton button = new JButton("exit");
        b.addActionListener(new ActionListener(){@Override
        public void actionPerformed(ActionEvent arg0){
            JFrameExample.frame.dispose();
            System.exit(0);
        }});

        frame.add(button);
        frame.setVisible(true);
    }
}

SQlite - Android - Foreign key syntax

Since I cannot comment, adding this note in addition to @jethro answer.

I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:

private static final String TASK_TABLE_CREATE = "create table "
    + TASK_TABLE + " (" + TASK_ID
    + " integer primary key autoincrement, " + TASK_TITLE
    + " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";

Where I put the TASK_DATE_TIME after the foreign key line.

MongoDB Aggregation: How to get total records count?

Use the $count aggregation pipeline stage to get the total document count:

Query :

db.collection.aggregate(
  [
    {
      $match: {
        ...
      }
    },
    {
      $group: {
        ...
      }
    },
    {
      $count: "totalCount"
    }
  ]
)

Result:

{
   "totalCount" : Number of records (some integer value)
}

Return single column from a multi-dimensional array

In this situation implode($array,','); will works, becasue you want the values only. In PHP 5.6 working for me.

If you want to implode the keys and the values in one like :
blogTags_id: 1
tag_name: google

$toImplode=array();
foreach($array as $key => $value) {
$toImplode[]= "$key: $value".'<br>';
}
$imploded=implode('',$toImplode);

Sorry, I understand wrong, becasue the title "Implode data from a multi-dimensional array". Well, my answer still answer it somehow, may help someone, so will not delete it.

How to check if an app is installed from a web-page on an iPhone?

I need to do something like this I ended up going with the following solution.

I have a specific website URL that will open a page with two buttons

1) Button One go to website

2) Button Two go to application (iphone / android phone / tablet) you can fall back to a default location from here if the app is not installed (like another url or an app store)

3) cookie to remember users choice

<head>
<title>Mobile Router Example </title>


<script type="text/javascript">
    function set_cookie(name,value)
    {
       // js code to write cookie
    }
    function read_cookie(name) {
       // jsCode to read cookie
    }

    function goToApp(appLocation) {
        setTimeout(function() {
            window.location = appLocation;
              //this is a fallback if the app is not installed. Could direct to an app store or a website telling user how to get app


        }, 25);
        window.location = "custom-uri://AppShouldListenForThis";
    }

    function goToWeb(webLocation) {
        window.location = webLocation;
    }

    if (readCookie('appLinkIgnoreWeb') == 'true' ) {
        goToWeb('http://somewebsite');

    }
    else if (readCookie('appLinkIgnoreApp') == 'true') {
        goToApp('http://fallbackLocation');
    }



</script>
</head>
<body>


<div class="iphone_table_padding">
<table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <!-- INTRO -->
            <span class="iphone_copy_intro">Check out our new app or go to website</span>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_btn_padding">

                <!-- GET IPHONE APP BTN -->
                <table border="0" cellspacing="0" cellpadding="0" class="iphone_btn" onclick="set_cookie('appLinkIgnoreApp',document.getElementById('chkDontShow').checked);goToApp('http://getappfallback')">
                    <tr>
                        <td class="iphone_btn_on_left">&nbsp;</td>
                        <td class="iphone_btn_on_mid">
                            <span class="iphone_copy_btn">
                                Get The Mobile Applications
                            </span>
                        </td>
                        <td class="iphone_btn_on_right">&nbsp;</td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_btn_padding">

                <table border="0" cellspacing="0" cellpadding="0" class="iphone_btn"  onclick="set_cookie('appLinkIgnoreWeb',document.getElementById('chkDontShow').checked);goToWeb('http://www.website.com')">
                    <tr>
                        <td class="iphone_btn_left">&nbsp;</td>
                        <td class="iphone_btn_mid">
                            <span class="iphone_copy_btn">
                                Visit Website.com
                            </span>
                        </td>
                        <td class="iphone_btn_right">&nbsp;</td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_chk_padding">

                <!-- CHECK BOX -->
                <table border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td><input type="checkbox" id="chkDontShow" /></td>
                        <td>
                            <span class="iphone_copy_chk">
                                <label for="chkDontShow">&nbsp;Don&rsquo;t show this screen again.</label>
                            </span>
                        </td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
</table>

</div>

</body>
</html>

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

I think jQuery cannot find the element.

First of all find the element

var rowTemplate= document.getElementsByName("rowTemplate");

or

var rowTemplate = document.getElementById("rowTemplate"); 

or

var rowTemplate = $('#rowTemplate');

Then try your code again

rowTemplate.html().replace(....)

Python Error: "ValueError: need more than 1 value to unpack"

You shouldn't be doing tuple dereferencing on values that can change like your line below.

 script, user_name = argv

The line above will fail if you pass less than one argument or more than one argument. A better way of doing this is to do something like this:

 for arg in argv[1:]:
     print arg

Of cause you will do something other than print the args. Maybe put a series of 'if' statement in the 'for' loop that set variables depending on the arguments passed. An even better way is to use the getopt or optparse packages.

How to deploy correctly when using Composer's develop / production switch?

Actually, I would highly recommend AGAINST installing dependencies on the production server.

My recommendation is to checkout the code on a deployment machine, install dependencies as needed (this includes NOT installing dev dependencies if the code goes to production), and then move all the files to the target machine.

Why?

  • on shared hosting, you might not be able to get to a command line
  • even if you did, PHP might be restricted there in terms of commands, memory or network access
  • repository CLI tools (Git, Svn) are likely to not be installed, which would fail if your lock file has recorded a dependency to checkout a certain commit instead of downloading that commit as ZIP (you used --prefer-source, or Composer had no other way to get that version)
  • if your production machine is more like a small test server (think Amazon EC2 micro instance) there is probably not even enough memory installed to execute composer install
  • while composer tries to no break things, how do you feel about ending with a partially broken production website because some random dependency could not be loaded during Composers install phase

Long story short: Use Composer in an environment you can control. Your development machine does qualify because you already have all the things that are needed to operate Composer.

What's the correct way to deploy this without installing the -dev dependencies?

The command to use is

composer install --no-dev

This will work in any environment, be it the production server itself, or a deployment machine, or the development machine that is supposed to do a last check to find whether any dev requirement is incorrectly used for the real software.

The command will not install, or actively uninstall, the dev requirements declared in the composer.lock file.

If you don't mind deploying development software components on a production server, running composer install would do the same job, but simply increase the amount of bytes moved around, and also create a bigger autoloader declaration.

What happens when a duplicate key is put into a HashMap?

It replaces the existing value in the map for the respective key. And if no key exists with the same name then it creates a key with the value provided. eg:

Map mymap = new HashMap();
mymap.put("1","one");
mymap.put("1","two");

OUTPUT key = "1", value = "two"

So, the previous value gets overwritten.

How do I convert a String to a BigInteger?

For a loop where you want to convert an array of strings to an array of bigIntegers do this:

String[] unsorted = new String[n]; //array of Strings
BigInteger[] series = new BigInteger[n]; //array of BigIntegers

for(int i=0; i<n; i++){
    series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
}

Minimum and maximum date

To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.

_x000D_
_x000D_
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
_x000D_
_x000D_

Two color borders

If by "embossing" you mean two borders around each other with two different colours, there is the outline property (outline-left, outline-right....) but it is poorly supported in the IE family (namely, IE6 and 7 don't support it at all). If you need two borders, a second wrapper element would indeed be best.

If you mean using two colours in the same border. Use e.g.

border-right: 1px white solid;
border-left: 1px black solid;
border-top: 1px black solid;
border-bottom: 1px white solid;

there are special border-styles for this as well (ridge, outset and inset) but they tend to vary across browsers in my experience.

React JS Error: is not defined react/jsx-no-undef

Strangely enough, the reason for my failure was about the CamelCase that I was applying to the component name. MyComponent was giving me this error but then I renamed it to Mycomponent and voila, it worked!!!

Is there a way to add a gif to a Markdown file?

in addition to all answers above:

if you want to use a gif for your github repository README.md and don't want to address it from your root directory, it's not enough if you just copy the url of your browser, for example your browser URL is sth like:

https://github.com/ashkan-nasirzadeh/simpleShell/blob/master/README%20assets/shell-gif.gif

but you should open your gif in your github account and right click on it and click copy image address or sth like that which is sth like this:

https://github.com/ashkan-nasirzadeh/simpleShell/blob/master/README%20assets/shell-gif.gif?raw=true

Source file not compiled Dev C++

Install new version of Dev c++. It works fine in Windows 8. It also supports 64 bit version.

Download link is http://sourceforge.net/projects/orwelldevcpp/ .

iOS 7: UITableView shows under status bar

I have done this for Retina/Non-Retina display as

BOOL isRetina = FALSE;

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    if ([[UIScreen mainScreen] scale] == 2.0) {
        isRetina = TRUE;
    } else {
        isRetina = FALSE;
    }
}

if (isRetina) {
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars=NO;
    self.automaticallyAdjustsScrollViewInsets=NO;
}

Retrieving the last record in each group - MySQL

Hope below Oracle query can help:

WITH Temp_table AS
(
    Select id, name, othercolumns, ROW_NUMBER() over (PARTITION BY name ORDER BY ID 
    desc)as rank from messages
)
Select id, name,othercolumns from Temp_table where rank=1

How to pass model attributes from one Spring MVC controller to another controller?

I used @ControllerAdvice , please check is available in Spring 3.X; I am using it in Spring 4.0.

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}

How to stop a setTimeout loop?

As this is tagged with the extjs tag it may be worth looking at the extjs method: http://docs.sencha.com/extjs/6.2.0/classic/Ext.Function.html#method-interval

This works much like setInterval, but also takes care of the scope, and allows arguments to be passed too:

function setBgPosition() {
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
       Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length){
            c=0;
        }
    }
    return Ext.Function.interval(run,200);
}

var bgPositionTimer = setBgPosition();

when you want to stop you can use clearInterval to stop it

clearInterval(bgPositionTimer);

An example use case would be:

Ext.Ajax.request({
    url: 'example.json',

    success: function(response, opts) {
        clearInterval(bgPositionTimer);
    },

    failure: function(response, opts) {
        console.log('server-side failure with status code ' + response.status);
        clearInterval(bgPositionTimer);
    }
});

Get refresh token google api

It is access_type=offline that you want.

This will return the refresh token the first time the user authorises the app. Subsequent calls do not force you to re-approve the app (approval_prompt=force).

See further detail: https://developers.google.com/accounts/docs/OAuth2WebServer#offline

C++ Singleton design pattern

I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:

#include<iostream>
#include<string>

class DoNotCopy
{
protected:
    DoNotCopy(void) = default;
    DoNotCopy(const DoNotCopy&) = delete;
    DoNotCopy& operator=(const DoNotCopy&) = delete;
};

class DoNotMove
{
protected:
    DoNotMove(void) = default;
    DoNotMove(DoNotMove&&) = delete;
    DoNotMove& operator=(DoNotMove&&) = delete;
};

class DoNotCopyMove : public DoNotCopy,
    public DoNotMove
{
protected:
    DoNotCopyMove(void) = default;
};

template<class T>
class Singleton : public DoNotCopyMove
{
public:
    static T& Instance(void)
    {
        static T instance;
        return instance;
    }

protected:
    Singleton(void) = default;
};

class Logger final: public Singleton<Logger>
{
public:
    void log(const std::string& str) { std::cout << str << std::endl; }
};



int main()
{
    Logger::Instance().log("xx");
}

The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

node.js - request - How to "emitter.setMaxListeners()"?

I use the code to increase the default limit globally: require('events').EventEmitter.prototype._maxListeners = 100;

Bootstrap 4, how to make a col have a height of 100%?

I came across this problem because my cols exceeded the row grid length (> 12)

A solution using 100% Bootstrap 4:

Since the rows in Bootstrap are already display: flex

You just need to add flex-fill to the Col, and h-100 to the container and any children.

Pen here: https://codepen.io/joshkopecek/pen/Exjdgjo

<div class="container-fluid h-100">
  <div class="row justify-content-center h-100">

    <div class="col-4 hidden-md-down flex-fill" id="yellow">
      XXXX
    </div>

    <div id="blue" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
      Form Goes Here
    </div>

    <div id="green" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
      Another form
    </div>
  </div>
</div>

Function of Project > Clean in Eclipse

There's another problem at work here. The Clean functionality of Eclipse is broken. If you delete files outside of Eclipse it will not pick up on the fact that the files are now missing, and you'll get build errors until you delete the files manually. Even then, that will not necessarily work either, especially if there are a lot of files missing. This happens to me rather often when I check out a branch of code that has had a lot of changes since the last time I built it. In that case, the only recourse I've found is to start a brand new workspace and reload the project from scratch.

SQL Server 2012 can't start because of a login failure

Short answer:
install Remote Server Administration tools on your SQL Server (it's an optional feature of Windows Server), reboot, then run SQL Server configuration manager, access the service settings for each of the services whose logon account starts with "NT Service...", clear out the password fields and restart the service. Under the covers, SQL Server Config manager will assign these virtual accounts the Log On as a Service right, and you'll be on your way.

tl;dr;

There is a catch-22 between default settings for a windows domain and default install of SQL Server 2012.

As mentioned above, default Windows domain setup will indeed prevent you from defining the "log on as a service" right via Group Policy Edit at the local machine (via GUI at least; if you install Powershell ActiveDirectory module (via Remote Server Administration tools download) you can do it by scripting.

And, by default, SQL Server 2012 setup runs services in "virtual accounts" (NT Service\ prefix, e.g, NT Service\MSSQLServer. These are like local machine accounts, not domain accounts, but you still can't assign them log on as service rights if your server is joined to a domain. SQL Server setup attempts to assign the right at install, and the SQL Server Config Management tool likewise attempts to assign the right when you change logon account.

And the beautiful catch-22 is this: SQL Server tools depend on (some component of) RSAT to assign the logon as service right. If you don't happen to have RSAT installed on your member server, SQL Server Config Manager fails silently trying to apply the setting (despite all the gaudy pre-installation verification it runs) and you end up with services that won't start.

The one hint of this requirement that I was able to find in the blizzard of SQL Server and Virtual Account doc was this: https://msdn.microsoft.com/en-us/library/ms143504.aspx#New_Accounts, search for RSAT.

C dynamically growing array

To create an array of unlimited items of any sort of type:

typedef struct STRUCT_SS_VECTOR {
    size_t size;
    void** items;
} ss_vector;


ss_vector* ss_init_vector(size_t item_size) {
    ss_vector* vector;
    vector = malloc(sizeof(ss_vector));
    vector->size = 0;
    vector->items = calloc(0, item_size);

    return vector;
}

void ss_vector_append(ss_vector* vec, void* item) {
    vec->size++;
    vec->items = realloc(vec->items, vec->size * sizeof(item));
    vec->items[vec->size - 1] = item;
};

void ss_vector_free(ss_vector* vec) {
    for (int i = 0; i < vec->size; i++)
        free(vec->items[i]);

    free(vec->items);
    free(vec);
}

and how to use it:

// defining some sort of struct, can be anything really
typedef struct APPLE_STRUCT {
    int id;
} apple;

apple* init_apple(int id) {
    apple* a;
    a = malloc(sizeof(apple));
    a-> id = id;
    return a;
};


int main(int argc, char* argv[]) {
    ss_vector* vector = ss_init_vector(sizeof(apple));

    // inserting some items
    for (int i = 0; i < 10; i++)
        ss_vector_append(vector, init_apple(i));


    // dont forget to free it
    ss_vector_free(vector);

    return 0;
}

This vector/array can hold any type of item and it is completely dynamic in size.

How to convert local time string to UTC?

You can do it with:

>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime

How to set child process' environment variable in Makefile

Make variables are not exported into the environment of processes make invokes... by default. However you can use make's export to force them to do so. Change:

test: NODE_ENV = test

to this:

test: export NODE_ENV = test

(assuming you have a sufficiently modern version of GNU make >= 3.77 ).

Why does DEBUG=False setting make my django Static Files Access fail?

This is Exactly you must type on terminal to run your project without DEBUG = TRUE and then you see all assets (static) file is loading correctly On local server .

python manage.py runserver --insecure 

--insecure : it means you can run server without security mode

Multidimensional arrays in Swift

For future readers, here is an elegant solution(5x5):

var matrix = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)

and a dynamic approach:

var matrix = [[Int]]() // creates an empty matrix
var row = [Int]() // fill this row
matrix.append(row) // add this row

Display JSON Data in HTML Table

Try this:

  <!DOCTYPE html>
    <html>
    <head>
        <title>Convert JSON Data to HTML Table</title>
        <style>
            th, td, p, input {
                font:14px Verdana;
            }
            tr{
                align: right
            }
            table, th, td 
            {
                border: solid 1px #DDD;
                border-collapse: collapse;
                padding: 2px 3px;
                text-align: center;
            }
            th {
                font-weight:bold;
            }
        </style>
    </head>
    <body>
        <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
        <div id="showData"></div>
    </body>

    <script>
        function CreateTableFromJSON() {
            var obj = {[{"city":"AMBALA","cStatus":"Y"}, 
                      {"city":"ASANKHURD","cStatus":"Y"}, 
                      {"city":"ASSANDH","cStatus":"Y"}]}

    var table = document.createElement('table');

    var tr = table.insertRow(-1);

    function iterate(obj,table,tr){

        for(var props in obj){

            if(obj.hasOwnProperty(props)){

                if(typeof obj[props]=='object')
                    {
                        var trNext = table.insertRow(-1);
                        var tabCellHead = trNext.insertCell(-1);
                        var tabCell = trNext.insertCell(-1);
                        var table_in = document.createElement('table'); 
                        var tr_in;
                        var th = document.createElement("th");      
                        th.innerHTML = props;

                        tabCellHead.appendChild(th);
                        tabCell.appendChild(table_in)
                        iterate(obj[props],table_in,tr_in);
                    }
                else
                    {
                        if(tr === undefined)
                        {
                            tr = table.insertRow(-1);
                        }
                        var tabCell = tr.insertCell(-1);
                        console.log(props+' * '+obj[props]);
                        tabCell.innerHTML = obj[props];
                    }

            }
        }
    }

    iterate(obj,table,tr);

    var divContainer = document.getElementById("showData");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);

    }
    </script>
    </html>

Sort array of objects by string property value

One more option:

var someArray = [...];

function generateSortFn(prop, reverse) {
    return function (a, b) {
        if (a[prop] < b[prop]) return reverse ? 1 : -1;
        if (a[prop] > b[prop]) return reverse ? -1 : 1;
        return 0;
    };
}

someArray.sort(generateSortFn('name', true));

sorts ascending by default.

Edit existing excel workbooks and sheets with xlrd and xlwt

As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

Here is the proper way to do it:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

  • Update your support library to last version

  • Open Manifest File , and add it into Manifest File

  • <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/>

  • And add for recyclerview in >> build.gradle Module app :

  • compile 'com.android.support:recyclerview-v7:25.3.1'

  • And click : Sync Now

Zoom to fit: PDF Embedded in HTML

Bit of a late response but I noticed that this information can be hard to find and haven't found the answer on SO, so here it is.

Try a differnt parameter #view=FitH to force it to fit in the horzontal space and also you need to start the querystring off with a # rather than an & making it:

filename.pdf#view=FitH

What I've noticed it is that this will work if adobe reader is embedded in the browser but chrome will use it's own version of the reader and won't respond in the same way. In my own case, the chrome browser zoomed to fit width by default, so no problem , but Internet Explorer needed the above parameters to ensure the link always opened the pdf page with the correct view setting.

For a full list of available parameters see this doc

EDIT: (lazy mode on)

enter image description here enter image description here enter image description here enter image description here enter image description here

Match whitespace but not newlines

What you are looking for is the POSIX blank character class. In Perl it is referenced as:

[[:blank:]]

in Java (don't forget to enable UNICODE_CHARACTER_CLASS):

\p{Blank}

Compared to the similar \h, POSIX blank is supported by a few more regex engines (reference). A major benefit is that its definition is fixed in Annex C: Compatibility Properties of Unicode Regular Expressions and standard across all regex flavors that support Unicode. (In Perl, for example, \h chooses to additionally include the MONGOLIAN VOWEL SEPARATOR.) However, an argument in favor of \h is that it always detects Unicode characters (even if the engines don't agree on which), while POSIX character classes are often by default ASCII-only (as in Java).

But the problem is that even sticking to Unicode doesn't solve the issue 100%. Consider the following characters which are not considered whitespace in Unicode:

The aforementioned Mongolian vowel separator isn't included for what is probably a good reason. It, along with 200C and 200D, occur within words (AFAIK), and therefore breaks the cardinal rule that all other whitespace obeys: you can tokenize with it. They're more like modifiers. However, ZERO WIDTH SPACE, WORD JOINER, and ZERO WIDTH NON-BREAKING SPACE (if it used as other than a byte-order mark) fit the whitespace rule in my book. Therefore, I include them in my horizontal whitespace character class.

In Java:

static public final String HORIZONTAL_WHITESPACE = "[\\p{Blank}\\u200B\\u2060\\uFFEF]"

Get index of current item in a PowerShell loop

.NET has some handy utility methods for this sort of thing in System.Array:

PS> $a = 'a','b','c'
PS> [array]::IndexOf($a, 'b')
1
PS> [array]::IndexOf($a, 'c')
2

Good points on the above approach in the comments. Besides "just" finding an index of an item in an array, given the context of the problem, this is probably more suitable:

$letters = { 'A', 'B', 'C' }
$letters | % {$i=0} {"Value:$_ Index:$i"; $i++}

Foreach (%) can have a Begin sciptblock that executes once. We set an index variable there and then we can reference it in the process scripblock where it gets incremented before exiting the scriptblock.

Difference between List, List<?>, List<T>, List<E>, and List<Object>

For the last part: Although String is a subset of Object, but List<String> is not inherited from List<Object>.

How to check if two words are anagrams

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Algorithms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JOptionPane;

/**
 *
 * @author Mokhtar
 */
public class Anagrams {

    //Write aprogram to check if two words are anagrams
    public static void main(String[] args) {
        Anagrams an=new Anagrams();
        ArrayList<String> l=new ArrayList<String>();
        String result=JOptionPane.showInputDialog("How many words to test anagrams");
        if(Integer.parseInt(result) >1)
        {    
            for(int i=0;i<Integer.parseInt(result);i++)
            {

                String word=JOptionPane.showInputDialog("Enter word #"+i);
                l.add(word);   
            }
            System.out.println(an.isanagrams(l));
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Can not be tested, \nYou can test two words or more");
        }

    }

    private static String sortString( String w )
    {
        char[] ch = w.toCharArray();
        Arrays.sort(ch);
        return new String(ch);
    }

    public boolean isanagrams(ArrayList<String> l)
    {
        boolean isanagrams=true; 
        ArrayList<String> anagrams = null;
        HashMap<String, ArrayList<String>> map =  new HashMap<String, ArrayList<String>>();
        for(int i=0;i<l.size();i++)
            {
        String word = l.get(i);
        String sortedWord = sortString(word);
            anagrams = map.get( sortedWord );
        if( anagrams == null ) anagrams = new ArrayList<String>();
        anagrams.add(word);
        map.put(sortedWord, anagrams);
            }

            for(int h=0;h<l.size();h++)
            {
                if(!anagrams.contains(l.get(h)))
                {
                    isanagrams=false;
                    break;
                }
            }

            return isanagrams;
        //}
        }

}

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

Plot 3D data in R

Adding to the solutions of others, I'd like to suggest using the plotly package for R, as this has worked well for me.

Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")

enter image description here

The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.

You can also try it with the built-in volcano dataset from R:

plot_ly(z=volcano, type="surface")

enter image description here

How can I upload files asynchronously?

What if using promises which ajax and checking if the file is valid and well saved in your backend, so you can use some animation in front while user is navigating thought your page.

You can even make it paralel upload or stacking with recursive approach

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

uuid1() is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the uuid and the computer, as the mac address gets used to make it unique across computers.

You can create duplicates by creating more than 214 uuid1 in less than 100ns, but this is not a problem for most use cases.

uuid4() generates, as you said, a random UUID. The chance of a collision is really, really, really small. Small enough, that you shouldn't worry about it. The problem is, that a bad random-number generator makes it more likely to have collisions.

This excellent answer by Bob Aman sums it up nicely. (I recommend reading the whole answer.)

Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second.

What is the "Upgrade-Insecure-Requests" HTTP header?

Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests response header, indicating that the browser supports it (and in fact prefers it).

It took me 30mins of Googling, but I finally found it buried in the W3 spec.

The confusion comes because the header in the spec was HTTPS: 1, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:

"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842

Their fix was to rename it to Upgrade-Insecure-Requests: 1, and the spec has since been updated to match.

Anyway, here is the explanation from the W3 spec (as it appeared at the time)...

The HTTPS HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide.

...

When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.

When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a Strict-Transport-Security header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].

Sample random rows in dataframe

Write one! Wrapping JC's answer gives me:

randomRows = function(df,n){
   return(df[sample(nrow(df),n),])
}

Now make it better by checking first if n<=nrow(df) and stopping with an error.

Could not resolve Spring property placeholder

make sure your properties file exist in classpath directory but not in sub folder of your classpath directory. if it is exist in sub folder then write as below classpath:subfolder/idm.properties

How do you run a single test/spec file in RSpec?

If you installed rspec as a plugin rather than as a gem, then you won't have the spec executable.

At any rate, All you need to do is run the file using ruby. The rspec code is clever enough to run the tests for you.

eg:

ruby myclass_spec.rb

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

If you have tried all of the above and it still did not work. Check firewall.

I was trying to connect from a windows machine to a MySql Server 5.7.32 installed on a VirtualBox machine with CentOs7. I have tried everything and it was not working, even though i could ping the machine i couldn't connect to the MySql Server.

On CentOs7 the commands to check the firewall are:

Step 1: Check the status of your firewall service:

systemctl status firewallid.service

Step 2: Disable the firewall service

systemctl stop firewallid.service

Is it possible to hide/encode/encrypt php source code and let others have the system?

Yes, you can definitely hide/encode/encrypt the php source code and 'others' can install it on their machine. You could use the below tools to achieve the same.

But these 'others' can also decode/decrypt the source code using other tools and services found online. So you cannot 100% protect your code, what you can do is, make it tougher for someone to reverse engineer your code.

Most of these tools above support Encoding and Obfuscating.

  • Encoding will hide your code by encrypting it.
  • Obfuscating will make your code difficult to understand.

You can choose to use both (Encoding and Obfuscating) or either one, depending on your needs.

Change the image source on rollover using jQuery

Adapted from Richard Ayotte's code - To target an img in a ul/li list (found via wrapper div class here), something like this:

$('div.navlist li').bind('mouseenter mouseleave', function() {    
    $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'), 
    'data-alt-src':$(this).find('img').attr('src') }
); 

Install an apk file from command prompt?

Open Terminal in Android Studio

You might see

C:\Users\nikhil\AppData\Local\Android\Sdk\platform-tools>

copy and paste your apk which you want to install on above path inside platform-tools. In my case app-qa-debug.apk I kept inside platform-tools folder.

install command

adb install app-qa-debug.apk

so in the terminal you could see something

C:\Users\nikhil\AppData\Local\Android\Sdk\platform-tools>adb install app-qa-debug.apk

post-installation you could get the message as

Performing Streamed

Install Success

Why is synchronized block better than synchronized method?

It should not be considered as a question of best for usage, but it really depends on the use case or the scenario.

Synchronized Methods

An entire method can be marked as synchronized resulting an implicit lock on the this reference (instance methods) or class (static methods). This is very convenient mechanism to achieve synchronization.

Steps A thread access the synchronized method. It implicitly acquires the lock and execute the code. If other thread want to access the above method, it has to wait. The thread can't get the lock, will be blocked and has to wait till the lock is released.

Synchronized Blocks

To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste.

More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Is it possible to get multiple values from a subquery?

View this web: http://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php

Use example

select ord_num, agent_code, ord_date, ord_amount  
from orders  
where(agent_code, ord_amount) IN  
(SELECT agent_code, MIN(ord_amount)  
FROM orders   
GROUP BY agent_code);    

Print range of numbers on same line

n = int(input())
for i in range(1,n+1):
    print(i,end='')

How to disable horizontal scrolling of UIScrollView?

Introduced in iOS 11 is a new property on UIScrollView

var contentLayoutGuide: UILayoutGuide

The documentation states that you:

Use this layout guide when you want to create Auto Layout constraints related to the content area of a scroll view.

Along with any other Autolayout constraints that you might be adding you will want to constrain the widthAnchor of the UIScrollView's contentLayoutGuide to be the same size as the "frame". You can use the frameLayoutGuide (also introduced in iOS 11) or any external width (such as your superView's.)

example:

NSLayoutConstraint.activate([
  scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.widthAnchor)
])

Documentation: https://developer.apple.com/documentation/uikit/uiscrollview/2865870-contentlayoutguide

Clearing a string buffer/builder after loop

The easiest way to reuse the StringBuffer is to use the method setLength()

public void setLength(int newLength)

You may have the case like

StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb

Remove Server Response Header IIS7

The solution proposed above in combination worked for me with following changes. Here I am posting my scenario and solution.

For me I wanted to remove the following headers:

  • Server
  • X-Powered-By
  • X-AspNet-Version
  • X-AspNetMvc-Version

I added these to my global.asax:

<%@ Application Language="C#" %>
<script runat="server">
    protected void Application_PreSendRequestHeaders()
    {
        Response.Headers.Remove("Server");
        Response.Headers.Remove("X-Powered-By");
        Response.Headers.Remove("X-AspNet-Version");
        Response.Headers.Remove("X-AspNetMvc-Version");
    }
</script>

The above event was not getting triggered, so for that I added following to web.config then it worked.

<modules runAllManagedModulesForAllRequests="true" />

and for removing version header I also added following to web.config:

<httpRuntime enableVersionHeader="false" />

Changes in web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
    <system.web>
        <httpRuntime enableVersionHeader="false" />
    </system.web>
</configuration>

Hope it helps!

Git error: "Please make sure you have the correct access rights and the repository exists"

Here is how I solve this issue. I was using Babun(mintty.exe) on Win7/10. When I have tried many solutions mentioned above, and none of them works. I realized maybe I just used wrong ssh agent... So I run echo $GIT_SSH to find out, it shows the path to Plink.exe. What I actually expected is OpenSSH.

So, I add following one-liner to ~/.zshrc file

Note 1: You can execute it in babun directly also
Note 2: You if you use bash then the config file is .bashrc

export GIT_SSH=$(which ssh)

And It works!

Android AlertDialog Single Button

Kotlin?

  val dialogBuilder = AlertDialog.Builder(this.context)
  dialogBuilder.setTitle("Alert")
               .setMessage(message)
               .setPositiveButton("OK", null)
               .create()
               .show()

How to update data in one table from corresponding data in another table in SQL Server 2005

If the two databases are on the same server, you should be able to create a SQL statement something like this:

UPDATE Test1.dbo.Employee
SET DeptID = emp2.DeptID
FROM Test2.dbo.Employee as 'emp2'
WHERE
   Test1.dbo.Employee.EmployeeID = emp2.EmployeeID

From your post, I'm not quite clear whether you want to update Test1.dbo.Employee with the values from Test2.dbo.Employee (that's what my query does), or the other way around (since you mention the db on Test1 was the new table......)

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Selecting multiple classes with jQuery

I use $('.myClass.myOtherClass').removeClass('theclass');

Relative paths in Python

In the file that has the script, you want to do something like this:

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

#foo.py
import os
print os.getcwd()
print __file__

#in the interactive interpreter
>>> import foo
/Users/jason
foo.py

#and finally, at the shell:
~ % python foo.py
/Users/jason
foo.py

However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

>>> import collections #note that collections is a C extension in Python 2.5
>>> collections.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
dynload/collections.so'

However, this raises an exception on my Windows machine.

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

How to call a method defined in an AngularJS directive?

Maybe this is not the best choice, but you can do angular.element("#element").isolateScope() or $("#element").isolateScope() to access the scope and/or the controller of your directive.

Where are the python modules stored?

  1. Is there a way to obtain a list of Python modules available (i.e. installed) on a machine?

This works for me:

help('modules')
  1. Where is the module code actually stored on my machine?

Usually in /lib/site-packages in your Python folder. (At least, on Windows.)

You can use sys.path to find out what directories are searched for modules.

PHPExcel auto size column width

This code snippet will auto size all the columns that contain data in all the sheets. There is no need to use the activeSheet getter and setter.

// In my case this line didn't make much of a difference
PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);
// Iterating all the sheets
/** @var PHPExcel_Worksheet $sheet */
foreach ($objPHPExcel->getAllSheets() as $sheet) {
    // Iterating through all the columns
    // The after Z column problem is solved by using numeric columns; thanks to the columnIndexFromString method
    for ($col = 0; $col <= PHPExcel_Cell::columnIndexFromString($sheet->getHighestDataColumn()); $col++) {
        $sheet->getColumnDimensionByColumn($col)->setAutoSize(true);
    }
}

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

RoboSpice Vs. Volley

From https://groups.google.com/forum/#!topic/robospice/QwVCfY_glOQ

  • RoboSpice(RS) is service based and more respectful of Android philosophy than Volley. Volley is thread based and this is not the way background processing should take place on Android. Ultimately, you can dig down both libs and find that they are quite similar, but our way to do background processing is more Android oriented, it allow us, for instance, to tell users that RS is actually doing something in background, which would be hard for volley (actually it doesn't at all).
  • RoboSpice and volley both offer nice features like prioritization, retry policies, request cancellation. But RS offers more : a more advanced caching and that's a big one, with cache management, request aggregation, more features like repluging to a pending request, dealing with cache expiry without relying on server headers, etc.
  • RoboSpice does more outside of UI Thread : volley will deserialize your POJOs on the main thread, which is horrible to my mind. With RS your app will be more responsive.
  • In terms of speed, we definitely need metrics. RS has gotten super fast now, but still we don't have figure to put here. Volley should theoretically be a bit faster, but RS is now massively parallel... who knows ?
  • RoboSpice offers a large compatibility range with extensions. You can use it with okhttp, retrofit, ormlite (beta), jackson, jackson2, gson, xml serializer, google http client, spring android... Quite a lot. Volley can be used with ok http and uses gson. that's it.
  • Volley offers more UI sugar that RS. Volley provides NetworkImageView, RS does provide a spicelist adapter. In terms of feature it's not so far, but I believe Volley is more advanced on this topic.
  • More than 200 bugs have been solved in RoboSpice since its initial release. It's pretty robust and used heavily in production. Volley is less mature but its user base should be growing fast (Google effect).
  • RoboSpice is available on maven central. Volley is hard to find ;)

Redirect parent window from an iframe action

or an alternative is the following (using document object)

parent.document.location.href = "http://example.com";

How do I tell a Python script to use a particular version

I had this problem and just decided to rename one of the programs from python.exe to python2.7.exe. Now I can specify on command prompt which program to run easily without introducing any scripts or changing environmental paths. So i have two programs: python2.7 and python (the latter which is v.3.8 aka default).

Can I pass parameters by reference in Java?

In Java there is nothing at language level similar to ref. In Java there is only passing by value semantic

For the sake of curiosity you can implement a ref-like semantic in Java simply wrapping your objects in a mutable class:

public class Ref<T> {

    private T value;

    public Ref(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }

    public void set(T anotherValue) {
        value = anotherValue;
    }

    @Override
    public String toString() {
        return value.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return value.equals(obj);
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }
}

testcase:

public void changeRef(Ref<String> ref) {
    ref.set("bbb");
}

// ...
Ref<String> ref = new Ref<String>("aaa");
changeRef(ref);
System.out.println(ref); // prints "bbb"

Swift - iOS - Dates and times in different format

func convertDateFormater(date: String) -> String {   
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    dateFormatter.timeZone = NSTimeZone(name: "UTC")

    guard let date = dateFormatter.dateFromString(date) else {
        assert(false, "no date from string")
        return ""
    }

    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date)

    return timeStamp
}

Edit for Swift 4

func convertDateFormatter(date: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    dateFormatter.locale = Locale(identifier: "your_loc_id")
    let convertedDate = dateFormatter.date(from: date)

    guard dateFormatter.date(from: date) != nil else {
        assert(false, "no date from string")
        return ""
    } 

    dateFormatter.dateFormat = "yyyy MMM HH:mm EEEE"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: convertedDate!)

    return timeStamp
}

PHP PDO returning single row

$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );

$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];

$DBH = null;

You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.

You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.

Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.

Binary Search Tree - Java Implementation

Here is a sample implementation:

import java.util.*;

public class MyBSTree<K,V> implements MyTree<K,V>{
    private BSTNode<K,V> _root;
    private int _size;
    private Comparator<K> _comparator;
    private int mod = 0;

    public MyBSTree(Comparator<K> comparator){
        _comparator = comparator;
    }

    public Node<K,V> root(){
        return _root;
    }

    public int size(){
        return _size;
    }

    public boolean containsKey(K key){
        if(_root == null){
            return false;
        }

        BSTNode<K,V> node = _root;

        while (node != null){
            int comparison = compare(key, node.key());

            if(comparison == 0){
                return true;
            }else if(comparison <= 0){
                node = node._left;
            }else {
                node = node._right;
            }
        }

        return false;
    }

    private int compare(K k1, K k2){
        if(_comparator != null){
            return _comparator.compare(k1,k2);
        }
        else {
            Comparable<K> comparable = (Comparable<K>)k1;
            return comparable.compareTo(k2);
        }
    }


    public V get(K key){
        Node<K,V> node = node(key);

        return node != null ? node.value() : null;
    }

    private BSTNode<K,V> node(K key){
        if(_root != null){
            BSTNode<K,V> node = _root;

            while (node != null){
                int comparison = compare(key, node.key());

                if(comparison == 0){
                    return node;
                }else if(comparison <= 0){
                    node = node._left;
                }else {
                    node = node._right;
                }
            }
        }

        return null;
    }

    public void add(K key, V value){
        if(key == null){
            throw new IllegalArgumentException("key");
        }

        if(_root == null){
            _root = new BSTNode<K, V>(key, value);
        }

        BSTNode<K,V> prev = null, curr = _root;
        boolean lastChildLeft = false;
        while(curr != null){
            int comparison = compare(key, curr.key());
            prev = curr;

            if(comparison == 0){
                curr._value = value;
                return;
            }else if(comparison < 0){
                curr = curr._left;
                lastChildLeft = true;
            }
            else{
                curr = curr._right;
                lastChildLeft = false;
            }
        }

        mod++;
        if(lastChildLeft){
            prev._left = new BSTNode<K, V>(key, value);
        }else {
            prev._right = new BSTNode<K, V>(key, value);
        }
    }

    private void removeNode(BSTNode<K,V> curr){
        if(curr.left() == null && curr.right() == null){
            if(curr == _root){
                _root = null;
            }else{
                if(curr.isLeft()) curr._parent._left = null;
                else curr._parent._right = null;
            }
        }
        else if(curr._left == null && curr._right != null){
            curr._key = curr._right._key;
            curr._value = curr._right._value;
            curr._left = curr._right._left;
            curr._right = curr._right._right;
        }
        else if(curr._left != null && curr._right == null){
            curr._key = curr._left._key;
            curr._value = curr._left._value;
            curr._right = curr._left._right;
            curr._left = curr._left._left;
        }
        else { // both left & right exist
            BSTNode<K,V> x = curr._left;
            // find right-most node of left sub-tree
            while (x._right != null){ 
                x = x._right;
            }
            // move that to current
            curr._key = x._key;
            curr._value = x._value;
            // delete duplicate data
            removeNode(x);
        }
    }


    public V remove(K key){
        BSTNode<K,V> curr = _root;
        V val = null;
        while(curr != null){
            int comparison = compare(key, curr.key());
            if(comparison == 0){
                val = curr._value;
                removeNode(curr);
                mod++;
                break;
            }else if(comparison < 0){
                curr = curr._left;
            }
            else{
                curr = curr._right;
            }
        }

        return val;
    }

    public Iterator<MyTree.Node<K,V>> iterator(){
        return new MyIterator();
    }

    private class MyIterator implements Iterator<Node<K,V>>{
        int _startMod;
        Stack<BSTNode<K,V>> _stack;

        public MyIterator(){
            _startMod = MyBSTree.this.mod;
            _stack = new Stack<BSTNode<K, V>>();

            BSTNode<K,V> node = MyBSTree.this._root;
            while (node != null){
                _stack.push(node);
                node = node._left;
            }
        }

        public void remove(){
            throw new UnsupportedOperationException();
        }

        public boolean hasNext(){
            if(MyBSTree.this.mod != _startMod){
                throw new ConcurrentModificationException();
            }

            return !_stack.empty();
        }

        public Node<K,V> next(){
            if(MyBSTree.this.mod != _startMod){
                throw new ConcurrentModificationException();
            }

            if(!hasNext()){
                throw new NoSuchElementException();
            }

            BSTNode<K,V> node = _stack.pop();
            BSTNode<K,V> x = node._right;
            while (x != null){
                _stack.push(x);
                x = x._left;
            }

            return node;
        }
    }

    @Override
    public String toString(){
        if(_root == null) return "[]";

        return _root.toString();
    }

    private static class BSTNode<K,V> implements Node<K,V>{
        K _key;
        V _value;
        BSTNode<K,V> _left, _right, _parent;

        public BSTNode(K key, V value){
            if(key == null){
                throw new IllegalArgumentException("key");
            }

            _key = key;
            _value = value;
        }

        public K key(){
            return _key;
        }

        public V value(){
            return _value;
        }

        public Node<K,V> left(){
            return _left;
        }

        public Node<K,V> right(){
            return _right;
        }

        public Node<K,V> parent(){
            return _parent;
        }

        boolean isLeft(){
            if(_parent == null) return false;

            return _parent._left == this;
        }

        boolean isRight(){
            if(_parent == null) return false;

            return _parent._right == this;
        }

        @Override
        public boolean equals(Object o){
            if(o == null){
                return false;
            }

            try{
                BSTNode<K,V> node = (BSTNode<K,V>)o;
                return node._key.equals(_key) && ((_value == null && node._value == null) || (_value != null && _value.equals(node._value)));
            }catch (ClassCastException ex){
                return false;
            }
        }

        @Override
        public int hashCode(){
            int hashCode = _key.hashCode();

            if(_value != null){
                hashCode ^= _value.hashCode();
            }

            return hashCode;
        }

        @Override
        public String toString(){
            String leftStr = _left != null ? _left.toString() : "";
            String rightStr = _right != null ? _right.toString() : "";
            return "["+leftStr+" "+_key+" "+rightStr+"]";
        }
    }
}

Using await outside of an async function

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

how to Call super constructor in Lombok

If child class has more members, than parent, it could be done not very clean, but short way:

@Data
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class User extends BaseEntity {
    private @NonNull String fullName;
    private @NonNull String email;
    ... 

    public User(Integer id, String fullName, String email, ....) {
        this(fullName, email, ....);
        this.id = id;
    }
}

@Data
@AllArgsConstructor
abstract public class BaseEntity {
   protected Integer id;

   public boolean isNew() {
      return id == null;
   }
}

getElementById returns null?

It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

Please, post your code.

android: stretch image in imageview to fit screen

The accepted answer is perfect, however if you want to do it from xml, you can use android:scaleType="fitXY"

How to "add existing frameworks" in Xcode 4?

I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.

AngularJS $watch window resize inside directive

You shouldn't need a $watch. Just bind to resize event on window:

DEMO

'use strict';

var app = angular.module('plunker', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){

         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);

CSS "and" and "or"

A word of caution. Stringing together several not selectors increases the specificity of the resulting selector, which makes it harder to override: you'll basically need to find the selector with all the nots and copy-paste it into your new selector.

A not(X or Y) selector would be great to avoid inflating specificity, but I guess we'll have to stick to combining the opposites, like in this answer.

Jenkins - passing variables between jobs?

Just add my answer in addition to Nigel Kirby's as I can't comment yet:

In order to pass a dynamically created parameter, you can also export the variable in 'Execute Shell' tile and then pass it through 'Trigger parameterized build on other projects' => 'Predefined parameters" => give 'YOUR_VAR=$YOUR_VAR'. My team use this feature to pass npm package version from build job to deployment jobs

UPDATE: above only works for Jenkins injected parameters, parameter created from shell still need to use same method. eg. echo YOUR_VAR=${YOUR_VAR} > variable.properties and pass that file downstream

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/