Programs & Examples On #Image optimization

Image optimization deals with optimization methods for image manipulation and display. How to better process image data, how to allow for more efficient display of images, etc.

How to use bootstrap datepicker

man you can use the basic Bootstrap Datepicker this way:

<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#pickyDate').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

and inside body:

<body>
<div id="testDIV">
    <div class="container">
        <div class="hero-unit">
            <input  type="text" placeholder="click to show datepicker"  id="pickyDate"/>
        </div>
    </div>
</div>

datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.

Getting or changing CSS class property with Javascript using DOM style

As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.

This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...

function changeBGColor() {
  var cols = document.getElementsByClassName('col1');
  for(i = 0; i < cols.length; i++) {
    cols[i].style.backgroundColor = 'blue';
  }
}

How to sign in kubernetes dashboard?

Combining two answers: 49992698 and 47761914 :

# Create service account
kubectl create serviceaccount -n kube-system cluster-admin-dashboard-sa

# Bind ClusterAdmin role to the service account
kubectl create clusterrolebinding -n kube-system cluster-admin-dashboard-sa \
  --clusterrole=cluster-admin \
  --serviceaccount=kube-system:cluster-admin-dashboard-sa

# Parse the token
TOKEN=$(kubectl describe secret -n kube-system $(kubectl get secret -n kube-system | awk '/^cluster-admin-dashboard-sa-token-/{print $1}') | awk '$1=="token:"{print $2}')

Error in spring application context schema

I have recently had same issue with JPA-1.3

Nothing worked until I used explicit tools.xsd link

xsi:schemaLocation=" ...
    http://www.springframework.org/schema/tool
    http://www.springframework.org/schema/tool/spring-tool-3.2.xsd
    ... ">

like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/jdbc 
        http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tool
        http://www.springframework.org/schema/tool/spring-tool-3.2.xsd
        ">

Item frequency count in Python

freqs = {}
for word in words:
    freqs[word] = freqs.get(word, 0) + 1 # fetch and increment OR initialize

I think this results to the same as Triptych's solution, but without importing collections. Also a bit like Selinap's solution, but more readable imho. Almost identical to Thomas Weigel's solution, but without using Exceptions.

This could be slower than using defaultdict() from the collections library however. Since the value is fetched, incremented and then assigned again. Instead of just incremented. However using += might do just the same internally.

How can I generate a tsconfig.json file?

For those who have TypeScript installed as a local package (and possibly as a dev dependency) via:

$ npm install typescript --save-dev

...and who have added tsc script to package.json:

"scripts": {
   ...
   "tsc": "tsc"
},

You can call tsc --init via npm:

$ npm run tsc -- --init 

How to remove first and last character of a string?

This way you can remove 1 leading "[" and 1 trailing "]" character. If your string happen to not start with "[" or end with "]" it won't remove anything:

str.replaceAll("^\\[|\\]$", "")

What is the correct way to check for string equality in JavaScript?

Considering that both strings may be very large, there are 2 main approaches bitwise search and localeCompare

I recommed this function

function compareLargeStrings(a,b){
    if (a.length !== b.length) {
         return false;
    }
    return a.localeCompare(b) === 0;
}

Spring,Request method 'POST' not supported

In Jsp:

action="profile/proffiesional"

In Controller

@RequestMapping(value = "proffessional", method = RequestMethod.POST)

Spelling MisMatch !

How to write a std::string to a UTF-8 text file

Use Glib::ustring from glibmm.

It is the only widespread UTF-8 string container (AFAIK). While glyph (not byte) based, it has the same method signatures as std::string so the port should be simple search and replace (just make sure that your data is valid UTF-8 before loading it into a ustring).

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

Redirecting to previous page after login? PHP

@philipobenito's answer worked best for me.
I first created a hidden input that contain the user's HTTP referer

<input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" />

and after a successful login i redirected the users to whatever value was stored in that hidden input

$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if(!empty($_POST['referer'])){
    header('Location: '.$_POST['referer']);
}
else{
    header('Location: members.php'); //members.php is a page used to send a user to their profile page.
}
exit;

MySQL Insert with While Loop

You cannot use WHILE like that; see: mysql DECLARE WHILE outside stored procedure how?

You have to put your code in a stored procedure. Example:

CREATE PROCEDURE myproc()
BEGIN
    DECLARE i int DEFAULT 237692001;
    WHILE i <= 237692004 DO
        INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
        SET i = i + 1;
    END WHILE;
END

Fiddle: http://sqlfiddle.com/#!2/a4f92/1

Alternatively, generate a list of INSERT statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:

for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done

By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.

paint() and repaint() in Java

The paint() method supports painting via a Graphics object.

The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

It might be too late to answer this in 2019. but I tried all the answers and none worked for me. So I solved it simply this way:

@Html.EditorFor(m => m.SellDateForInstallment, "{0:dd/MM/yyyy}", 
               new {htmlAttributes = new { @class = "form-control", @type = "date" } })

EditorFor is what worked for me.

Note that SellDateForInstallment is a Nullable datetime object.

public DateTime? SellDateForInstallment { get; set; } // Model property

Usage of @see in JavaDoc?

A good example of a situation when @see can be useful would be implementing or overriding an interface/abstract class method. The declaration would have javadoc section detailing the method and the overridden/implemented method could use a @see tag, referring to the base one.

Related question: Writing proper javadoc with @see?

Java SE documentation: @see

Where does the slf4j log file get saved?

It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).

how to set font size based on container size?

Another js alternative:

Working Example

fontsize = function () {
    var fontSize = $("#container").width() * 0.10; // 10% of container width
    $("#container h1").css('font-size', fontSize);
};
$(window).resize(fontsize);
$(document).ready(fontsize);

Or as stated in torazaburo's answer you could use svg. I put together a simple example as a proof of concept:

SVG Example

<div id="container">
    <svg width="100%" height="100%" viewBox="0 0 13 15">
        <text x="0" y="13">X</text>
    </svg>
</div>

How can I make setInterval also work when a tab is inactive in Chrome?

I was able to call my callback function at minimum of 250ms using audio tag and handling its ontimeupdate event. Its called 3-4 times in a second. Its better than one second lagging setTimeout

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

Batch files: List all files in a directory with relative paths

This answer will not work correctly with root paths containing equal signs (=). (Thanks @dbenham for pointing that out.)


EDITED: Fixed the issue with paths containing !, again spotted by @dbenham (thanks!).

Alternatively to calculating the length and extracting substrings you could use a different approach:

  • store the root path;

  • clear the root path from the file paths.

Here's my attempt (which worked for me):

@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
  SET "p=%%F"
  SETLOCAL EnableDelayedExpansion
  ECHO(!p:%r%=!
  ENDLOCAL
)

The r variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with \, which we amend by appending the character. (No longer the case, as the script now reads the __CD__ variable, whose value always ends with \ (thanks @jeb!), instead of CD.)

In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.

Flask at first run: Do not use the development server in a production environment

If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run

$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run

Alternatively you can do the following (I haven't tried this but one resource online talks about it)

$ export FLASK_APP = hello.py
$ python -m flask run

source: For more

jQuery selector to get form by name

You have no combinator (space, >, +...) so no children will get involved, ever.

However, you could avoid the need for jQuery by using an ID and getElementById, or you could use the old getElementsByName("frmSave")[0] or the even older document.forms['frmSave']. jQuery is unnecessary here.

Error pushing to GitHub - insufficient permission for adding an object to repository database

Since the error deals with permissions on the object folder, I did a chown directly on the objects folder and it worked for me.

How to display an alert box from C# in ASP.NET?

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true); 

You can use this way, but be sure that there is no Page.Redirect() is used. If you want to redirect to another page then you can try this:

page.aspx:

<asp:Button AccessKey="S" ID="submitBtn" runat="server" OnClick="Submit" Text="Submit"
                                        Width="90px" ValidationGroup="vg" CausesValidation="true" OnClientClick = "Confirm()" />

JavaScript code:

function Confirm()
{
   if (Page_ClientValidate())
   {
      var confirm_value = document.createElement("INPUT");
      confirm_value.type = "hidden";
      confirm_value.name = "confirm_value";
      if (confirm("Data has been Added. Do you wish to Continue ?"))
      {
         confirm_value.value = "Yes";
      }
      else
      {
         confirm_value.value = "No";
      }
      document.forms[0].appendChild(confirm_value);
   }
}

and this is your code behind snippet :

protected void Submit(object sender, EventArgs e)
{
   string confirmValue = Request.Form["confirm_value"];
   if (confirmValue == "Yes")
   {
      Response.Redirect("~/AddData.aspx");
   }
   else
   {
      Response.Redirect("~/ViewData.aspx");
   }
}

This will sure work.

Convert python datetime to epoch with strftime

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0

Why are C++ inline functions in the header?

The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.

Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

How can I setup & run PhantomJS on Ubuntu?

From the official site: phantomjs site

sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev
git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 1.8
./build.sh

Pretty printing JSON from Jackson 2.2's ObjectMapper

the IDENT_OUTPUT did not do anything for me, and to give a complete answer that works with my jackson 2.2.3 jars:

public static void main(String[] args) throws IOException {

byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));

ObjectMapper objectMapper = new ObjectMapper();

Object json = objectMapper.readValue( jsonBytes, Object.class );

System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
}

applying css to specific li class

The CSS you have applies color #c1c1c1 to all <a> elements.

And it also applies color #c1c1c1 to the first <li> element.

Perhaps the code you posted is missing something because I don't see any other colors being defined.

Setting Action Bar title and subtitle

Try This

Just go to your Manifest file. and You have define the label for each activity in your manifest file.

<activity
        android:name=".Search_Video"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
    </activity>

here change

android:label="@string/your_title"

Javascript how to parse JSON array

This is my answer,

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br> 
Last Name: <span id="lname"></span><br> 
</p> 
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
    var counter = jsonData.employees[i];
    //console.log(counter.counter_name);
    alert(counter.firstName);
}

</script>
</body>
</html>

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

Ok uninstall the app, but we admit that the data not must be lost? This can be resolve, upgrading versionCode and versionName and try the application in "Release" mode.

For example, this is important when we want to try the migration of our Database. We can compare the our application on play store with actual application not release yet.

CSS selector (id contains part of text)

<div id='element_123_wrapper_text'>My sample DIV</div>

The Operator ^ - Match elements that starts with given value

div[id^="element_123"] {

}

The Operator $ - Match elements that ends with given value

div[id$="wrapper_text"] {

}

The Operator * - Match elements that have an attribute containing a given value

div[id*="wrapper_text"] {

}

update columns values with column of another table based on condition

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);

How to convert an ASCII character into an int in C

You mean the ASCII ordinal value? Try type casting like this one:

int x = 'a';

How to add a new row to datagridview programmatically

You can do:

DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells[0].Value = "XYZ";
row.Cells[1].Value = 50.2;
yourDataGridView.Rows.Add(row);

or:

DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells["Column2"].Value = "XYZ";
row.Cells["Column6"].Value = 50.2;
yourDataGridView.Rows.Add(row);

Another way:

this.dataGridView1.Rows.Add("five", "six", "seven","eight");
this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");

From: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rows.aspx

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Get the first element of an array

$array=array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

$firstValue = each($array)[1];

This is much more efficient than array_values() because the each() function does not copy the entire array.

For more info see http://www.php.net/manual/en/function.each.php

Store query result in a variable using in PL/pgSQL

You can use the following example to store a query result in a variable using PL/pgSQL:

 select * into demo from maintenanceactivitytrack ; 
    raise notice'p_maintenanceid:%',demo;

jQuery $.ajax request of dataType json will not retrieve data from PHP script

Try this...  
  <script type="text/javascript">

    $(document).ready(function(){

    $("#find").click(function(){
        var username  = $("#username").val();
            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'includes/find.php',
            data: 'username='+username,
            success: function( data ) {
            //in data you result will be available...
            response = jQuery.parseJSON(data);
//further code..
            },

    error: function(xhr, status, error) {
        alert(status);
        },
    dataType: 'text'

    });
        });

    });



    </script>

    <form name="Find User" id="userform" class="invoform" method="post" />

    <div id ="userdiv">
      <p>Name (Lastname, firstname):</p>
      </label>
      <input type="text" name="username" id="username" class="inputfield" />
      <input type="button" name="find" id="find" class="passwordsubmit" value="find" />
    </div>
    </form>
    <div id="userinfo"><b>info will be listed here.</b></div>

Comments in Markdown

I use standard HTML tags, like

<!---
your comment goes here
and here
-->

Note the triple dash. The advantage is that it works with pandoc when generating TeX or HTML output. More information is available on the pandoc-discuss group.

how to add super privileges to mysql database?

You can add super privilege using phpmyadmin:

Go to PHPMYADMIN > privileges > Edit User > Under Administrator tab Click SUPER. > Go

If you want to do it through Console, do like this:

 mysql> GRANT SUPER ON *.* TO user@'localhost' IDENTIFIED BY 'password';

After executing above code, end it with:

mysql> FLUSH PRIVILEGES;

You should do in on *.* because SUPER is not the privilege that applies just to one database, it's global.

How to lazy load images in ListView in Android

Check my fork of LazyList. Basically, I improve the LazyList by delaying the call of the ImageView and create two methods:

  1. When you need to put something like "Loading image..."
  2. When you need to show the downloaded image.

I also improved the ImageLoader by implementing a singleton in this object.

width:auto for <input> fields

Because input's width is controlled by it's size attribute, this is how I initialize an input width according to its content:

<input type="text" class="form-list-item-name" [size]="myInput.value.length" #myInput>

How to get htaccess to work on MAMP

The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with

RewriteBase /

Which doesn't seem to work in MAMP...at least for me.

Removing the password from a VBA project

My 2 cents on Excel 2016:

  1. open the xls file with Notepad++
  2. Search for DPB= and replace it with DPx=
  3. Save the file
  4. Open the file, open the VB Editor, open modules will not work (error 40230)
  5. Save the file as xlsm
  6. It works

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

Python installation folder > Lib > idlelib > idle.pyw

send a shortcut to desktop.

From the desktop shortcut you can add it to taskbar too for quickaccess.

Hope this helps.

Where are Magento's log files located?

These code lines can help you quickly enable log setting in your magento site.

INSERT INTO `core_config_data` (`config_id`, `scope`, `scope_id`, `path`, `value`) VALUES
('', 'default', 0, 'dev/log/active', '1'),
('', 'default', 0, 'dev/log/file', 'system.log'),
('', 'default', 0, 'dev/log/exception_file', 'exception.log');

Then you can see them inside the folder: /var/log under root installation.

More detail in this blog

What does the "static" modifier after "import" mean?

Very good exaple. npt tipical with MAth in wwww....

https://www.java2novice.com/java-fundamentals/static-import/

public class MyStaticMembClass {
 
    public static final int INCREMENT = 2;
     
    public static int incrementNumber(int number){
        return number+INCREMENT;
    }
}

in onother file inlude

import static com.java2novice.stat.imp.pac1.MyStaticMembClass.*;

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

I encountered some weird behaviour that did not reflect the actual code base so after some time trying several solutions, my problem was solved by manually deleting everything under /var/cache/tomcat8/

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

Here's a working solution (2019): put this code inside your login logic;

 GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject json, GraphResponse response) {
                    // Application code
                    if (response.getError() != null) {
                        System.out.println("ERROR");
                    } else {
                        System.out.println("Success");
                        String jsonresult = String.valueOf(json);
                        System.out.println("JSON Result" + jsonresult);

                        String fbUserId = json.optString("id");
                        String fbUserFirstName = json.optString("name");
                        String fbUserEmail = json.optString("email");
                        //String fbUserProfilePics = "http://graph.facebook.com/" + fbUserId + "/picture?type=large";
                        Log.d("SignUpActivity", "Email: " + fbUserEmail + "\nName: " + fbUserFirstName + "\nID: " + fbUserId);
                    }
                    Log.d("SignUpActivity", response.toString());
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender, birthday");
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
            setResult(RESULT_CANCELED);
            Toast.makeText(SignUpActivity.this, "Login Attempt Cancelled", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException error) {
            Toast.makeText(SignUpActivity.this, "An Error Occurred", Toast.LENGTH_LONG).show();
            error.printStackTrace();
        }
    });

Get first n characters of a string

This is what i do

    function cutat($num, $tt){
        if (mb_strlen($tt)>$num){
            $tt=mb_substr($tt,0,$num-2).'...';
        }
        return $tt;
    }

where $num stands for number of chars, and $tt the string for manipulation.

How to remove folders with a certain name

I ended up here looking to delete my node_modules folders before doing a backup of my work in progress using rsync. A key requirements is that the node_modules folder can be nested, so you need the -prune option.

First I ran this to visually verify the folders to be deleted:

find -type d -name node_modules -prune

Then I ran this to delete them all:

find -type d -name node_modules -prune -exec rm -rf {} \;

Thanks to pistache

IF a cell contains a string

SEARCH does not return 0 if there is no match, it returns #VALUE!. So you have to wrap calls to SEARCH with IFERROR.

For example...

=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")

or

=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))

Here, IFERROR returns the value from SEARCH when it works; the given value of 0 otherwise.

Custom ImageView with drop shadow

This works for me ...

public class ShadowImage extends Drawable {

Bitmap bm;

@Override
public void draw(Canvas canvas) {

    Paint mShadow = new Paint();
    Rect rect = new Rect(0,0,bm.getWidth(), bm.getHeight());

    mShadow.setAntiAlias(true);
    mShadow.setShadowLayer(5.5f, 4.0f, 4.0f, Color.BLACK);

    canvas.drawRect(rect, mShadow);
    canvas.drawBitmap(bm, 0.0f, 0.0f, null);

}

public ShadowImage(Bitmap bitmap) {
    super();
    this.bm = bitmap;
} ... }

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

How can I get zoom functionality for images?

UPDATE

I've just given TouchImageView a new update. It now includes Double Tap Zoom and Fling in addition to Panning and Pinch Zoom. The code below is very dated. You can check out the github project to get the latest code.

USAGE

Place TouchImageView.java in your project. It can then be used the same as ImageView. Example:

TouchImageView img = (TouchImageView) findViewById(R.id.img);

If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view. Example:

<com.example.touch.TouchImageView
    android:id="@+id/img”
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Note: I've removed my prior answer, which included some very old code and now link straight to the most updated code on github.

ViewPager

If you are interested in putting TouchImageView in a ViewPager, refer to this answer.

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

How does a Linux/Unix Bash script know its own PID?

The PID is stored in $$.

Example: kill -9 $$ will kill the shell instance it is called from.

Octave/Matlab: Adding new elements to a vector

x(end+1) = newElem is a bit more robust.

x = [x newElem] will only work if x is a row-vector, if it is a column vector x = [x; newElem] should be used. x(end+1) = newElem, however, works for both row- and column-vectors.

In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)

Is there a php echo/print equivalent in javascript

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).

Char to int conversion in C

As others have suggested, but wrapped in a function:

int char_to_digit(char c) {
    return c - '0';
}

Now just use the function. If, down the line, you decide to use a different method, you just need to change the implementation (performance, charset differences, whatever), you wont need to change the callers.

This version assumes that c contains a char which represents a digit. You can check that before calling the function, using ctype.h's isdigit function.

SQL like search string starts with

SELECT * from games WHERE (lower(title) LIKE 'age of empires III');

The above query doesn't return any rows because you're looking for 'age of empires III' exact string which doesn't exists in any rows.

So in order to match with this string with different string which has 'age of empires' as substring you need to use '%your string goes here%'

More on mysql string comparision

You need to try this

SELECT * from games WHERE (lower(title) LIKE '%age of empires III%');

In Like '%age of empires III%' this will search for any matching substring in your rows, and it will show in results.

Using Math.round to round to one decimal place?

DecimalFormat decimalFormat = new DecimalFormat(".#");
String result = decimalFormat.format(12.763);                // -->  12.7

How to highlight a current menu item?

Using a directive (since we are doing DOM manipulation here) the following is probably the closest to doing things the "angular way":

$scope.timeFilters = [
  {'value':3600,'label':'1 hour'},
  {'value':10800,'label':'3 hours'},
  {'value':21600,'label':'6 hours'},
  {'value':43200,'label':'12 hours'},
  {'value':86400,'label':'24 hours'},
  {'value':604800,'label':'1 week'}
]

angular.module('whatever', []).directive('filter',function(){
return{
    restrict: 'A',
    template: '<li ng-repeat="time in timeFilters" class="filterItem"><a ng-click="changeTimeFilter(time)">{{time.label}}</a></li>',
    link: function linkFn(scope, lElement, attrs){

        var menuContext = attrs.filter;

        scope.changeTimeFilter = function(newTime){
          scope.selectedtimefilter = newTime;

        }

        lElement.bind('click', function(cevent){
            var currentSelection = angular.element(cevent.srcElement).parent();
            var previousSelection = scope[menuContext];

            if(previousSelection !== currentSelection){
                if(previousSelection){
                    angular.element(previousSelection).removeClass('active')
                }
                scope[menuContext] = currentSelection;

                scope.$apply(function(){
                    currentSelection.addClass('active');
                })
            }
        })
    }
}
})

Then your HTML would look like:

<ul class="dropdown-menu" filter="times"></ul>

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I got an error in Eclipse Mars version as "Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment.

To resolve this issue, please do the following steps, "Right click on Project Choose Build path Choose Configure Build path Choose Libraries tab Select JRE System Library and click on Edit button Choose workspace default JRE and Finish

Problem will be resolved.

How to get the data-id attribute?

HTML

<span id="spanTest" data-value="50">test</span>

JS

$(this).data().value;

or

$("span#spanTest").data().value;

ANS : 50

Works for me!

How to enable CORS on Firefox?

Do nothing to the browser. CORS is supported by default on all modern browsers (and since Firefox 3.5).

The server being accessed by JavaScript has to give the site hosting the HTML document in which the JS is running permission via CORS HTTP response headers.


security.fileuri.strict_origin_policy is used to give JS in local HTML documents access to your entire hard disk. Don't set it to false as it makes you vulnerable to attacks from downloaded HTML documents (including email attachments).

How can I create a dynamically sized array of structs?

Here is how I would do it in C++

size_t size = 500;
char* dynamicAllocatedString = new char[ size ];

Use same principal for any struct or c++ class.

How to create a batch file to run cmd as administrator

To prevent the script from failing when the script file resides on a non system drive (c:) and in a directory with spaces.

Batch_Script_Run_As_Admin.cmd

@echo off
if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload

::ENTER YOUR CODE BELOW::   





::END OF YOUR CODE::

echo.
echo...Script Complete....
echo.

pause

How to read a local text file?

If you want to prompt the user to select a file, then read its contents:

// read the contents of a file input
const readInputFile = (inputElement, callback) => {
  const reader = new FileReader();
  reader.onload = () => {
    callback(reader.result)
  };
  reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
export const openFile = (callback) => {
  var el = document.createElement('input');
  el.setAttribute('type', 'file');
  el.style.display = 'none';
  document.body.appendChild(el);
  el.onchange = () => {readInputFile(el, (data) => {
    callback(data)
    document.body.removeChild(el);
  })}
  el.click();
}

Usage:

// prompt the user to select a file and read it
openFile(data => {
    console.log(data)
  })

Why functional languages?

It's catching on because it's the best tool around for controlling complexity. See:
- slides 109-116 of Simon Peyton-Jones talk "A Taste of Haskell"
- "The Next Mainstream Programming Language: A Game Developer's Perspective" by Tim Sweeney

Questions every good Database/SQL developer should be able to answer

The application is in use 24 hours a day. Your maintenance / update window is 2 hours every month, how do you plan to minimise disruption?

Can someone explain __all__ in Python?

It also changes what pydoc will show:

module1.py

a = "A"
b = "B"
c = "C"

module2.py

__all__ = ['a', 'b']

a = "A"
b = "B"
c = "C"

$ pydoc module1

Help on module module1:

NAME
    module1

FILE
    module1.py

DATA
    a = 'A'
    b = 'B'
    c = 'C'

$ pydoc module2

Help on module module2:

NAME
    module2

FILE
    module2.py

DATA
    __all__ = ['a', 'b']
    a = 'A'
    b = 'B'

I declare __all__ in all my modules, as well as underscore internal details, these really help when using things you've never used before in live interpreter sessions.

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I was also facing the same issue But my issue was due to wrong credentials stored in my keyChain. So I solved by removing my old credentials from my keychain.

what does "dead beef" mean?

The value of 0xDEADBEEF has three practical benefits, mostly for older systems. Old assembler/C hacks, like me, would use it to fill unallocated memory to coax out memory issues. Also, it's a pun of the slang term "dead meat". The programmer is dead meat if DEADBEEF winds up in his pointers. I congratulate the guy who first thought of using the value DEADBEEF. It's clever in many ways.

As for practical reasons, firstly, it's more noticeable in a hex memory dump because it actually spells words as opposed to random hex values.

Secondly, if the value winds up in a pointer, it's more likely to induce a memory out-of-range fault. An address of DEADBEEF was out of the address range of systems (we're talking last century systems now) regardless of the system's endian.

Thirdly, it is more likely to induce a fault on systems that require even boundary pointer values for accessing 16/32/64-bit data. The value is more likely to fault because both of the 16 bit values (DEAD, BEEF) are odd.

There is already an open DataReader associated with this Command which must be closed first

As a side-note...this can also happen when there is a problem with (internal) data-mapping from SQL Objects.

For instance...

I created a SQL Scalar Function that accidentally returned a VARCHAR...and then...used it to generate a column in a VIEW. The VIEW was correctly mapped in the DbContext...so Linq was calling it just fine. However, the Entity expected DateTime? and the VIEW was returning String.

Which ODDLY throws...

"There is already an open DataReader associated with this Command which must be closed first"

It was hard to figure out...but after I corrected the return parameters...all was well

Print Html template in Angular 2 (ng-print in Angular 2)

I ran into the same issue and found another way to do this. It worked for in my case as it was a relatively small application.

First, the user will a click button in the component which needs to be printed. This will set a flag that can be accessed by the app component. Like so

.html file

<button mat-button (click)="printMode()">Print Preview</button>

.ts file

  printMode() {
    this.utilities.printMode = true;
  }

In the html of the app component, we hide everything except the router-outlet. Something like below

<div class="container">       
  <app-header *ngIf="!utilities.printMode"></app-header>
  <mat-sidenav-container>
    <mat-sidenav *ngIf="=!utilities.printMode">
      <app-sidebar></app-sidebar>
    </mat-sidenav>
    <mat-sidenav-content>
      <router-outlet></router-outlet>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

With similar ngIf conidtions, we can also adjust the html template of the component to only show or hide things in printMode. So that the user will see only what needs to get printed when print preview is clicked.

We can now simply print or go back to normal mode with the below code

.html file

<button mat-button class="doNotPrint" (click)="print()">Print</button>
<button mat-button class="doNotPrint" (click)="endPrint()">Close</button>

.ts file

  print() {
    window.print();
  }

  endPrint() {
    this.utilities.printMode = false;
  } 

.css file (so that the print and close button's don't get printed)

@media print{
   .doNotPrint{display:none !important;}
 }

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

What is difference between monolithic and micro kernel?

  1. Monolithic kernel design is much older than the microkernel idea, which appeared at the end of the 1980's.

  2. Unix and Linux kernels are monolithic, while QNX, L4 and Hurd are microkernels. Mach was initially a microkernel (not Mac OS X), but later converted into a hybrid kernel. Minix (before version 3) wasn't a pure microkernel because device drivers were compiled as part of the kernel.

  3. Monolithic kernels are usually faster than microkernels. The first microkernel Mach was 50% slower than most monolithic kernels, while later ones like L4 were only 2% or 4% slower than the monolithic designs.

  4. Monolithic kernels are big in size, while microkernels are small in size - they usually fit into the processor's L1 cache (first generation microkernels).

  5. In monolithic kernels, the device drivers reside in the kernel space while in the microkernels the device drivers are user-space.

  6. Since monolithic kernels' device drivers reside in the kernel space, monolithic kernels are less secure than microkernels, and failures (exceptions) in the drivers may lead to crashes (displayed as BSODs in Windows). Microkernels are more secure than monolithic kernels, hence more often used in military devices.

  7. Monolithic kernels use signals and sockets to implement inter-process communication (IPC), microkernels use message queues. 1st gen microkernels didn't implement IPC well and were slow on context switches - that's what caused their poor performance.

  8. Adding a new feature to a monolithic system means recompiling the whole kernel or the corresponding kernel module (for modular monolithic kernels), whereas with microkernels you can add new features or patches without recompiling.

Detecting Enter keypress on VB.NET

I see this has been answered, but it seems like you could avoid all of this 'remapping' of the enter key by simply hooking your validation into the AcceptButton on a form. ie. you have 3 textboxes (txtA,txtB,txtC) and an 'OK' button set to be AcceptButton (and TabOrder set properly). So, if in txtA and you hit enter, if the data is invalid, your focus will stay in txtA, but if it is valid, assuming the other txts need input, validation will just put you into the next txt that needs valid input thus simulating TAB behaviour... once all txts have valid input, pressing enter will fire a succsessful validation and close form (or whatever...) Make sense?

Grab a segment of an array in Java without creating a new array on heap

You could use the ArrayUtils.subarray in apache commons. Not perfect but a bit more intuitive than System.arraycopy. The downside is that it does introduce another dependency into your code.

How do I update the password for Git?

In Windows 10 with Git

Remove/update related Credentials stored in Windows Credentials in >>Control Panel\All Control Panel Items\Credential Manager

enter image description here

XMLHttpRequest module not defined/found

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

Making a Windows shortcut start relative to where the folder is?

After making the shortcut as you have, set the following in Properties:

Target: %comspec% /k "data\run.bat"

  • Drop the /k if you don't want the prompt to stay open after you've run it.

Start In: %cd%\data

How to parse a string to an int in C++?

This is a safer C way than atoi()

const char* str = "123";
int i;

if(sscanf(str, "%d", &i)  == EOF )
{
   /* error */
}

C++ with standard library stringstream: (thanks CMS )

int str2int (const string &str) {
  stringstream ss(str);
  int num;
  if((ss >> num).fail())
  { 
      //ERROR 
  }
  return num;
}

With boost library: (thanks jk)

#include <boost/lexical_cast.hpp>
#include <string>

try
{
    std::string str = "123";
    int number = boost::lexical_cast< int >( str );
}
catch( const boost::bad_lexical_cast & )
{
    // Error
}

Edit: Fixed the stringstream version so that it handles errors. (thanks to CMS's and jk's comment on original post)

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

Java ArrayList for integers

List of Integer.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

lodash: mapping array to object

This is probably more verbose than you want, but you're asking for a slightly complex operation so actual code might be involved (the horror).

My recommendation, with zipObject that's pretty logical:

_.zipObject(_.map(params, 'name'), _.map(params, 'input'));

Another option, more hacky, using fromPairs:

_.fromPairs(_.map(params, function(val) { return [val['name'], val['input']));

The anonymous function shows the hackiness -- I don't believe JS guarantees order of elements in object iteration, so callling .values() won't do.

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

Creating multiple log files of different content with log4j

I had this question, but with a twist - I was trying to log different content to different files. I had information for a LowLevel debug log, and a HighLevel user log. I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.

My solution was to configure the 3 appenders, and then setup the logging like this:

log4j.threshold=ALL
log4j.rootLogger=,LowLogger

log4j.logger.HighLevel=ALL,Syslog,HighLogger
log4j.additivity.HighLevel=false

The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.

Hope this helps someone at some point!

how to change namespace of entire project?

When I wanted to change namespace and the solution name I did as follows:
1) changed the namespace by selecting it and renaming it and I did the same with solution name
2) clicked on the light bulb and renamed all the instances of old namespace
3) removed all the projects from the solution
4) closed the visual studio
5) renamed all the projects in windows explorer
6) opened visual studio and added all the projects again
7) rename namespaces in all projects in their properties
8) removed bin folder (from all projects)
9) build the project again

That worked for me without any problems and my project had as well source control. All was fine after pushing those changes to the remote.

Twitter bootstrap progress bar animation on page load

While Tats_innit's answer has a nice touch to it, I had to do it a bit differently since I have more than one progress bar on the page.

here's my solution:

JSfiddle: http://jsfiddle.net/vacNJ/

HTML (example):

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="60"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="50"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="40"></div>
</div>

?

JavaScript:

setTimeout(function(){

    $('.progress .bar').each(function() {
        var me = $(this);
        var perc = me.attr("data-percentage");

        var current_perc = 0;

        var progress = setInterval(function() {
            if (current_perc>=perc) {
                clearInterval(progress);
            } else {
                current_perc +=1;
                me.css('width', (current_perc)+'%');
            }

            me.text((current_perc)+'%');

        }, 50);

    });

},300);

@Tats_innit: Using setInterval() to dynamically recalc the progress is a nice solution, thx mate! ;)

EDIT:

A friend of mine wrote a nice jquery plugin for custom twitter bootstrap progress bars. Here's a demo: http://minddust.github.com/bootstrap-progressbar/

Here's the Github repo: https://github.com/minddust/bootstrap-progressbar

Python Selenium accessing HTML source

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')

Now you can apply BeautifulSoup function to extract data...

"Debug certificate expired" error in Eclipse Android plugins

Delete your debug certificate under ~/.android/debug.keystore on Linux and Mac OS X; the directory is something like %USERPROFILE%/.androidon Windows.

The Eclipse plugin should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.

how to merge 200 csv files in Python

A slight change to the code above as it does not actually work correctly.

It should be as follows...

from glob import glob

with open('main.csv', 'a') as singleFile:
    for csv in glob('*.csv'):
        if csv == 'main.csv':
            pass
        else:
            for line in open(csv, 'r'):
                singleFile.write(line)

How to resize image (Bitmap) to a given size?

 Bitmap yourBitmap;
 Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

or:

 resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

ASP.NET Identity reset password

Deprecated

This was the original answer. It does work, but has a problem. What if AddPassword fails? The user is left without a password.

The original answer: we can use three lines of code:

UserManager<IdentityUser> userManager = 
    new UserManager<IdentityUser>(new UserStore<IdentityUser>());

userManager.RemovePassword(userId);

userManager.AddPassword(userId, newPassword);

See also: http://msdn.microsoft.com/en-us/library/dn457095(v=vs.111).aspx

Now Recommended

It's probably better to use the answer that EdwardBrey proposed and then DanielWright later elaborated with a code sample.

How to make a script wait for a pressed key?

I don't know of a platform independent way of doing it, but under Windows, if you use the msvcrt module, you can use its getch function:

import msvcrt
c = msvcrt.getch()
print 'you entered', c

mscvcrt also includes the non-blocking kbhit() function to see if a key was pressed without waiting (not sure if there's a corresponding curses function). Under UNIX, there is the curses package, but not sure if you can use it without using it for all of the screen output. This code works under UNIX:

import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()

Note that curses.getch() returns the ordinal of the key pressed so to make it have the same output I had to cast it.

Difference between break and continue in PHP?

'continue' is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

'break' ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

Check out the following links:

http://www.php.net/manual/en/control-structures.break.php

http://www.php.net/manual/en/control-structures.continue.php

Hope it helps..

Convert Long into Integer

In java ,there is a rigorous way to convert a long to int

not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.

Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);

Getting attributes of Enum's value

This extension method will obtain a string representation of an enum value using its XmlEnumAttribute. If no XmlEnumAttribute is present, it falls back to enum.ToString().

public static string ToStringUsingXmlEnumAttribute<T>(this T enumValue)
    where T: struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("T must be an enumerated type");
    }

    string name;

    var type = typeof(T);

    var memInfo = type.GetMember(enumValue.ToString());

    if (memInfo.Length == 1)
    {
        var attributes = memInfo[0].GetCustomAttributes(typeof(System.Xml.Serialization.XmlEnumAttribute), false);

        if (attributes.Length == 1)
        {
            name = ((System.Xml.Serialization.XmlEnumAttribute)attributes[0]).Name;
        }
        else
        {
            name = enumValue.ToString();
        }
    }
    else
    {
        name = enumValue.ToString();
    }

    return name;
}

PHP Session data not being saved

A common issue often overlooked is also that there must be NO other code or extra spacing before the session_start() command.

I've had this issue before where I had a blank line before session_start() which caused it not to work properly.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

Just wanted to add -- apparently this can also be caused by installing Instant Client for 10, then realizing you want the full install and installing it again in a parallel directory. I don't know why this broke it.

A html space is showing as %2520 instead of %20

For some - possibly valid - reason the url was encoded twice. %25 is the urlencoded % sign. So the original url looked like:

http://server.com/my path/

Then it got urlencoded once:

http://server.com/my%20path/

and twice:

http://server.com/my%2520path/

So you should do no urlencoding - in your case - as other components seems to to that already for you. Use simply a space

Capitalize first letter. MySQL

CREATE A FUNCTION:

CREATE DEFINER=`root`@`localhost` FUNCTION `UC_FIRST`(`oldWord` VARCHAR(255)) 

RETURNS varchar(255) CHARSET utf8

RETURN CONCAT( UCASE( LEFT(oldWord, 1)), LCASE(SUBSTRING(oldWord, 2)))

USE THE FUNCTION

UPDATE tbl_name SET col_name = UC_FIRST(col_name);

Facebook key hash does not match any stored key hashes

My problem is possibly due to the hash got wrongly generated by the openssl itself, if anyone is facing similar problem using the method provided by the facebook android guide itself.

One way to deal with this is :

  1. Get your sha1 using this tool :

keytool -exportcert -keystore path-to-debug-or-production-keystore -list -v

  1. convert it to base64 using this tool

http://tomeko.net/online_tools/hex_to_base64.php

credit :

https://github.com/facebook/react-native-fbsdk/issues/424#issuecomment-469047955

How to programmatically take a screenshot on Android?

Most of the answers for this question use the the Canvas drawing method or drawing cache method. However, the View.setDrawingCache() method is deprecated in API 28. Currently the recommended API for making screenshots is the PixelCopy class available from API 24 (but the methods which accept Window parameter are available from API 26 == Android 8.0 Oreo). Here is a sample Kotlin code for retrieving a Bitmap:

@RequiresApi(Build.VERSION_CODES.O)
fun saveScreenshot(view: View) {
    val window = (view.context as Activity).window
    if (window != null) {
        val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
        val locationOfViewInWindow = IntArray(2)
        view.getLocationInWindow(locationOfViewInWindow)
        try {
            PixelCopy.request(window, Rect(locationOfViewInWindow[0], locationOfViewInWindow[1], locationOfViewInWindow[0] + view.width, locationOfViewInWindow[1] + view.height), bitmap, { copyResult ->
                if (copyResult == PixelCopy.SUCCESS) {
                    saveBitmap(bitmap)
                }
                // possible to handle other result codes ...
            }, Handler())
        } catch (e: IllegalArgumentException) {
            // PixelCopy may throw IllegalArgumentException, make sure to handle it
        }
    }
}

tell pip to install the dependencies of packages listed in a requirement file

Extending Piotr's answer, if you also need a way to figure what to put in requirements.in, you can first use pip-chill to find the minimal set of required packages you have. By combining these tools, you can show the dependency reason why each package is installed. The full cycle looks like this:

  1. Create virtual environment:
    $ python3 -m venv venv
  2. Activate it:
    $ . venv/bin/activate
  3. Install newest version of pip, pip-tools and pip-chill:
    (venv)$ pip install --upgrade pip
    (venv)$ pip install pip-tools pip-chill
  4. Build your project, install more pip packages, etc, until you want to save...
  5. Extract minimal set of packages (ie, top-level without dependencies):
    (venv)$ pip-chill --no-version > requirements.in
  6. Compile list of all required packages (showing dependency reasons):
    (venv)$ pip-compile requirements.in
  7. Make sure the current installation is synchronized with the list:
    (venv)$ pip-sync

How to convert the time from AM/PM to 24 hour format in PHP?

If you use a Datetime format see http://php.net/manual/en/datetime.format.php

You can do this :

$date = new \DateTime();
echo date_format($date, 'Y-m-d H:i:s');
#output: 2012-03-24 17:45:12

echo date_format($date, 'G:ia');
#output: 05:45pm

Installation error: INSTALL_FAILED_OLDER_SDK

You will see the same error if you are trying to install an apk that was built using

compileSdkVersion "android-L"

Even for devices running the final version of Android 5.0. Simply change this to

compileSdkVersion 21

Getting the class of the element that fired an event using JQuery

You will get all the class in below array

event.target.classList

Atom menu is missing. How do I re-enable

Same happened to me, I had to go into Packages and re-enable Tabs and Tree-View (both part of core).

What's the valid way to include an image with no src?

I personally use an about:blank src and deal with the broken image icon by setting the opacity of the img element to 0.

How can I view the allocation unit size of a NTFS partition in Vista?

Another way to find it quickly via the GUI on any windows system:

  1. create a text file, type a word or two (or random text) in it, and save it.

  2. Right-click on the file to show Properties.

  3. "Size on disk" = allocation unit.

How do I turn a python datetime into a string, with readable format date?

Using f-strings, in Python 3.6+.

from datetime import datetime

date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

This is what I finally could do for installing psych package in R-3.4.1 when I got the same warning

1:Googled for that package.

2:downloaded it manually having tar.gz extension

3:Chose the option "Package Archive File (.zip;.tar.gz)" for install packages in R

4:browsed locally to the place where it was downloaded and clicked install

You may get a warning: dependencies 'xyz' not available for the package ,then first install those from the repository and then do steps 3-4 .

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

How to search for an element in an stl list?

No, find() method is not a member of std::list. Instead, use std::find from <algorithm>

    std :: list < int > l;
    std :: list < int > :: iterator pos;

    l.push_back(1);
    l.push_back(2);
    l.push_back(3);
    l.push_back(4);
    l.push_back(5);
    l.push_back(6);

    int elem = 3;   
    pos = find(l.begin() , l.end() , elem);
    if(pos != l.end() )
        std :: cout << "Element is present. "<<std :: endl;
    else
        std :: cout << "Element is not present. "<<std :: endl;

how to modify the size of a column

This was done using Toad for Oracle 12.8.0.49

ALTER TABLE SCHEMA.TABLENAME 
    MODIFY (COLUMNNAME NEWDATATYPE(LENGTH)) ;

For example,

ALTER TABLE PAYROLL.EMPLOYEES 
    MODIFY (JOBTITLE VARCHAR2(12)) ;

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Extract first and last row of a dataframe in pandas

Here is the same style as in large datasets:

x = df[:5]
y = pd.DataFrame([['...']*df.shape[1]], columns=df.columns, index=['...'])
z = df[-5:]
frame = [x, y, z]
result = pd.concat(frame)

print(result)

Output:

                     date  temp
0     1981-01-01 00:00:00  20.7
1     1981-01-02 00:00:00  17.9
2     1981-01-03 00:00:00  18.8
3     1981-01-04 00:00:00  14.6
4     1981-01-05 00:00:00  15.8
...                   ...   ...
3645  1990-12-27 00:00:00    14
3646  1990-12-28 00:00:00  13.6
3647  1990-12-29 00:00:00  13.5
3648  1990-12-30 00:00:00  15.7
3649  1990-12-31 00:00:00    13

Why do we need C Unions?

Unions are great. One clever use of unions I've seen is to use them when defining an event. For example, you might decide that an event is 32 bits.

Now, within that 32 bits, you might like to designate the first 8 bits as for an identifier of the sender of the event... Sometimes you deal with the event as a whole, sometimes you dissect it and compare it's components. unions give you the flexibility to do both.

union Event
{
  unsigned long eventCode;
  unsigned char eventParts[4];
};

A hex viewer / editor plugin for Notepad++?

According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.

Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.

Git mergetool generates unwanted .orig files

I use this to clean up all files ending in ".orig":

function git-clean-orig {
    git status -su | grep -e"\.orig$" | cut -f2 -d" " | xargs rm -r
}

If you are a scaredy-cat :) you could leave the last part off just to list them (or leave off the -r if you want to approve each delete):

function git-show-orig {
    git status -su | grep -e"\.orig$" | cut -f2 -d" "
}

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

Python - TypeError: 'int' object is not iterable

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

What is the correct way to restore a deleted file from SVN?

Use the Tortoise SVN copy functionality to revert commited changes:

  1. Right click the parent folder that contains the deleted files/folder
  2. Select the "show log"
  3. Select and right click on the version before which the changes/deleted was done
  4. Select the "browse repository"
  5. Select the file/folder which needs to be restored and right click
  6. Select "copy to" which will copy the files/folders to the head revision

Hope that helps

Creating dummy variables in pandas for python

Based on the official documentation:

dummies = pd.get_dummies(df['Category']).rename(columns=lambda x: 'Category_' + str(x))
df = pd.concat([df, dummies], axis=1)
df = df.drop(['Category'], inplace=True, axis=1)

There is also a nice post in the FastML blog.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As others have stated, regular (traditional) functions use this from the object that called the function, (e.g. a button that was clicked). Instead, arrow functions use this from the object that defines the function.

Consider two almost identical functions:

regular = function() {
  ' Identical Part Here;
}


arrow = () => {
  ' Identical Part Here;
}

The snippet below demonstrates the fundamental difference between what this represents for each function. The regular function outputs [object HTMLButtonElement] whereas the arrow function outputs [object Window].

_x000D_
_x000D_
<html>_x000D_
 <button id="btn1">Regular: `this` comes from "this button"</button>_x000D_
 <br><br>_x000D_
 <button id="btn2">Arrow: `this` comes from object that defines the function</button>_x000D_
 <p id="res"/>_x000D_
_x000D_
 <script>_x000D_
  regular = function() {_x000D_
    document.getElementById("res").innerHTML = this;_x000D_
  }_x000D_
_x000D_
  arrow = () => {_x000D_
    document.getElementById("res").innerHTML = this;_x000D_
  }_x000D_
_x000D_
  document.getElementById("btn1").addEventListener("click", regular);_x000D_
  document.getElementById("btn2").addEventListener("click", arrow);_x000D_
 </script>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Cannot install packages inside docker Ubuntu image

You need to update the package list in your Ubuntu:

$ sudo apt-get update
$ sudo apt-get install <package_name>

Get nth character of a string in Swift programming language

Swift's String type does not provide a characterAtIndex method because there are several ways a Unicode string could be encoded. Are you going with UTF8, UTF16, or something else?

You can access the CodeUnit collections by retrieving the String.utf8 and String.utf16 properties. You can also access the UnicodeScalar collection by retrieving the String.unicodeScalars property.

In the spirit of NSString's implementation, I'm returning a unichar type.

extension String
{
    func characterAtIndex(index:Int) -> unichar
    {
        return self.utf16[index]
    }

    // Allows us to use String[index] notation
    subscript(index:Int) -> unichar
    {
        return characterAtIndex(index)
    }
}

let text = "Hello Swift!"
let firstChar = text[0]

How do I restart a program based on user input?

You can do this simply with a function. For example:

def script():
    # program code here...
    restart = raw_input("Would you like to restart this program?")
    if restart == "yes" or restart == "y":
        script()
    if restart == "n" or restart == "no":
        print "Script terminating. Goodbye."
script()

Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname(). More on this here.

Regex match entire words only

To match any whole word you would use the pattern (\w+)

Assuming you are using PCRE or something similar:

enter image description here

Above screenshot taken from this live example: http://regex101.com/r/cU5lC2

Matching any whole word on the commandline with (\w+)

I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match

Start phpsh, put some content into a variable, match on word.

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1, $content2 and $content3 with the (\w)+ pattern.

$content1 and $content2 contain at least one word, $content3 does not.

Match a number of literal words on the commandline with (dart|fart)

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

variables gun1 and gun2 contain the string dart or fart. gun4 does not. However it may be a problem that looking for word fart matches farty. To fix this, enforce word boundaries in regex.

Match literal words on the commandline with word boundaries.

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

So it's the same as the previous example except that the word fart with a \b word boundary does not exist in the content: farty.

How can I reverse a NSArray in Objective-C?

Georg Schölly's categories are very nice. However, for NSMutableArray, using NSUIntegers for the indices results in a crash when the array is empty. The correct code is:

@implementation NSMutableArray (Reverse)

- (void)reverse {
    NSInteger i = 0;
    NSInteger j = [self count] - 1;
    while (i < j) {
        [self exchangeObjectAtIndex:i
                  withObjectAtIndex:j];

        i++;
        j--;
    }
}

@end

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

ERROR: JAVA_HOME is set to an invalid directory. JAVA_HOME = "E:\Sun\SDK\jdk\bin" Please set the JAVA_HOME variable in your environment to match the location of your Java installation

JAVA_HOME should be set to E:\Sun\SDK\jdk. PATH should be set to include %JAVA_HOME%\bin.

How does Tomcat locate the webapps directory?

I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/", for example, I kept getting "This localhost page can't be found" in the browser.

I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/" as changing it to appBase="C:/Java Project/ROOT" will cause "This localhost page can't be found" to be displayed again.

Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

I want to declare an empty array in java and then I want do update it but the code is not working

You need to give the array a size:

public static void main(String args[])
{
    int array[] = new int[4];
    int number = 5, i = 0,j = 0;
    while (i<4){
        array[i]=number;
        i=i+1;
    }
    while (j<4){
        System.out.println(array[j]);
        j++;
    }
}

Python: Pandas Dataframe how to multiply entire column with a scalar

The real problem of why you are getting the error is not that there is anything wrong with your code: you can use either iloc, loc, or apply, or *=, another of them could have worked.

The real problem that you have is due to how you created the df DataFrame. Most likely you created your df as a slice of another DataFrame without using .copy(). The correct way to create your df as a slice of another DataFrame is df = original_df.loc[some slicing].copy().

The problem is already stated in the error message you got " SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"
You will get the same message in the most current version of pandas too.

Whenever you receive this kind of error message, you should always check how you created your DataFrame. Chances are you forgot the .copy()

How to get Django and ReactJS to work together?

As others answered you, if you are creating a new project, you can separate frontend and backend and use any django rest plugin to create rest api for your frontend application. This is in the ideal world.

If you have a project with the django templating already in place, then you must load your react dom render in the page you want to load the application. In my case I had already django-pipeline and I just added the browserify extension. (https://github.com/j0hnsmith/django-pipeline-browserify)

As in the example, I loaded the app using django-pipeline:

PIPELINE = {
    # ...
    'javascript':{
        'browserify': {
            'source_filenames' : (
                'js/entry-point.browserify.js',
            ),
            'output_filename': 'js/entry-point.js',
        },
    }
}

Your "entry-point.browserify.js" can be an ES6 file that loads your react app in the template:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app.js';
import "babel-polyfill";

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise';
import reducers from './reducers/index.js';

const createStoreWithMiddleware = applyMiddleware(
  promise
)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App/>
  </Provider>
  , document.getElementById('my-react-app')
);

In your django template, you can now load your app easily:

{% load pipeline %}

{% comment %} 
`browserify` is a PIPELINE key setup in the settings for django 
 pipeline. See the example above
{% endcomment %}

{% javascript 'browserify' %}

{% comment %} 
the app will be loaded here thanks to the entry point you created 
in PIPELINE settings. The key is the `entry-point.browserify.js` 
responsable to inject with ReactDOM.render() you react app in the div 
below
{% endcomment %}
<div id="my-react-app"></div>

The advantage of using django-pipeline is that statics get processed during the collectstatic.

How can I change UIButton title color?

You can use -[UIButton setTitleColor:forState:] to do this.

Example:

Objective-C

[buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

Swift 2

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

Swift 3

buttonName.setTitleColor(UIColor.white, for: .normal)

Thanks to richardchildan

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

import org.junit.Assert
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test

class FeatureTest {
    companion object {
        private lateinit var heavyFeature: HeavyFeature
        @BeforeClass
        @JvmStatic
        fun beforeHeavy() {
            heavyFeature = HeavyFeature()
        }
    }

    private lateinit var feature: Feature

    @Before
    fun before() {
        feature = Feature()
    }

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}

Same as

import org.junit.Assert
import org.junit.Test

 class FeatureTest {
    companion object {
        private val heavyFeature = HeavyFeature()
    }

    private val feature = Feature()

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

I had a similar problem when posting to the WebAPI endpoint. By turning the CustomErrors=Off, i was able to see the actual error which is one of the dlls was missing.

Using prepared statements with JDBCTemplate

class Main {
    public static void main(String args[]) throws Exception {
        ApplicationContext ac = new
          ClassPathXmlApplicationContext("context.xml", Main.class);
        DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String prasobhName = 
        jdbcTemplate.query(
           "select first_name from customer where last_name like ?",
            new PreparedStatementSetter() {
              public void setValues(PreparedStatement preparedStatement) throws
                SQLException {
                  preparedStatement.setString(1, "nair%");
              }
            }, 
            new ResultSetExtractor<Long>() {
              public Long extractData(ResultSet resultSet) throws SQLException,
                DataAccessException {
                  if (resultSet.next()) {
                      return resultSet.getLong(1);
                  }
                  return null;
              }
            }
        );
        System.out.println(machaceksName);
    }
}

How can I put an icon inside a TextInput in React Native?

You can use combination of View, Icon and TextInput like so:

<View style={styles.searchSection}>
    <Icon style={styles.searchIcon} name="ios-search" size={20} color="#000"/>
    <TextInput
        style={styles.input}
        placeholder="User Nickname"
        onChangeText={(searchString) => {this.setState({searchString})}}
        underlineColorAndroid="transparent"
    />
</View>

and use flex-direction for styling

searchSection: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
},
searchIcon: {
    padding: 10,
},
input: {
    flex: 1,
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 10,
    paddingLeft: 0,
    backgroundColor: '#fff',
    color: '#424242',
},

Icons were taken from "react-native-vector-icons"

How to loop through a plain JavaScript object with the objects as members?

In ES7 you can do:

for (const [key, value] of Object.entries(obj)) {
  //
}

Send mail via CMD console

Scenario: Your domain: mydomain.com Domain you wish to send to: theirdomain.com

1. Determine the mail server you're sending to. Open a CMD prompt Type

NSLOOKUP 
 set q=mx 
 theirdomain.com

Response:

Non-authoritative answer: 
theirdomain.com MX preference = 50, mail exchanger = mail.theirdomain.com 
Nslookup_big

EDIT Be sure to type exit to terminate NSLOOKUP.

2. Connect to their mail server

SMTP communicates over port 25. We will now try to use TELNET to connect to their mail server "mail.theirdomain.com"

Open a CMD prompt

TELNET MAIL.THEIRDOMAIN.COM 25

You should see something like this as a response:

220 mx.google.com ESMTP 6si6253627yxg.6

Be aware that different servers will come up with different greetings but you should get SOMETHING. If nothing comes up at this point there are 2 possible problems. Port 25 is being blocked at your firewall, or their server is not responding. Try a different domain, if that works then it's not you.

3. Send an Email

Now, use simple SMTP commands to send a test email. This is very important, you CANNOT use the backspace key, it will work onscreen but not be interpreted correctly. You have to type these commands perfectly.

ehlo mydomain.com 
mail from:<[email protected]> 
rcpt to:<[email protected]> 
data 
This is a test, please do not respond
. 
quit

So, what does that all mean? EHLO - introduce yourself to the mail server HELO can also be used but EHLO tells the server to use the extended command set (not that we're using that).

MAIL FROM - who's sending the email. Make sure to place this is the greater than/less than brackets as many email servers will require this (Postini).

RCPT TO - who you're sending it to. Again you need to use the brackets. See Step #4 on how to test relaying mail!

DATA - tells the SMTP server that what follows is the body of your email. Make sure to hit "Enter" at the end.

. - the period alone on the line tells the SMTP server you're all done with the data portion and it's clear to send the email.

quit - exits the TELNET session.

4. Test SMTP relay Testing SMTP relay is very easy, and simply requires a small change to the above commands. See below:

ehlo mydomain.com 
mail from:<[email protected]> 
rcpt to:<[email protected]> 
data 
This is a test, please do not respond 
. 
quit

See the difference? On the RCPT TO line, we're sending to a domain that is not controlled by the SMTP server we're sending to. You will get an immediate error is SMTP relay is turned off. If you're able to continue and send an email, then relay is allowed by that server.

How to set HTML5 required attribute in Javascript?

required is a reflected property (like id, name, type, and such), so:

element.required = true;

...where element is the actual input DOM element, e.g.:

document.getElementById("edName").required = true;

(Just for completeness.)

Re:

Then the attribute's value is not the empty string, nor the canonical name of the attribute:

edName.attributes.required = [object Attr]

That's because required in that code is an attribute object, not a string; attributes is a NamedNodeMap whose values are Attr objects. To get the value of one of them, you'd look at its value property. But for a boolean attribute, the value isn't relevant; the attribute is either present in the map (true) or not present (false).

So if required weren't reflected, you'd set it by adding the attribute:

element.setAttribute("required", "");

...which is the equivalent of element.required = true. You'd clear it by removing it entirely:

element.removeAttribute("required");

...which is the equivalent of element.required = false.

But we don't have to do that with required, since it's reflected.

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

How to autosize and right-align GridViewColumn data in WPF?

I created a function for updating GridView column headers for a list and call it whenever the window is re-sized or the listview updates it's layout.

public void correctColumnWidths()
{
    double remainingSpace = myList.ActualWidth;

    if (remainingSpace > 0)
    {
         for (int i = 0; i < (myList.View as GridView).Columns.Count; i++)
              if (i != 2)
                   remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth;

          //Leave 15 px free for scrollbar
          remainingSpace -= 15;

          (myList.View as GridView).Columns[2].Width = remainingSpace;
    }
}

How to disable/enable select field using jQuery?

Just simply use:

var update_pizza = function () {
     $("#pizza_kind").prop("disabled", !$('#pizza').prop('checked'));
};

update_pizza();
$("#pizza").change(update_pizza);

DEMO ?

How do I call the base class constructor?

You do this in the initializer-list of the constructor of the subclass.

class Foo : public BaseClass {
public:
    Foo() : BaseClass("asdf") {}
};

Base-class constructors that take arguments have to be called there before any members are initialized.

How do I initialize a TypeScript Object with a JSON-Object?

TLDR: TypedJSON (working proof of concept)


The root of the complexity of this problem is that we need to deserialize JSON at runtime using type information that only exists at compile time. This requires that type-information is somehow made available at runtime.

Fortunately, this can be solved in a very elegant and robust way with decorators and ReflectDecorators:

  1. Use property decorators on properties which are subject to serialization, to record metadata information and store that information somewhere, for example on the class prototype
  2. Feed this metadata information to a recursive initializer (deserializer)

 

Recording Type-Information

With a combination of ReflectDecorators and property decorators, type information can be easily recorded about a property. A rudimentary implementation of this approach would be:

function JsonMember(target: any, propertyKey: string) {
    var metadataFieldKey = "__propertyTypes__";

    // Get the already recorded type-information from target, or create
    // empty object if this is the first property.
    var propertyTypes = target[metadataFieldKey] || (target[metadataFieldKey] = {});

    // Get the constructor reference of the current property.
    // This is provided by TypeScript, built-in (make sure to enable emit
    // decorator metadata).
    propertyTypes[propertyKey] = Reflect.getMetadata("design:type", target, propertyKey);
}

For any given property, the above snippet will add a reference of the constructor function of the property to the hidden __propertyTypes__ property on the class prototype. For example:

class Language {
    @JsonMember // String
    name: string;

    @JsonMember// Number
    level: number;
}

class Person {
    @JsonMember // String
    name: string;

    @JsonMember// Language
    language: Language;
}

And that's it, we have the required type-information at runtime, which can now be processed.

 

Processing Type-Information

We first need to obtain an Object instance using JSON.parse -- after that, we can iterate over the entires in __propertyTypes__ (collected above) and instantiate the required properties accordingly. The type of the root object must be specified, so that the deserializer has a starting-point.

Again, a dead simple implementation of this approach would be:

function deserialize<T>(jsonObject: any, Constructor: { new (): T }): T {
    if (!Constructor || !Constructor.prototype.__propertyTypes__ || !jsonObject || typeof jsonObject !== "object") {
        // No root-type with usable type-information is available.
        return jsonObject;
    }

    // Create an instance of root-type.
    var instance: any = new Constructor();

    // For each property marked with @JsonMember, do...
    Object.keys(Constructor.prototype.__propertyTypes__).forEach(propertyKey => {
        var PropertyType = Constructor.prototype.__propertyTypes__[propertyKey];

        // Deserialize recursively, treat property type as root-type.
        instance[propertyKey] = deserialize(jsonObject[propertyKey], PropertyType);
    });

    return instance;
}
var json = '{ "name": "John Doe", "language": { "name": "en", "level": 5 } }';
var person: Person = deserialize(JSON.parse(json), Person);

The above idea has a big advantage of deserializing by expected types (for complex/object values), instead of what is present in the JSON. If a Person is expected, then it is a Person instance that is created. With some additional security measures in place for primitive types and arrays, this approach can be made secure, that resists any malicious JSON.

 

Edge Cases

However, if you are now happy that the solution is that simple, I have some bad news: there is a vast number of edge cases that need to be taken care of. Only some of which are:

  • Arrays and array elements (especially in nested arrays)
  • Polymorphism
  • Abstract classes and interfaces
  • ...

If you don't want to fiddle around with all of these (I bet you don't), I'd be glad to recommend a working experimental version of a proof-of-concept utilizing this approach, TypedJSON -- which I created to tackle this exact problem, a problem I face myself daily.

Due to how decorators are still being considered experimental, I wouldn't recommend using it for production use, but so far it served me well.

How do you install Boost on MacOS?

Unless your compiler is different than the one supplied with the Mac XCode Dev tools, just follow the instructions in section 5.1 of Getting Started Guide for Unix Variants. The configuration and building of the latest source couldn't be easier, and it took all about about 1 minute to configure and 10 minutes to compile.

How to write log to file

os.Open() must have worked differently in the past, but this works for me:

f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
    log.Fatalf("error opening file: %v", err)
}
defer f.Close()

log.SetOutput(f)
log.Println("This is a test log entry")

Based on the Go docs, os.Open() can't work for log.SetOutput, because it opens the file "for reading:"

func Open

func Open(name string) (file *File, err error) Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

EDIT

Moved defer f.Close() to after if err != nil check

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

It depends with the office you have installed, if you have x64 bit office then you must compile the application as a x64 to allow it to run, so if you want it to run on x36 then you must install office x86 to accept, i tried all the solutions above but none worked until when i realised i had office x64bit and so i built the application as x64 and worked

Table Naming Dilemma: Singular vs. Plural Names

My take is in semantics depending on how you define your container. For example, A "bag of apples" or simply "apples" or an "apple bag" or "apple".

Example: a "college" table can contain 0 or more colleges a table of "colleges" can contain 0 or more collegues

a "student" table can contain 0 or more students 
a table of "students" can contain 0 or more students.

My conclusion is that either is fine but you have to define how you (or people interacting with it) are going to approach when referring to the tables; "a x table" or a "table of xs"

How to distinguish mouse "click" and "drag"

This should work well. Similar to the accepted answer (though using jQuery), but the isDragging flag is only reset if the new mouse position differs from that on mousedown event. Unlike the accepted answer, that works on recent versions of Chrome, where mousemove is fired regardless of whether mouse was moved or not.

var isDragging = false;
var startingPos = [];
$(".selector")
    .mousedown(function (evt) {
        isDragging = false;
        startingPos = [evt.pageX, evt.pageY];
    })
    .mousemove(function (evt) {
        if (!(evt.pageX === startingPos[0] && evt.pageY === startingPos[1])) {
            isDragging = true;
        }
    })
    .mouseup(function () {
        if (isDragging) {
            console.log("Drag");
        } else {
            console.log("Click");
        }
        isDragging = false;
        startingPos = [];
    });

You may also adjust the coordinate check in mousemove if you want to add a little bit of tolerance (i.e. treat tiny movements as clicks, not drags).

Node.js Mongoose.js string to ObjectId function

Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)

_x000D_
_x000D_
...._x000D_
exports.AddSomething = (req,res,next) =>{_x000D_
  const newSomething = new SomeEntity({_x000D_
 _id:new mongoose.Types.ObjectId(), //its very own ID_x000D_
  somethingName:req.body.somethingName,_x000D_
  theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID_x000D_
})_x000D_
}_x000D_
...
_x000D_
_x000D_
_x000D_

Hope it Helps

kubectl apply vs kubectl create?

We love Kubernetes is because once we give them what we want it goes on to figure out how to achieve it without our any involvement.

"create" is like playing GOD by taking things into our own hands. It is good for local debugging when you only want to work with the POD and not care abt Deployment/Replication Controller.

"apply" is playing by the rules. "apply" is like a master tool that helps you create and modify and requires nothing from you to manage the pods.

How to find a parent with a known class in jQuery?

Pass a selector to the jQuery parents function:

d.parents('.a').attr('id')

EDIT Hmm, actually Slaks's answer is superior if you only want the closest ancestor that matches your selector.

How do I fix the npm UNMET PEER DEPENDENCY warning?

One of the most possible causes of this error could be that you have defined older version in your package.json. To solve this problem, change the versions in the package.json to match those npm is complaining about.

Once done, run npm install and voila!!.

Apply jQuery datepicker to multiple instances

I had a similar problem with dynamically adding datepicker classes. The solution I found was to comment out line 46 of datepicker.js

// this.element.on('click', $.proxy(this.show, this));

Nested attributes unpermitted parameters

From the docs

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this

  def question_params

      params.require(:question).permit!

  end

Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.

Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.

Delegates in swift?

The solutions above seemed a little coupled and at the same time avoid reuse the same protocol in other controllers, that's why I've come with the solution that is more strong typed using generic type-erasure.

@noreturn public func notImplemented(){
    fatalError("not implemented yet")
}


public protocol DataChangedProtocol: class{
    typealias DataType

    func onChange(t:DataType)
}

class AbstractDataChangedWrapper<DataType> : DataChangedProtocol{

    func onChange(t: DataType) {
        notImplemented()
    }
}


class AnyDataChangedWrapper<T: DataChangedProtocol> : AbstractDataChangedWrapper<T.DataType>{

    var base: T

    init(_ base: T ){
        self.base = base
    }

    override func onChange(t: T.DataType) {
        base.onChange(t)
    }
}


class AnyDataChangedProtocol<DataType> : DataChangedProtocol{

    var base: AbstractDataChangedWrapper<DataType>

    init<S: DataChangedProtocol where S.DataType == DataType>(_ s: S){
        self.base = AnyDataChangedWrapper(s)
    }

    func onChange(t: DataType) {
        base.onChange(t)
    }
}



class Source : DataChangedProtocol {
    func onChange(data: String) {
        print( "got new value \(data)" )
    }
}


class Target {
    var delegate: AnyDataChangedProtocol<String>?

    func reportChange(data:String ){
        delegate?.onChange(data)
    }
}


var source = Source()
var target = Target()

target.delegate = AnyDataChangedProtocol(source)
target.reportChange("newValue")    

output: got new value newValue

*ngIf else if in template

You can also use this old trick for converting complex if/then/else blocks into a slightly cleaner switch statement:

<div [ngSwitch]="true">
    <button (click)="foo=(++foo%3)+1">Switch!</button>

    <div *ngSwitchCase="foo === 1">one</div>
    <div *ngSwitchCase="foo === 2">two</div>
    <div *ngSwitchCase="foo === 3">three</div>
</div>

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

how to reset <input type = "file">

var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Clearing <input type='file' /> using jQuery

I have used https://github.com/malsup/form/blob/master/jquery.form.js, which has a function called clearInputs(), which is crossbrowser, well tested, easy to use and handles also IE issue and hidden fields clearing if needed. Maybe a little long solution to only clear file input, but if you are dealing with crossbrowser file uploads, then this solution is recommended.

The usage is easy:

// Clear all file fields:
$("input:file").clearInputs();

// Clear also hidden fields:
$("input:file").clearInputs(true);

// Clear specific fields:
$("#myfilefield1,#myfilefield2").clearInputs();
/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
    var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (re.test(t) || tag == 'textarea') {
            this.value = '';
        }
        else if (t == 'checkbox' || t == 'radio') {
            this.checked = false;
        }
        else if (tag == 'select') {
            this.selectedIndex = -1;
        }
        else if (t == "file") {
            if (/MSIE/.test(navigator.userAgent)) {
                $(this).replaceWith($(this).clone(true));
            } else {
                $(this).val('');
            }
        }
        else if (includeHidden) {
            // includeHidden can be the value true, or it can be a selector string
            // indicating a special test; for example:
            //  $('#myForm').clearForm('.special:hidden')
            // the above would clean hidden inputs that have the class of 'special'
            if ( (includeHidden === true && /hidden/.test(t)) ||
                 (typeof includeHidden == 'string' && $(this).is(includeHidden)) )
                this.value = '';
        }
    });
};

Relative frequencies / proportions with dplyr

You can use count() function, which has however a different behaviour depending on the version of dplyr:

  • dplyr 0.7.1: returns an ungrouped table: you need to group again by am

  • dplyr < 0.7.1: returns a grouped table, so no need to group again, although you might want to ungroup() for later manipulations

dplyr 0.7.1

mtcars %>%
  count(am, gear) %>%
  group_by(am) %>%
  mutate(freq = n / sum(n))

dplyr < 0.7.1

mtcars %>%
  count(am, gear) %>%
  mutate(freq = n / sum(n))

This results into a grouped table, if you want to use it for further analysis, it might be useful to remove the grouped attribute with ungroup().

When can I use a forward declaration?

You will usually want to use forward declaration in a classes header file when you want to use the other type (class) as a member of the class. You can not use the forward-declared classes methods in the header file because C++ does not know the definition of that class at that point yet. That's logic you have to move into the .cpp-files, but if you are using template-functions you should reduce them to only the part that uses the template and move that function into the header.

JSON find in JavaScript

If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions is messy and less maintainable than the alternative.

Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:

// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
    db = fdb.db('myTestDatabase'),
    coll;

// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});

// Insert our records into the collection
coll.insert([
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]);

// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
    name: /my nam/i
});

console.log(searchResultArray);

/* Outputs
[
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]
*/

Disclaimer: I am the developer of ForerunnerDB.

Java string to date conversion

Try this

String date = get_pump_data.getString("bond_end_date");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date datee = (Date)format.parse(date);

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

What does ||= (or-equals) mean in Ruby?

Please also remember that ||= isn't an atomic operation and so, it isn't thread safe. As rule of thumb, don't use it for class methods.

You don't have permission to access / on this server

Right click your www folder and click on properties. Navigate to permissions and change all to read and write then click on "Apply permission to enclosed files" and your are done!! Maybe its too late but this will definitely help some other person

Cannot start session without errors in phpMyAdmin

I cleared browser cache. Created session folder as listed in phpinfo.php.

It worked !

How to get data by SqlDataReader.GetValue by column name

You can also do this.

//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName"); 
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);

Cygwin Make bash command not found

You probably have not installed make. Restart the cygwin installer, search for make, select it and it should be installed. By default the cygwin installer does not install everything for what I remember.

Parse time of format hh:mm:ss

As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:

    String myDateString = "13:24:40";
    LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
    int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
    int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
    int second = localTime.get(ChronoField.SECOND_OF_MINUTE);

    //prints "hour: 13, minute: 24, second: 40":
    System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));

Remarks:

  • since the OP's question contains a concrete example of a time instant containing only hours, minutes and seconds (no day, month, etc.), the answer above only uses LocalTime. If wanting to parse a string that also contains days, month, etc. then LocalDateTime would be required. Its usage is pretty much analogous to that of LocalTime.
  • since the time instant int OP's question doesn't contain any information about timezone, the answer uses the LocalXXX version of the date/time classes (LocalTime, LocalDateTime). If the time string that needs to be parsed also contains timezone information, then ZonedDateTime needs to be used.

====== Below is the old (original) answer for this question, using pre-Java8 API: =====

I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.

A SimpleDateFormat might do the trick here:

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

It should be something like:

String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);

Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds

The gotchas you should be aware of:

  • the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this

  • Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.

How do I resolve "Cannot find module" error using Node.js?

Please install the new CLI v3 (npm install -g ionic@latest).

If this issue is still a problem in CLI v3. Thank you!

Using the last-child selector

Why not apply the border to the bottom of the UL?

#refundReasonMenu #nav ul
{
    border-bottom: 1px solid #b5b5b5;
}

How do I join two lists in Java?

public static <T> List<T> merge(List<T>... args) {
    final List<T> result = new ArrayList<>();

    for (List<T> list : args) {
        result.addAll(list);
    }

    return result;
}

Understanding Apache's access log

You seem to be using the combined log format.

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

  • %h is the remote host (ie the client IP)
  • %l is the identity of the user determined by identd (not usually used since not reliable)
  • %u is the user name determined by HTTP authentication
  • %t is the time the request was received.
  • %r is the request line from the client. ("GET / HTTP/1.0")
  • %>s is the status code sent from the server to the client (200, 404 etc.)
  • %b is the size of the response to the client (in bytes)
  • Referer is the Referer header of the HTTP request (containing the URL of the page from which this request was initiated) if any is present, and "-" otherwise.
  • User-agent is the browser identification string.

The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.

Unable to allocate array with shape and data type

change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:

data['label'] = data['label'].astype(np.uint8)

asp.net validation to make sure textbox has integer values

There are several different ways you can handle this. You could add a RequiredFieldValidator as well as a RangeValidator (if that works for your case) or you could add a CustomFieldValidator.

Link to the CustomFieldValidator: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator%28VS.71%29.aspx

Link to MSDN Article on ASP.NET Validation: http://msdn.microsoft.com/en-us/library/aa479045.aspx

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

Quadratic and cubic regression in Excel

You need to use an undocumented trick with Excel's LINEST function:

=LINEST(known_y's, [known_x's], [const], [stats])

Background

A regular linear regression is calculated (with your data) as:

=LINEST(B2:B21,A2:A21)

which returns a single value, the linear slope (m) according to the formula:

enter image description here

which for your data:

enter image description here

is:

enter image description here

Undocumented trick Number 1

You can also use Excel to calculate a regression with a formula that uses an exponent for x different from 1, e.g. x1.2:

enter image description here

using the formula:

=LINEST(B2:B21, A2:A21^1.2)

which for you data:

enter image description here

is:

enter image description here

You're not limited to one exponent

Excel's LINEST function can also calculate multiple regressions, with different exponents on x at the same time, e.g.:

=LINEST(B2:B21,A2:A21^{1,2})

Note: if locale is set to European (decimal symbol ","), then comma should be replaced by semicolon and backslash, i.e. =LINEST(B2:B21;A2:A21^{1\2})

Now Excel will calculate regressions using both x1 and x2 at the same time:

enter image description here

How to actually do it

The impossibly tricky part there's no obvious way to see the other regression values. In order to do that you need to:

  • select the cell that contains your formula:

    enter image description here

  • extend the selection the left 2 spaces (you need the select to be at least 3 cells wide):

    enter image description here

  • press F2

  • press Ctrl+Shift+Enter

    enter image description here

You will now see your 3 regression constants:

  y = -0.01777539x^2 + 6.864151123x + -591.3531443

Bonus Chatter

I had a function that I wanted to perform a regression using some exponent:

y = m×xk + b

But I didn't know the exponent. So I changed the LINEST function to use a cell reference instead:

=LINEST(B2:B21,A2:A21^F3, true, true)

With Excel then outputting full stats (the 4th paramter to LINEST):

enter image description here

I tell the Solver to maximize R2:

enter image description here

And it can figure out the best exponent. Which for you data:

enter image description here

is:

enter image description here

Does Java have an exponential operator?

To do this with user input:

public static void getPow(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first integer: ");    // 3
    int first = sc.nextInt();
    System.out.println("Enter second integer: ");    // 2
    int second = sc.nextInt();
    System.out.println(first + " to the power of " + second + " is " + 
        (int) Math.pow(first, second));    // outputs 9

jQuery Datepicker onchange event issue

if you are using wdcalendar this going to help you

 $("#PatientBirthday").datepicker({ 
        picker: "<button class='calpick'></button>",
        onReturn:function(d){
          var today = new Date();
          var birthDate = d;
          var age = today.getFullYear() - birthDate.getFullYear();
          var m = today.getMonth() - birthDate.getMonth();
          if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
          }

          $('#ageshow')[0].innerHTML="Age: "+age;
          $("#PatientBirthday").val((d.getMonth() + 1) + '/' + d.getDate() + '/' +  d.getFullYear());
        }
      }); 

the event onReturn works for me

hope this help

iOS UIImagePickerController result image orientation after upload

I have experienced this issue with images taken from camera or saved in camera roll which are taken from camera. Images downloaded in photo library from safari browser does not rotate when uploaded.

I was able to solve this issue by making the image data as JPEG before uploading.

let image = info[UIImagePickerControllerOriginalImage] as! UIImage        
let data = UIImageJPEGRepresentation(image, 1.0)

We can now use the data for uploading and the image will not get rotated after upload.

Hope this will work.

What does "javascript:void(0)" mean?

It's worth mentioning that you'll sometimes see void 0 when checking for undefined, simply because it requires fewer characters.

For example:

if (something === undefined) {
    doSomething();
}

Compared to:

if (something === void 0) {
    doSomething();
}

Some minification methods replace undefined with void 0 for this reason.