Programs & Examples On #Episerver 6

EPiServer is an ASP.NET-based CMS (Content Management System).

Inconsistent Accessibility: Parameter type is less accessible than method

After updating my entity framework model, I found this error infecting several files in my solution. I simply right clicked on my .edmx file and my TT file and click "Run Custom Tool" and that had me right again after a restart of Visual Studio 2012.

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

How to save username and password with Mercurial?

There are three ways to do this: use the .hgrc file, use ssh or use the keyring extension


1. The INSECURE way - update your ~/.hgrc file

The format that works for me (in my ~/.hgrc file) is this

[ui]
username=Chris McCauley <[email protected]>

[auth]
repo.prefix = https://server/repo_path
repo.username = username
repo.password = password


You can configure as many repos as you want by adding more triplets of prefix,username, password by prepending a unique tag.

This only works in Mercurial 1.3 and obviously your username and password are in plain text - not good.


2. The secure way - Use SSH to AVOID using passwords

Mercurial fully supports SSH so we can take advantage of SSH's ability to log into a server without a password - you do a once off configuration to provide a self-generated certificate. This is by far the safest way to do what you want.


You can find more information on configuring passwordless login here


3. The keyring Extension

If you want a secure option, but aren't familiar with SSH, why not try this?

From the docs ...

The extension prompts for the HTTP password on the first pull/push to/from given remote repository (just like it is done by default), but saves the password (keyed by the combination of username and remote repository url) in the password database. On the next run it checks for the username in .hg/hgrc, then for suitable password in the password database, and uses those credentials if found.

There is more detailed information here

Disable scrolling when touch moving certain element

To my surprise, the "preventDefault()" method is working for me on latest Google Chrome (version 85) on iOS 13.7. It also works on Safari on the same device and also working on my Android 8.0 tablet. I am currently implemented it for 2D view on my site here: https://papercraft-maker.com

How to post query parameters with Axios?

In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.

        var data = {};

        const params = new URLSearchParams({
          contact: this.ContactPerson,
          phoneNumber: this.PhoneNumber,
          email: this.Email
        }).toString();

        const url =
          "https://test.com/api/UpdateProfile?" +
          params;

        axios
          .post(url, data, {
            headers: {
              aaid: this.ID,
              token: this.Token
            }
          })
          .then(res => {
            this.Info = JSON.parse(res.data);
          })
          .catch(err => {
            console.log(err);
          });

How do I force Postgres to use a particular index?

Sometimes PostgreSQL fails to make the best choice of indexes for a particular condition. As an example, suppose there is a transactions table with several million rows, of which there are several hundred for any given day, and the table has four indexes: transaction_id, client_id, date, and description. You want to run the following query:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description = 'Refund'
GROUP BY client_id

PostgreSQL may choose to use the index transactions_description_idx instead of transactions_date_idx, which may lead to the query taking several minutes instead of less than one second. If this is the case, you can force using the index on date by fudging the condition like this:

SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
      description||'' = 'Refund'
GROUP BY client_id

Removing duplicates from a list of lists

This should work.

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

k_cleaned = []
for ele in k:
    if set(ele) not in [set(x) for x in k_cleaned]:
        k_cleaned.append(ele)
print(k_cleaned)

# output: [[1, 2], [4], [5, 6, 2], [3]]

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

How to wrap text around an image using HTML/CSS

you have to float your image container as follows:

HTML

<div id="container">
    <div id="floated">...some other random text</div>
    ...
    some random text
    ...
</div>

CSS

#container{
    width: 400px;
    background: yellow;
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

FIDDLE

http://jsfiddle.net/kYDgL/

convert HTML ( having Javascript ) to PDF using JavaScript

With Docmosis or JODReports you could feed your HTML and Javascript to the document render process which could produce PDF or doc or other formats. The conversion underneath is performed by OpenOffice so results will be dependent on the OpenOffice import filters. You can try manually by saving your web page to a file, then loading with OpenOffice - if that looks good enough, then these tools will be able to give you the same result as a PDF.

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

How do I call one constructor from another in Java?

The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.

Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.

Setter methods or constructors

Sleep function in ORACLE

You can use the DBMS_ALERT package as follows:

CREATE OR REPLACE FUNCTION sleep(seconds IN NUMBER) RETURN NUMBER
AS
    PRAGMA AUTONOMOUS_TRANSACTION;
    message VARCHAR2(200);
    status  INTEGER;
BEGIN
    DBMS_ALERT.WAITONE('noname', message, status, seconds);
    ROLLBACK;
    RETURN seconds;
END;
SELECT sleep(3) FROM dual;

Join two data frames, select all columns from one and some columns from the other

Not sure if the most efficient way, but this worked for me:

from pyspark.sql.functions import col

df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

The trick is in:

[col('a.'+xx) for xx in a.columns] : all columns in a

[col('b.other1'),col('b.other2')] : some columns of b

How to make link not change color after visited?

If you want to set to a new color or prevent the change of the color of a specific link after visiting it, add inside the tag of that link:

<a style="text-decoration:none; color:#ff0000;" href="link.html">test link</a>

Above the color is #ff0000 but you can make it anything you'd like.

How do I adb pull ALL files of a folder present in SD Card

Yep, just use the trailing slash to recursively pull the directory. Works for me with Nexus 5 and current version of adb (March 2014).

How to set environment variable for everyone under my linux system?

Some interesting excerpts from the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.

So have a look at /etc/profile or /etc/bash.bashrc, these files are the right places for global settings. Put something like this in them to set up an environement variable:

export MY_VAR=xxx

How to append rows to an R data frame

A more generic solution for might be the following.

    extendDf <- function (df, n) {
    withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
    nr          <- nrow (df)
    colNames    <- names(df)
    for (c in 1:length(colNames)) {
        if (is.factor(df[,c])) {
            col         <- vector (mode='character', length = nr+n) 
            col[1:nr]   <- as.character(df[,c])
            col[(nr+1):(n+nr)]<- rep(col[1], n)  # to avoid extra levels
            col         <- as.factor(col)
        } else {
            col         <- vector (mode=mode(df[1,c]), length = nr+n)
            class(col)  <- class (df[1,c])
            col[1:nr]   <- df[,c] 
        }
        if (c==1) {
            newDf       <- data.frame (col ,stringsAsFactors=withFactors)
        } else {
            newDf[,c]   <- col 
        }
    }
    names(newDf) <- colNames
    newDf
}

The function extendDf() extends a data frame with n rows.

As an example:

aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
#      l i n c                   t
# 1  TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00

system.time (eDf <- extendDf (aDf, 100000))
#    user  system elapsed 
#   0.009   0.002   0.010
system.time (eDf <- extendDf (eDf, 100000))
#    user  system elapsed 
#   0.068   0.002   0.070

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

The Request Payload - or to be more precise: payload body of a HTTP Request - is the data normally send by a POST or PUT Request. It's the part after the headers and the CRLF of a HTTP Request.

A request with Content-Type: application/json may look like this:

POST /some-path HTTP/1.1
Content-Type: application/json

{ "foo" : "bar", "name" : "John" }

If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.

If you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data your request may look like this:

POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded

foo=bar&name=John

In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.

So, they differ in the Content-Type but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.

Add error bars to show standard deviation on a plot in R

A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).

You should better use the errbar function from the Hmisc package:

d = data.frame(
  x  = c(1:5)
  , y  = c(1.1, 1.5, 2.9, 3.8, 5.2)
  , sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
)

##install.packages("Hmisc", dependencies=T)
library("Hmisc")

# add error bars (without adjusting yrange)
plot(d$x, d$y, type="n")
with (
  data = d
  , expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
)

# new plot (adjusts Yrange automatically)
with (
  data = d
  , expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
)

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Edit file '/usr/share/phpmyadmin/libraries/sql.lib.php' Replace: (make backup)

"|| (count($analyzed_sql_results['select_expr'] == 1) 
&&($analyzed_sql_results['select_expr'][0] == '*'))) 
&& count($analyzed_sql_results['select_tables']) == 1;"

With:

"|| (count($analyzed_sql_results['select_expr']) == 1) 
&& ($analyzed_sql_results['select_expr'][0] == '*') 
&& (count($analyzed_sql_results['select_tables']) == 1));"

How can I get a Bootstrap column to span multiple rows?

Like the comments suggest, the solution is to use nested spans/rows.

<div class="container">
    <div class="row">
        <div class="span4">1</div>
        <div class="span8">
            <div class="row">
                <div class="span4">2</div>
                <div class="span4">3</div>
            </div>
            <div class="row">
                <div class="span4">4</div>
                <div class="span4">5</div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="span4">6</div>
        <div class="span4">7</div>
        <div class="span4">8</div>
    </div>
</div>

ProgressDialog is deprecated.What is the alternate one to use?

ProgressBar is very simple and easy to use, i am intending to make this same as simple progress dialog. first step is that you can make xml layout of the dialog that you want to show, let say we name this layout

layout_loading_dialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="20dp">
    <ProgressBar
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="4"
        android:gravity="center"
        android:text="Please wait! This may take a moment." />
</LinearLayout>

next step is create AlertDialog which will show this layout with ProgressBar

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false); // if you want user to wait for some process to finish,
builder.setView(R.layout.layout_loading_dialog);
AlertDialog dialog = builder.create();

now all that is left is to show and hide this dialog in our click events like this

dialog.show(); // to show this dialog
dialog.dismiss(); // to hide this dialog

and thats it, it should work, as you can see it is farely simple and easy to implement ProgressBar instead of ProgressDialog. now you can show/dismiss this dialog box in either Handler or ASyncTask, its up to your need

Multiple file upload in php

this simple script worked for me.

<?php

foreach($_FILES as $file){
  //echo $file['name']; 
  echo $file['tmp_name'].'</br>'; 
  move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);
}

?>

Syntax behind sorted(key=lambda: ...)

Simple and not time consuming answer with an example relevant to the question asked Follow this example:

 user = [{"name": "Dough", "age": 55}, 
            {"name": "Ben", "age": 44}, 
            {"name": "Citrus", "age": 33},
            {"name": "Abdullah", "age":22},
            ]
    print(sorted(user, key=lambda el: el["name"]))
    print(sorted(user, key= lambda y: y["age"]))

Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code

print(sorted(user, key=lambda el: el["name"]))

Results to:

[{'name': 'Abdullah', 'age': 22}, 
{'name': 'Ben', 'age': 44}, 
{'name': 'Citrus', 'age': 33}, 
{'name': 'Dough', 'age': 55}]

sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.

The second print code

print(sorted(user, key= lambda y: y["age"]))

Result:

[{'name': 'Abdullah', 'age': 22},
 {'name': 'Citrus', 'age': 33},
 {'name': 'Ben', 'age': 44}, 
 {'name': 'Dough', 'age': 55}]

sorts by age, and hence the list returns by ascending order of age.

Try this code for better understanding.

Beginner Python: AttributeError: 'list' object has no attribute

You need to pass the values of the dict into the Bike constructor before using like that. Or, see the namedtuple -- seems more in line with what you're trying to do.

"Could not find Developer Disk Image"

I am facing the same issue on Xcode 7.3 and my device version is iOS 10.

This error is shown when your Xcode is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.

We can solve this issue by following the below steps:-

  • Open Finder select Applications
  • Right click on Xcode 8, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
  • Copy the 10.0 folder (or above for later version).
  • Back in Finder select Applications again
  • Right click on Xcode 7.3, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
  • Paste the 10.0 folder

If everything worked properly, your Xcode has a new developer disk image. Close the finder now, and quit your Xcode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.

Thanks

HTML.ActionLink method

Use named parameters for readability and to avoid confusions.

@Html.ActionLink(
            linkText: "Click Here",
            actionName: "Action",
            controllerName: "Home",
            routeValues: new { Identity = 2577 },
            htmlAttributes: null)

nvarchar(max) still being truncated

To see the dynamic SQL generated, change to text mode (shortcut: Ctrl-T), then use SELECT

PRINT LEN(@Query) -- Prints out 4273, which is correct as far as I can tell
--SET NOCOUNT ON
SELECT @Query

As for sp_executesql, try this (in text mode), it should show the three aaaaa...'s the middle one being the longest with 'SELECT ..' added. Watch the Ln... Col.. indicator in the status bar at bottom right showing 4510 at the end of the 2nd output.

declare @n nvarchar(max)
set @n = REPLICATE(convert(nvarchar(max), 'a'), 4500)
SET @N = 'SELECT ''' + @n + ''''
print @n   -- up to 4000
select @n  -- up to max
exec sp_Executesql @n

How can I count the number of characters in a Bash variable

Use the wc utility with the print the byte counts (-c) option:

$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
    13

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

How do I put hint in a asp:textbox

 <asp:TextBox runat="server" ID="txtPassword" placeholder="Password">

This will work you might some time feel that it is not working due to Intellisence not showing placeholder

'^M' character at end of lines

In vi, do a :%s/^M//g

To get the ^M hold the CTRL key, press V then M (Both while holding the control key) and the ^M will appear. This will find all occurrences and replace them with nothing.

How to send a POST request from node.js Express?

As described here for a post request :

var http = require('http');

var options = {
  host: 'www.host.com',
  path: '/',
  port: '80',
  method: 'POST'
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();

Python strip() multiple characters?

Because that's not what strip() does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.

You could do:

name= name.replace('(', '').replace(')', '').replace ...

or:

name= ''.join(c for c in name if c not in '(){}<>')

or maybe use a regex:

import re
name= re.sub('[(){}<>]', '', name)

Print Currency Number Format in PHP

try

echo "$".money_format('%i',$price);

output will be

$1.06

Changing iframe src with Javascript

The onselect must be onclick. This will work for keyboard users.

I would also recommend adding <label> tags to the text of "Day", "Month", and "Year" to make them easier to click on. Example code:

<input id="day" name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/><label for="day">Day</label>

I would also recommend removing the spaces between the attribute onclick and the value, although it can be parsed by browsers:

<input name="calendarSelection" type="radio" onclick = "go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day

Should be:

<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day

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

Now with Java EE 7 you can find the resource more easily with

InputStream resource = getServletContext().getResourceAsStream("/WEB-INF/my.json");

https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--

jQuery: print_r() display equivalent?

$.each(myobject, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

This does the work for me. :)

Force drop mysql bypassing foreign key constraint

Simple solution to drop all the table at once from terminal.

This involved few steps inside your mysql shell (not a one step solution though), this worked me and saved my day.

Worked for Server version: 5.6.38 MySQL Community Server (GPL)

Steps I followed:

 1. generate drop query using concat and group_concat.
 2. use database
 3. turn off / disable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 0;), 
 4. copy the query generated from step 1
 5. re enable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 1;)
 6. run show table

MySQL shell

$ mysql -u root -p
Enter password: ****** (your mysql root password)
mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0;                                                                                                                                                   Query OK, 0 rows affected (0.00 sec)

// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)

mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW tables;
Empty set (0.01 sec)

mysql> 

IntelliJ: Working on multiple projects

Since macOS Big Sur and IntelliJ IDEA 2020.3.2 you can use "open projects in tabs on macOS Big Sur" feature. To use it, you have to enable this feature in your system settings:

System Preferences -> General -> Prefer tabs [always] when opening documents

enter image description here

After this step, when you will try to open second project in IntelliJ, choose New Window (yes, New Window, not This Window).

enter image description here

It should result with opening new project in same window, but in the new card:

enter image description here

Angular 4: How to include Bootstrap?

If you want to use bootstrap online and your application has access to the internet you can add

@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.min.css');

Into you'r main style.css file. and its the simplest way.

Reference : angular.io

Note. This solution loads bootstrap from unpkg website and it need to have internet access.

Android Error - Open Failed ENOENT

With sdk, you can't write to the root of internal storage. This cause your error.

Edit :

Based on your code, to use internal storage with sdk:

final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");

Is there a JavaScript / jQuery DOM change listener?

Another approach depending on how you are changing the div. If you are using JQuery to change a div's contents with its html() method, you can extend that method and call a registration function each time you put html into a div.

(function( $, oldHtmlMethod ){
    // Override the core html method in the jQuery object.
    $.fn.html = function(){
        // Execute the original HTML method using the
        // augmented arguments collection.

        var results = oldHtmlMethod.apply( this, arguments );
        com.invisibility.elements.findAndRegisterElements(this);
        return results;

    };
})( jQuery, jQuery.fn.html );

We just intercept the calls to html(), call a registration function with this, which in the context refers to the target element getting new content, then we pass on the call to the original jquery.html() function. Remember to return the results of the original html() method, because JQuery expects it for method chaining.

For more info on method overriding and extension, check out http://www.bennadel.com/blog/2009-Using-Self-Executing-Function-Arguments-To-Override-Core-jQuery-Methods.htm, which is where I cribbed the closure function. Also check out the plugins tutorial at JQuery's site.

How to convert latitude or longitude to meters?

Based on average distance for degress in the Earth.

1° = 111km;

Converting this for radians and dividing for meters, take's a magic number for the RAD, in meters: 0.000008998719243599958;

then:

const RAD = 0.000008998719243599958;
Math.sqrt(Math.pow(lat1 - lat2, 2) + Math.pow(long1 - long2, 2)) / RAD;

How set background drawable programmatically in Android

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
     layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
     layout.setBackground(getResources().getDrawable(R.drawable.ready));
else
     layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

how to count length of the JSON array element

I think you should try

data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};

ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}

Remove characters from C# string

I needed to remove special characters from an XML file. Here's how I did it. char.ToString() is the hero in this code.

string item = "<item type="line" />"
char DC4 = (char)0x14;
string fixed = item.Replace(DC4.ToString(), string.Empty);

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

Does it matter what extension is used for SQLite database files?

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

How can I return the difference between two lists?

If you only want find missing values in b, you can do:

List toReturn = new ArrayList(a);
toReturn.removeAll(b);

return toReturn;

If you want to find out values which are present in either list you can execute upper code twice. With changed lists.

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").

Update

Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

In [2]: df
Out[2]:
   A  B
0  1  4
1  2  5
2  3  6

In [3]: df.to_csv('file.csv', index=None)
File[3]:
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
Out[4]:
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
   B
A
1  4
2  5
3  6

How to get public directory?

The best way to retrieve your public folder path from your Laravel config is the function:

$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);

There is no need to have all the variables, but this is just for a demonstrative purpose.

Hope this helps, GRnGC

Invert colors of an image in CSS or JavaScript

You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

And this is the

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>

Now all you need to do is call invert() We do this when the image is clicked.

_x000D_
_x000D_
function invert(){_x000D_
document.getElementById("theImage").style.filter="invert(100%)";_x000D_
}
_x000D_
<h4> Click image to invert </h4>_x000D_
_x000D_
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>
_x000D_
_x000D_
_x000D_

We use this on our website

Iterator invalidation rules

C++03 (Source: Iterator Invalidation Rules (C++03))


Insertion

Sequence containers

  • vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.2.4.3/1]
  • deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.2.1.3/1]
  • list: all iterators and references unaffected [23.2.2.3/1]

Associative containers

  • [multi]{set,map}: all iterators and references unaffected [23.1.2/8]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence containers

  • vector: every iterator and reference after the point of erase is invalidated [23.2.4.3/3]
  • deque: all iterators and references are invalidated, unless the erased members are at an end (front or back) of the deque (in which case only iterators and references to the erased members are invalidated) [23.2.1.3/4]
  • list: only the iterators and references to the erased element is invalidated [23.2.2.3/3]

Associative containers

  • [multi]{set,map}: only iterators and references to the erased elements are invalidated [23.1.2/8]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Resizing

  • vector: as per insert/erase [23.2.4.2/6]
  • deque: as per insert/erase [23.2.1.2/1]
  • list: as per insert/erase [23.2.2.2/1]

Note 1

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.1/11]

Note 2

It's not clear in C++2003 whether "end" iterators are subject to the above rules; you should assume, anyway, that they are (as this is the case in practice).

Note 3

The rules for invalidation of pointers are the sames as the rules for invalidation of references.

How to search a string in String array

Each class implementing IList has a method Contains(Object value). And so does System.Array.

Remove new lines from string and replace with one empty space

maybe this works:

$str='\n';
echo str_replace('\n','',$str);

How to delete all records from table in sqlite with Android?

You missed a space: db.execSQL("delete * from " + TABLE_NAME);

Also there is no need to even include *, the correct query is:

db.execSQL("delete from "+ TABLE_NAME);

Google Map API v3 — set bounds and center

Yes, you can declare your new bounds object.

 var bounds = new google.maps.LatLngBounds();

Then for each marker, extend your bounds object:

bounds.extend(myLatLng);
map.fitBounds(bounds);

API: google.maps.LatLngBounds

Razor Views not seeing System.Web.Mvc.HtmlHelper

I came across several answers in SO and at the end I realized that my error was that I had misspelled "Html.TextBoxFor." In my case what I wrote was "Html.TextboxFor." I did not uppercase the B in TextBoxFor. Fixed that and voilà. Problem solved. I hope this helps someone.

Finding moving average from data points in Python

A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.

import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)

I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.

How to get a value from a cell of a dataframe?

It doesn't need to be complicated:

val = df.loc[df.wd==1, 'col_name'].values[0]

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Node Express sending image files as API response

There is an api in Express.

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

Order data frame rows according to vector with specific order

Try match:

df <- data.frame(name=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
df[match(target, df$name),]

  name value
2    b  TRUE
3    c FALSE
1    a  TRUE
4    d FALSE

It will work as long as your target contains exactly the same elements as df$name, and neither contain duplicate values.

From ?match:

match returns a vector of the positions of (first) matches of its first argument 
in its second.

Therefore match finds the row numbers that matches target's elements, and then we return df in that order.

How do I get an animated gif to work in WPF?

I couldn't get the most popular answer to this question (above by Dario) to work properly. The result was weird, choppy animation with weird artifacts. Best solution I have found so far: https://github.com/XamlAnimatedGif/WpfAnimatedGif

You can install it with NuGet

PM> Install-Package WpfAnimatedGif

and to use it, at a new namespace to the Window where you want to add the gif image and use it as below

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:gif="http://wpfanimatedgif.codeplex.com" <!-- THIS NAMESPACE -->
    Title="MainWindow" Height="350" Width="525">

<Grid>
    <!-- EXAMPLE USAGE BELOW -->
    <Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" />

The package is really neat, you can set some attributes like below

<Image gif:ImageBehavior.RepeatBehavior="3x"
       gif:ImageBehavior.AnimatedSource="Images/animated.gif" />

and you can use it in your code as well:

var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);

EDIT: Silverlight support

As per josh2112's comment if you want to add animated GIF support to your Silverlight project then use github.com/XamlAnimatedGif/XamlAnimatedGif

How do I increase the contrast of an image in Python OpenCV

I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.

I have done the following using OpenCV 3.0.0 and python:

import cv2

#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img) 

#-----Converting image to LAB Color model----------------------------------- 
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)

#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)

#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)

#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)

#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)

#_____END_____#

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.

strdup() - what does it do in C?

The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)

Better way to find index of item in ArrayList?

the best solution here

class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)

Highlight a word with jQuery

You can use the following function to highlight any word in your text.

function color_word(text_id, word, color) {
    words = $('#' + text_id).text().split(' ');
    words = words.map(function(item) { return item == word ? "<span style='color: " + color + "'>" + word + '</span>' : item });
    new_words = words.join(' ');
    $('#' + text_id).html(new_words);
    }

Simply target the element that contains the text, choosing the word to colorize and the color of choice.

Here is an example:

<div id='my_words'>
This is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.
</div>

Usage,

color_word('my_words', 'possible', 'hotpink')

enter image description here

Understanding repr( ) function in Python

str() is used for creating output for end user while repr() is used for debuggin development.And it's represent the official of object.

Example:

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2018-04-08 18:00:15.178404'
>>> repr(today)
'datetime.datetime(2018, 4, 8, 18, 3, 21, 167886)'

From output we see that repr() shows the official representation of date object.

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

There is a new ISO8601DateFormatter class that let's you create a string with just one line. For backwards compatibility I used an old C-library. I hope this is useful for someone.

Swift 3.0

extension Date {
    var iso8601: String {
        if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
            return ISO8601DateFormatter.string(from: self, timeZone: TimeZone.current, formatOptions: .withInternetDateTime)
        } else {
            var buffer = [CChar](repeating: 0, count: 25)
            var time = time_t(self.timeIntervalSince1970)
            strftime_l(&buffer, buffer.count, "%FT%T%z", localtime(&time), nil)
            return String(cString: buffer)
        }
    }
}

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

In jQuery, how do I get the value of a radio button when they all have the same name?

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

$(function(){
    $("#submit").click(function(){      
        alert($('input:radio:checked').val());
    });
 });

How do I set the visibility of a text box in SSRS using an expression?

This didn't work

=IIf((CountRows("ScannerStatisticsData") = 0),False,True)

but this did and I can't really explain why

=IIf((CountRows("ScannerStatisticsData") < 1),False,True)

guess SSRS doesn't like equal comparisons as much as less than.

How to create a directory and give permission in single command

When the directory already exist:

mkdir -m 777 /path/to/your/dir

When the directory does not exist and you want to create the parent directories:

mkdir -m 777 -p /parent/dirs/to/create/your/dir

JQuery: dynamic height() with window resize()

Okay, how about a CSS answer! We use display: table. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.

http://jsfiddle.net/NfmX3/3/

body { display: table; }
div { display: table-row; }
#content {
    width:450px; 
    margin:0 auto;
    text-align: center;
    background-color: blue;
    color: white;
    height: 100%;
}

Plot inline or a separate window using Matplotlib in Spyder IDE

Magic commands such as

%matplotlib qt  

work in the iPython console and Notebook, but do not work within a script.

In that case, after importing:

from IPython import get_ipython

use:

get_ipython().run_line_magic('matplotlib', 'inline')

for inline plotting of the following code, and

get_ipython().run_line_magic('matplotlib', 'qt')

for plotting in an external window.

Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.

Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.

Finish all activities at a time

The best solution i have found, which is compatible with devices having API level <11

Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);

This solution requires Android support library

Closing a Userform with Unload Me doesn't work

Unload Me only works when its called from userform self. If you want to close a form from another module code (or userform), you need to use the Unload function + userformtoclose name.

I hope its helps

Hibernate openSession() vs getCurrentSession()

If we talk about SessionFactory.openSession()

  • It always creates a new Session object.
  • You need to explicitly flush and close session objects.
  • In single threaded environment it is slower than getCurrentSession().
  • You do not need to configure any property to call this method.

And If we talk about SessionFactory.getCurrentSession()

  • It creates a new Session if not exists, else uses same session which is in current hibernate context.
  • You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.

PostgreSQL ERROR: canceling statement due to conflict with recovery

No need to touch hot_standby_feedback. As others have mentioned, setting it to on can bloat master. Imagine opening transaction on a slave and not closing it.

Instead, set max_standby_archive_delay and max_standby_streaming_delay to some sane value:

# /etc/postgresql/10/main/postgresql.conf on a slave
max_standby_archive_delay = 900s
max_standby_streaming_delay = 900s

This way queries on slaves with a duration less than 900 seconds won't be cancelled. If your workload requires longer queries, just set these options to a higher value.

jQuery load first 3 elements, click "load more" to display next 5 elements

Simple and with little changes. And also hide load more when entire list is loaded.

jsFiddle here.

$(document).ready(function () {
    // Load the first 3 list items from another HTML file
    //$('#myList').load('externalList.html li:lt(3)');
    $('#myList li:lt(3)').show();
    $('#showLess').hide();
    var items =  25;
    var shown =  3;
    $('#loadMore').click(function () {
        $('#showLess').show();
        shown = $('#myList li:visible').size()+5;
        if(shown< items) {$('#myList li:lt('+shown+')').show();}
        else {$('#myList li:lt('+items+')').show();
             $('#loadMore').hide();
             }
    });
    $('#showLess').click(function () {
        $('#myList li').not(':lt(3)').hide();
    });
});

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

If you want to make a change global to the whole notebook:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]

Finding sum of elements in Swift array

A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)

A bit of a different approach here.

Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types

protocol Number 
{
   func +(l: Self, r: Self) -> Self
   func -(l: Self, r: Self) -> Self
   func >(l: Self, r: Self) -> Bool
   func <(l: Self, r: Self) -> Bool
}

extension Double : Number {}
extension Float  : Number {}
extension Int    : Number {}

infix operator += {}

func += <T:Number> (inout left: T, right: T)
{
   left = left + right
}

prefix operator +/ {}

prefix func +/ <T:Number>(ar:[T]?) -> T?
{
    switch true
    {
    case ar == nil:
        return nil

    case ar!.isEmpty:
        return nil

    default:
        var result = ar![0]
        for n in 1..<ar!.count
        {
            result += ar![n]
        }
        return result
   }
}

use like so:

let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
let intarr = [1, 34, 23, 54, 56, -67, 0, 44]

+/nmbrs     // 548.1
+/intarr    // 145

(updated for Swift 2.2, tested in Xcode Version 7.3)

What is the default access modifier in Java?

From a book named OCA Java SE 7 Programmer I:

The members of a class defined without using any explicit access modifier are defined with package accessibility (also called default accessibility). The members with package access are only accessible to classes and interfaces defined in the same package.

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

Concatenate a vector of strings/character

Try using an empty collapse argument within the paste function:

paste(sdata, collapse = '')

Thanks to http://twitter.com/onelinetips/status/7491806343

Difference between webdriver.Dispose(), .Close() and .Quit()

Difference between driver.close() & driver.quit()

driver.close – It closes the the browser window on which the focus is set.

driver.quit – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.

MySQL "incorrect string value" error when save unicode string in Django

If it's a new project, I'd just drop the database, and create a new one with a proper charset:

CREATE DATABASE <dbname> CHARACTER SET utf8;

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

For Windows users:

Set-ExecutionPolicy RemoteSigned -scope CurrentUser
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
scoop install gradle

How to change password using TortoiseSVN?

To change your password for accessing Subversion

Typically this would be handled by your Subversion server administrator. If that's you and you are using the built-in authentication, then edit your [repository]\conf\passwd file on your Subversion server machine.

To delete locally-cached credentials

Follow these steps:

  • Right-click your desktop and select TortoiseSVN->Settings
  • Select Saved Data.
  • Click Clear against Authentication Data.

Next time you attempt an action that requires credentials you'll be asked for them.

If you're using the command-line svn.exe use the --no-auth-cache option so that you can specify alternate credentials without having them cached against your Windows user.

Create Carriage Return in PHP String?

There is also the PHP 5.0.2 PHP_EOL constant that is cross-platform !

Stackoverflow reference

How do I use Maven through a proxy?

If maven works through proxy but not some of the plugins it is invoking, try setting JAVA_TOOL_OPTIONS as well with -Dhttp*.proxy* settings.

If you have already JAVA_OPTS just do

export JAVA_TOOL_OPTIONS=$JAVA_OPTS

SQL INSERT INTO from multiple tables

Here is an short extension for 3 or more tables to the answer of D Stanley:

INSERT INTO other_table (name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table_1 p
INNER JOIN table_2 a ON a.id = p.id
INNER JOIN table_3 b ON b.id = p.id
...
INNER JOIN table_n x ON x.id = p.id

Converting a string to an integer on Android

You can also do it one line:

int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));

Reading from order of execution

  1. grab the view using findViewById(R.id.button1)
  2. use ((Button)______) to cast the View as a Button
  3. Call .GetText() to get the text entry from Button
  4. Call .toString() to convert the Character Varying to a String
  5. Call .ReplaceAll() with "[\\D]" to replace all Non Digit Characters with "" (nothing)
  6. Call Integer.parseInt() grab and return an integer out of the Digit-only string.

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

how to use math.pi in java

Replace

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;

How do I read configuration settings from Symfony2 config.yml?

Like it was saying previously - you can access any parameters by using injection container and use its parameter property.

"Symfony - Working with Container Service Definitions" is a good article about it.

How to set ChartJS Y axis title?

Consider using a the transform: rotate(-90deg) style on an element. See http://www.w3schools.com/cssref/css3_pr_transform.asp

Example, In your css

.verticaltext_content {
  position: relative;
  transform: rotate(-90deg);
  right:90px;   //These three positions need adjusting
  bottom:150px; //based on your actual chart size
  width:200px;
}

Add a space fudge factor to the Y Axis scale so the text has room to render in your javascript.

scaleLabel: "      <%=value%>"

Then in your html after your chart canvas put something like...

<div class="text-center verticaltext_content">Y Axis Label</div>

It is not the most elegant solution, but worked well when I had a few layers between the html and the chart code (using angular-chart and not wanting to change any source code).

how to get GET and POST variables with JQuery?

There's a plugin for jQuery to get GET params called .getUrlParams

For POST the only solution is echoing the POST into a javascript variable using PHP, like Moran suggested.

HTML Image not displaying, while the src url works

My images were not getting displayed even after putting them in the correct folder, problem was they did not have the right permission, I changed the permission to read write execute. I used chmod 777 image.png. All worked then, images were getting displayed. :)

PHP Adding 15 minutes to Time value

You can use below code also.It quite simple.

$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));

How to select between brackets (or quotes or ...) in Vim?

For selecting within single quotes use vi'.

For selecting within parenthesis use vi(.

Can constructors throw exceptions in Java?

Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).

One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream and a FileOutputStream, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.

Why functional languages?

I don't see anyone mentioning the elephant in the room here, so I think it's up to me :)

JavaScript is a functional language. As more and more people do more advanced things with JS, especially leveraging the finer points of jQuery, Dojo, and other frameworks, FP will be introduced by the web-developer's back-door.

In conjunction with closures, FP makes JS code really light, yet still readable.

Cheers, PS

How do you get the magnitude of a vector in Numpy?

If you are worried at all about speed, you should instead use:

mag = np.sqrt(x.dot(x))

Here are some benchmarks:

>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372

EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:

In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop

In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True

How do I print a datetime in the local timezone?

As of python 3.2, using only standard library functions:

u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'

Just need to use l_tm - u_tm or u_tm - l_tm depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.

And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

Use double quote for your password: like - "Abc@%$67eSDu"

C error: undefined reference to function, but it IS defined

I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create, not having point.c will cause the compilation to fail.

I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:

gcc point.c testpoint.c

As others have pointed out, you also need to remove one of your main functions, since you can only have one.

What is the best way to give a C# auto-property an initial value?

You can simple put like this

public sealed  class Employee
{
    public int Id { get; set; } = 101;
}

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

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

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

z-index not working with fixed positioning

When elements are positioned outside the normal flow, they can overlap other elements.

according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp

Angular 2 Date Input not binding to date value

In your component

let today: string;

ngOnInit() {
  this.today = new Date().toISOString().split('T')[0];
}

and in your html file

<input name="date" [(ngModel)]="today" type="date" required>

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

How to iterate over the keys and values with ng-repeat in AngularJS?

If you would like to edit the property value with two way binding:

<tr ng-repeat="(key, value) in data">
    <td>{{key}}<input type="text" ng-model="data[key]"></td>
</tr>

How to read an entire file to a string using C#?

string content = System.IO.File.ReadAllText( @"C:\file.txt" );

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

Getting RSA private key from PEM BASE64 Encoded private key file

Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.

String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
    .replace("-----END RSA PRIVATE KEY-----", "");

// Base64 decode the data

byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);

try {
    ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
        .fromByteArray(encodedPrivateKey);
    Enumeration<?> e = primitive.getObjects();
    BigInteger v = ((DERInteger) e.nextElement()).getValue();

    int version = v.intValue();
    if (version != 0 && version != 1) {
        throw new IllegalArgumentException("wrong version for RSA private key");
    }
    /**
     * In fact only modulus and private exponent are in use.
     */
    BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
    BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();

    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
    throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
    throw new IllegalStateException(e);
}

CSS two div width 50% in one line with line break in file

The problem you run into when setting width to 50% is the rounding of subpixels. If the width of your container is i.e. 99 pixels, a width of 50% can result in 2 containers of 50 pixels each.

Using float is probably easiest, and not such a bad idea. See this question for more details on how to fix the problem then.

If you don't want to use float, try using a width of 49%. This will work cross-browser as far as I know, but is not pixel-perfect..

html:

<div id="a">A</div>
<div id="b">B</div>

css:

#a, #b {
    width: 49%;
    display: inline-block; 
}
#a {background-color: red;}
#b {background-color: blue;}

Display an array in a readable/hierarchical format

echo '<pre>';
foreach($data as $entry){
    foreach($entry as $entry2){
        echo $entry2.'<br />';
    }
}

disable Bootstrap's Collapse open/close animation

Maybe not a direct answer to the question, but a recent addition to the official documentation describes how jQuery can be used to disable transitions entirely just by:

$.support.transition = false

Setting the .collapsing CSS transitions to none as mentioned in the accepted answer removed the animation. But this — in Firefox and Chromium for me — creates an unwanted visual issue on collapse of the navbar.

For instance, visit the Bootstrap navbar example and add the CSS from the accepted answer:

.collapsing {
     -webkit-transition: none;
     transition: none;
}

What I currently see is when the navbar collapses, the bottom border of the navbar momentarily becomes two pixels instead of one, then disconcertingly jumps back to one. Using jQuery, this artifact doesn't appear.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

Replace non-ASCII characters with a single space

Potentially for a different question, but I'm providing my version of @Alvero's answer (using unidecode). I want to do a "regular" strip on my strings, i.e. the beginning and end of my string for whitespace characters, and then replace only other whitespace characters with a "regular" space, i.e.

"Ceñía?mañana????"

to

"Ceñía mañana"

,

def safely_stripped(s: str):
    return ' '.join(
        stripped for stripped in
        (bit.strip() for bit in
         ''.join((c if unidecode(c) else ' ') for c in s).strip().split())
        if stripped)

We first replace all non-unicode spaces with a regular space (and join it back again),

''.join((c if unidecode(c) else ' ') for c in s)

And then we split that again, with python's normal split, and strip each "bit",

(bit.strip() for bit in s.split())

And lastly join those back again, but only if the string passes an if test,

' '.join(stripped for stripped in s if stripped)

And with that, safely_stripped('????Ceñía?mañana????') correctly returns 'Ceñía mañana'.

JavaScript: How to pass object by value?

Not really.

Depending on what you actually need, one possibility may be to set o as the prototype of a new object.

var o = {};
(function(x){
    var obj = Object.create( x );
    obj.foo = 'foo';
    obj.bar = 'bar';
})(o);

alert( o.foo ); // undefined

So any properties you add to obj will be not be added to o. Any properties added to obj with the same property name as a property in o will shadow the o property.

Of course, any properties added to o will be available from obj if they're not shadowed, and all objects that have o in the prototype chain will see the same updates to o.

Also, if obj has a property that references another object, like an Array, you'll need to be sure to shadow that object before adding members to the object, otherwise, those members will be added to obj, and will be shared among all objects that have obj in the prototype chain.

var o = {
    baz: []
};
(function(x){
    var obj = Object.create( x );

    obj.baz.push( 'new value' );

})(o);

alert( o.baz[0] );  // 'new_value'

Here you can see that because you didn't shadow the Array at baz on o with a baz property on obj, the o.baz Array gets modified.

So instead, you'd need to shadow it first:

var o = {
    baz: []
};
(function(x){
    var obj = Object.create( x );

    obj.baz = [];
    obj.baz.push( 'new value' );

})(o);

alert( o.baz[0] );  // undefined

Getting an odd error, SQL Server query using `WITH` clause

;WITH 
    CteProductLookup(ProductId, oid) 
    AS 
...

Why can't I change my input value in React even with the onChange listener

In react, state will not change until you do it by using this.setState({});. That is why your console message showing old values.

How to set NODE_ENV to production/development in OS X

If you using webpack in your application, you can simply set it there, using DefinePlugin...

So in your plugin section, set the NODE_ENV to production:

plugins: [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': '"production"',
  })
]

Django ChoiceField

If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .

Example:

views.py:

def my_view(request, interview_pk):
    interview = Interview.objects.get(pk=interview_pk)
    all_rounds = interview.round_set.order_by('created_at')
    all_round_names = [rnd.name for rnd in all_rounds]
    form = forms.AddRatingForRound(all_round_names)
    return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})

forms.py

class AddRatingForRound(forms.ModelForm):

    def __init__(self, round_list, *args, **kwargs):
        super(AddRatingForRound, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))

    class Meta:
        model = models.RatingSheet
        fields = ('name', )

template:

<form method="post">
    {% csrf_token %}
    {% if interview %}
         {{ interview }}
    {% endif %}
    {% if rounds %}
    <hr>
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    {% else %}
        <h3>No rounds found</h3>
    {% endif %}

</form>

How do you keep parents of floated elements from collapsing?

The ideal solution would be to use inline-block for the columns instead of floating. I think the browser support is pretty good if you follow (a) apply inline-block only to elements that are normally inline (eg span); and (b) add -moz-inline-box for Firefox.

Check your page in FF2 as well because I had a ton of problems when nesting certain elements (surprisingly, this is the one case where IE performs much better than FF).

How to get the connection String from a database

On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

on myServerAddress, write the name of your installed instance (by default it's .\SQLEXPRESS for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.

edit

You will need to omit username and password for windows authentication and add Integrated Security=SSPI.

onChange and onSelect in DropDownList

I bet the onchange is getting fired after the onselect, essentially re-enabling the select.

I'd recommend you implement only the onchange, inspect which option has been selected, and enable or disabled based on that.

To get the value of the selected option use:

document.getElementById("mySelect").options[document.getElementById("mySelect").selectedIndex].value

Which will yield .. nothing since you haven't specified a value for each option .. :(

<select id="mySelect" onChange="enable();">
<option onSelect="disable();" value="no">No</option>
<option onSelect="enable();" value="yes">Yes</option>
</select>

Now it will yield "yes" or "no"

PHP to search within txt file and echo the whole line

one way...

$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];

though it would probably be better to read it line by line with fopen() and fread() and use strpos()

Manually Set Value for FormBuilder Control

If you are using form control then the simplest way to do this:

this.FormName.get('ControlName').setValue(value);

Android studio Gradle build speed up

Definitely makes a difference: How To… Speed up Gradle build time

Just create a file named gradle.properties in the following directory:

/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)

Add this line to the file:

org.gradle.daemon=true

How to compare two tables column by column in oracle

It won't be fast, and there will be a lot for you to type (unless you generate the SQL from user_tab_columns), but here is what I use when I need to compare two tables row-by-row and column-by-column.

The query will return all rows that

  • Exists in table1 but not in table2
  • Exists in table2 but not in table1
  • Exists in both tables, but have at least one column with a different value

(common identical rows will be excluded).

"PK" is the column(s) that make up your primary key. "a" will contain A if the present row exists in table1. "b" will contain B if the present row exists in table2.

select pk
      ,decode(a.rowid, null, null, 'A') as a
      ,decode(b.rowid, null, null, 'B') as b
      ,a.col1, b.col1
      ,a.col2, b.col2
      ,a.col3, b.col3
      ,...
  from table1 a 
  full outer 
  join table2 b using(pk)
 where decode(a.col1, b.col1, 1, 0) = 0
    or decode(a.col2, b.col2, 1, 0) = 0
    or decode(a.col3, b.col3, 1, 0) = 0
    or ...;

Edit Added example code to show the difference described in comment. Whenever one of the values contains NULL, the result will be different.

with a as(
   select 0    as col1 from dual union all
   select 1    as col1 from dual union all
   select null as col1 from dual
)
,b as(
   select 1    as col1 from dual union all
   select 2    as col1 from dual union all
   select null as col1 from dual
)   
select a.col1
      ,b.col1
      ,decode(a.col1, b.col1, 'Same', 'Different') as approach_1
      ,case when a.col1 <> b.col1 then 'Different' else 'Same' end as approach_2       
  from a,b
 order 
    by a.col1
      ,b.col1;    




col1   col1_1   approach_1  approach_2
====   ======   ==========  ==========
  0        1    Different   Different  
  0        2    Different   Different  
  0      null   Different   Same         <--- 
  1        1    Same        Same       
  1        2    Different   Different  
  1      null   Different   Same         <---
null       1    Different   Same         <---
null       2    Different   Same         <---
null     null   Same        Same       

Use Toast inside Fragment

When making a toast in fragment do as following:

Toast.makeText(getActivity(),"Message", Toast.LENGTH_SHORT).show();

When class is extending fragment it is necessary to use getActivity() since fragment is a subclass of activity.

Cheerse

JavaScript string newline character?

printAccountSummary: function()
        {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method

Prints:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.

How can one develop iPhone apps in Java?

There is anew tool called Codename one: One SDK based on JAVA to code in WP8, Android, iOS with all extensive features

Features:

  1. Full Android environment with super fast android simulator
  2. An iPhone/iPad simulator with easy to take iPhone apps to large screen iPad in minutes.
  3. Full support for standard java debugging, profiling for apps on any platform.
  4. Easy themeing / styling – Only a click away

More at Develop Android, iOS iPhone, WP8 apps using Java

Calling jQuery method from onClick attribute in HTML

I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:

function showMessage(msg) {
   alert(msg);
};

<input type="button" value="ahaha" onclick="showMessage('msg');" />

UPDATE: With a small change to how your method is defined I can get it to work:

<html>
<head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script language="javascript">
    // define the function within the global scope
    $.fn.MessageBox = function(msg) {
        alert(msg);
    };

    // or, if you want to encapsulate variables within the plugin
    (function($) {
        $.fn.MessageBoxScoped = function(msg) {
            alert(msg);
        };
    })(jQuery); //<-- make sure you pass jQuery into the $ parameter
 </script>
</head>
<body>
 <div class="Title">Welcome!</div>
 <input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>

Manually raising (throwing) an exception in Python

Read the existing answers first, this is just an addendum.

Notice that you can raise exceptions with or without arguments.

Example:

raise SystemExit

exits the program but you might want to know what happened.So you can use this.

raise SystemExit("program exited")

this will print "program exited" to stderr before closing the program.

PHP case-insensitive in_array function

The above is correct if we assume that arrays can contain only strings, but arrays can contain other arrays as well. Also in_array() function can accept an array for $needle, so strtolower($needle) is not going to work if $needle is an array and array_map('strtolower', $haystack) is not going to work if $haystack contains other arrays, but will result in "PHP warning: strtolower() expects parameter 1 to be string, array given".

Example:

$needle = array('p', 'H');
$haystack = array(array('p', 'H'), 'U');

So i created a helper class with the releveant methods, to make case-sensitive and case-insensitive in_array() checks. I am also using mb_strtolower() instead of strtolower(), so other encodings can be used. Here's the code:

class StringHelper {

public static function toLower($string, $encoding = 'UTF-8')
{
    return mb_strtolower($string, $encoding);
}

/**
 * Digs into all levels of an array and converts all string values to lowercase
 */
public static function arrayToLower($array)
{
    foreach ($array as &$value) {
        switch (true) {
            case is_string($value):
                $value = self::toLower($value);
                break;
            case is_array($value):
                $value = self::arrayToLower($value);
                break;
        }
    }
    return $array;
}

/**
 * Works like the built-in PHP in_array() function — Checks if a value exists in an array, but
 * gives the option to choose how the comparison is done - case-sensitive or case-insensitive
 */
public static function inArray($needle, $haystack, $case = 'case-sensitive', $strict = false)
{
    switch ($case) {
        default:
        case 'case-sensitive':
        case 'cs':
            return in_array($needle, $haystack, $strict);
            break;
        case 'case-insensitive':
        case 'ci':
            if (is_array($needle)) {
                return in_array(self::arrayToLower($needle), self::arrayToLower($haystack), $strict);
            } else {
                return in_array(self::toLower($needle), self::arrayToLower($haystack), $strict);
            }
            break;
    }
}
}

docker error - 'name is already in use by container'

You can remove it with command sudo docker rm YOUR_CONTAINER_ID, then run a new container with sudo docker run ...; or restart an existing container with sudo docker start YOUR_CONTAINER_ID

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

System.Collections.Generic.Dictionary<TKey, TValue> and System.Collections.Hashtable classes both maintain a hash table data structure internally. None of them guarantee preserving the order of items.

Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.

The primary structural difference between them is that Dictionary relies on chaining (maintaining a list of items for each hash table bucket) to resolve collisions whereas Hashtable uses rehashing for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).

There is little benefit to use Hashtable class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by Dictionary<TKey, TValue>.

Are there such things as variables within an Excel formula?

I know it's a little off-topic, but following up with the solution presented by Jonas Bøhmer, actually I think that MOD is the best solution to your example.

If your intention was to limit the result to one digit, MOD is the best approach to achieve it.

ie. Let's suppose that VLOOKUP(A1, B:B, 1, 0) returns 23. Your IF formula would simply make this calculation: 23 - 10 and return 13 as the result.

On the other hand, MOD(VLOOKUP(A1, B:B, 1, 0), 10) would divide 23 by 10 and show the remainder: 3.

Back to the main topic, when I need to use a formula that repeats some part, I usually put it on another cell and then hide it as some people already suggested.

Changing Underline color

You can also use the box-shadow property to simulate an underline.

Here is a fiddle. The idea is to use two layered box shadows to position the line in the same place as an underline.

a.underline {
    text-decoration: none;
    box-shadow: inset 0 -4px 0 0 rgba(255, 255, 255, 1), inset 0 -5px 0 0 rgba(255, 0, 0, 1);
}

How to find all positions of the maximum value in a list?

I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:

=== maxelements.py ===

a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
             35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c

def maxelements_s(seq): # @SilentGhost
    ''' Return list of position(s) of largest element '''
    m = max(seq)
    return [i for i, j in enumerate(seq) if j == m]

def maxelements_m(seq): # @martineau
    ''' Return list of position(s) of largest element '''
    max_indices = []
    if len(seq):
        max_val = seq[0]
        for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
            if val == max_val:
                max_indices.append(i)
            else:
                max_val = val
                max_indices = [i]
    return max_indices

def maxelements_j(seq): # @John Machin
    ''' Return list of position(s) of largest element '''
    if not seq: return []
    max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
    max_indices = []
    for i, val in enumerate(seq):
        if val < max_val: continue
        if val == max_val:
            max_indices.append(i)
        else:
            max_val = val
            max_indices = [i]
    return max_indices

Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:

>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop

>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop

>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop

>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop

>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop

>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop

Use Awk to extract substring

You do not need any external command at all, just use Parameter Expansion in bash:

hostname=aaa0.bbb.ccc
echo ${hostname%%.*}

How should I multiple insert multiple records?

If I were you I would not use either of them.

The disadvantage of the first one is that the parameter names might collide if there are same values in the list.

The disadvantage of the second one is that you are creating command and parameters for each entity.

The best way is to have the command text and parameters constructed once (use Parameters.Add to add the parameters) change their values in the loop and execute the command. That way the statement will be prepared only once. You should also open the connection before you start the loop and close it after it.

Visual Studio Code Automatic Imports

If anyone has run into this issue recently, I found I had to add a setting to use my workspace's version of typescript for the auto-imports to work. To do this, add this line to your workspace settings:

{
  "typescript.tsdk": "./node_modules/typescript/lib"
}

Then, with a typescript file open in vscode, click the typescript version number in the lower right-hand corner. When the options at the top appear, choose "use workspace version", then reload vscode.

Now auto-imports should work.

PHP 7: Missing VCRUNTIME140.dll

I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ filesFrom There yoy can modify MVC

How do I get the current date in Cocoa

CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%2.0f", currentDate.hour, currentDate.minute, currentDate.second];

Mark was right this code is MUCH more efficient to manage dates hours min and secs. But he forgot the @ at the beginning of format string declaration.

How much does it cost to develop an iPhone application?

I am an account exec at a web and mobile development company and hear this question everyday. Unfortunately, iPhone apps are not cheap. You can expect around $100 per hour if you are staying on US soil. I have seen some offshore Indian developers out there for as low as $20 per hour. It all depends on the number and complexity of the functions you wish the app to perform. Simple one function apps are normally around 4-5k. They are so expensive because you are paying a team of people a healthy hourly wage and any type of raw prototyping, development, and coding takes time. Apps can exceed 60-100k pretty easily. Southwest Airlines making an app with a full ecommerce platform that allows you to buy tickets over your phone is an example. All of that porting into their IT is a big job.

And offshoring the project is definitely not always a better option. If you do so you better know who you are dealing with. Do not get me wrong there folks over there who do a bad ass job for a way better deal, but they are not that easy to find. Those guys could fuck around for 5 months on a simple project that would take 6 weeks here, or just not complete it at all and hand it over half finished. I have seen this scenario many times where we finish the work. The project management becomes a challenge. It can be difficult to communicate exactly what you want the app to do.

qmake: could not find a Qt installation of ''

For my Qt 5.7, open QtCreator, go to Tools -> Options -> Build & Run -> Qt Versions gave me the location of qmake.

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

Unsuccessful append to an empty NumPy array

numpy.append always copies the array before appending the new values. Your code is equivalent to the following:

import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)

Perhaps you mean to do this?

import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])

Setting an image for a UIButton in code

Don't worry so much framing the button from code, you can do that on the storyboard. This worked for me, one line...more simple.

[self.button setBackgroundImage:[UIImage imageNamed: @"yourPic.png"] forState:UIControlStateNormal];

The "backspace" escape character '\b': unexpected behavior?

Not too hard to explain... This is like typing hello worl, hitting the left-arrow key twice, typing d, and hitting the down-arrow key.

At least, that is how I infer your terminal is interpeting the \b and \n codes.

Redirect the output to a file and I bet you get something else entirely. Although you may have to look at the file's bytes to see the difference.

[edit]

To elaborate a bit, this printf emits a sequence of bytes: hello worl^H^Hd^J, where ^H is ASCII character #8 and ^J is ASCII character #10. What you see on your screen depends on how your terminal interprets those control codes.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

one of the easy way to do that is use landa function without any problem like

userControl_Material1.simpleButton4.Click += (s, ee) =>
            {
                Save_mat(mat_global);
            };

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

How to remove "Server name" items from history of SQL Server Management Studio

File SqlStudio.bin actually contains binary serialized data of type "Microsoft.SqlServer.Management.UserSettings.SqlStudio".

Using BinaryFormatter class you can write simple .NET application in order to edit file content.

What should every programmer know about security?

Principles to keep in mind if you want your applications to be secure:

  • Never trust any input!
  • Validate input from all untrusted sources - use whitelists not blacklists
  • Plan for security from the start - it's not something you can bolt on at the end
  • Keep it simple - complexity increases the likelihood of security holes
  • Keep your attack surface to a minimum
  • Make sure you fail securely
  • Use defence in depth
  • Adhere to the principle of least privilege
  • Use threat modelling
  • Compartmentalize - so your system is not all or nothing
  • Hiding secrets is hard - and secrets hidden in code won't stay secret for long
  • Don't write your own crypto
  • Using crypto doesn't mean you're secure (attackers will look for a weaker link)
  • Be aware of buffer overflows and how to protect against them

There are some excellent books and articles online about making your applications secure:

Train your developers on application security best pratices

Codebashing (paid)

Security Innovation(paid)

Security Compass (paid)

OWASP WebGoat (free)

CREATE TABLE LIKE A1 as A2

Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

What about:

Create Table New_Users Select * from Old_Users Where 1=2;

and if that doesn't work, just select a row and truncate after creation:

Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;

EDIT:

I noticed your comment below about needing indexes, etc. Try:

show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;

That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:

#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);

Using python map and other functional tools

How about this:

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest(foo, bar):
    print foo, bar

map(maptest, foos, [bars]*len(foos))

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

/etc/mysql$ sudo nano my.cnf

Relevant portion that works for me:

#skip-networking
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            = MY_IP

MY_IP can be found using ifconfig or curl -L whatismyip.org |grep blue.

Restart mysql to ensure the new config is loaded:

/etc/mysql$ sudo service mysql restart

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

Using setTimeout to delay timing of jQuery actions

You can also use jQuery's delay() method instead of setTimeout(). It'll give you much more readable code. Here's an example from the docs:

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout thrusts upon you.

Make an html number input always display 2 decimal places

What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):

HTML

<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">

JS

function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };

How to change the default background color white to something else in twitter bootstrap

You have to override the bootstrap default by being a bit more specific. Try this for a black background:

html body {
    background-color: rgba(0,0,0,1.00);

}

Causes of getting a java.lang.VerifyError

In my case I had to remove this block:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

It was showing error near Fragment.showDialog() method call.

MySQl Error #1064

At first you need to add semi colon (;) after quantity INT NOT NULL) then remove ** from ,genre,quantity)**. to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.

Pass variable to function in jquery AJAX success callback

Just to share a similar problem I had in case it might help some one, I was using:

var NextSlidePage = $("bottomcontent" + Slide + ".html");

to make the variable for the load function, But I should have used:

var NextSlidePage = "bottomcontent" + Slide + ".html";

without the $( )

Don't know why but now it works! Thanks, finally i saw what was going wrong from this post!

HTML image not showing in Gmail

Google only allows images which are coming from trusted source .

So I solved this issue by hosting my images in google drive and using its url as source for my images.

Example: with: http://drive.google.com/uc?export=view&id=FILEID'>

to form URL please refer here.

How can I use Google's Roboto font on a website?

For Website you can use 'Roboto' font as below:

If you have created separate css file then put below line at the top of css file as:

@import url('https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');

Or if you don't want to create separate file then add above line in between <style>...</style>:

<style>
  @import url('https://fonts.googleapis.com/css? 
  family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');
</style>

then:

html, body {
    font-family: 'Roboto', sans-serif;
}

Floating Div Over An Image

Actually just adding margin-bottom: -20px; to the tag class fixed it right up.

http://jsfiddle.net/dChUR/7/

Being block elements, div's naturally have defined borders that they try not to violate. To get them to layer for images, which have no content beside the image because they have no closing tag, you just have to force them to do what they do not want to do, like violate their natural boundaries.

.container {
  border: 1px solid #DDDDDD;
  width: 200px;
  height: 200px;
  }
.tag {
  float: left;
  position: relative;
  left: 0px;
  top: 0px;
  background-color: green;
  z-index: 1000;
  margin-bottom: -20px;
  }

Another toue to take would be to create div's using an image as the background, and then place content where ever you like.

<div id="imgContainer" style="
         background-image: url("foo.jpg"); 
         background-repeat: no-repeat; 
         background-size: cover; 
         -webkit-background-size: cover; 
         -mox-background-size: cover; 
         -o-background-size: cover;">
  <div id="theTag">BLAH BLAH BLAH</div>
</div>

COALESCE Function in TSQL

Here is a simple query containing coalesce -

select * from person where coalesce(addressId, ContactId) is null.

It will return the persons where both addressId and contactId are null.

coalesce function

  • takes least two arguments.
  • arguments must be of integer type.
  • return the first non-null argument.

e.g.

  • coalesce(null, 1, 2, 3) will return 1.
  • coalesce(null, null) will return null.

How can git be installed on CENTOS 5.5?

Just updating this for 2017 and later, as CentOS 5 has reached EOL and the URL for EPEL has changed:

sudo rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo yum install git

This gets you git 1.8.2.3

Git - How to fix "corrupted" interactive rebase?

On Windows, if you are unwilling or unable to restart the machine see below.

Install Process Explorer: https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

In Process Explorer, Find > File Handle or DLL ...

Type in the file name mentioned in the error (for my error it was 'git-rebase-todo' but in the question above, 'done').

Process Explorer will highlight the process holding a lock on the file (for me it was 'grep').

Kill the process and you will be able to abort the git action in the standard way.

How do you use global variables or constant values in Ruby?

Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $ are global, variables with @ are instance variables, @@ means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.

I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:

  1. Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo and create a constant Offset, so then all the classes could access Foo::Offset.

  2. Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

Read entire file in Scala?

Just like in Java, using CommonsIO library:

FileUtils.readFileToString(file, StandardCharsets.UTF_8)

Also, many answers here forget Charset. It's better to always provide it explicitly, or it will hit one day.

How to fill the whole canvas with specific color?

Yes, fill in a Rectangle with a solid color across the canvas, use the height and width of the canvas itself:

_x000D_
_x000D_
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
canvas{ border: 1px solid black; }
_x000D_
<canvas width=300 height=150 id="canvas">
_x000D_
_x000D_
_x000D_

How can I hash a password in Java?

In addition to bcrypt and PBKDF2 mentioned in other answers, I would recommend looking at scrypt

MD5 and SHA-1 are not recommended as they are relatively fast thus using "rent per hour" distributed computing (e.g. EC2) or a modern high end GPU one can "crack" passwords using brute force / dictionary attacks in relatively low costs and reasonable time.

If you must use them, then at least iterate the algorithm a predefined significant amount of times (1000+).

Hibernate Criteria Query to get specific columns

You can use multiselect function for this.

   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }
            

This is supported by hibernate 5. createCriteria is deprecated in further version of hibernate. So you can use criteria builder instead.

Angularjs - ng-cloak/ng-show elements blink

I had a similar issue and found out that if you have a class that contains transitions, the element will blink. I tried to add ng-cloak without success, but by removing the transition the button stopped blinking.

I'm using ionic framework and the button-outline has this transition

.button-outline {
  -webkit-transition: opacity .1s;
  transition: opacity .1s;
}

Simply overwrite the class to remove the transition and the button will stop blinking.

Update

Again on ionic there is a flicker when using ng-show/ng-hide. Adding the following CSS resolves it:

.ng-hide-add,
.ng-hide-remove {
  display: none !important;
}

Source: http://forum.ionicframework.com/t/beta-14-ng-hide-show/14270/9

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

How to find tags with only certain attributes - BeautifulSoup

Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:

from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
    <td width="580" valign="top">.......</td>\
    <td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')

How to get script of SQL Server data?

SQL Server Management Studio

This is your best tool for performing this task. You can generate a script that will build whichever tables you wish from a database as well as insert the data in those tables (as far as I know you have to export all of the data in the selected tables however).

To do this follow these steps:

  1. Right-click on your database and select Tasks > Generate Scripts

  2. In the Generate and Publish Scripts wizard, select the "Select specific database objects" option

  3. Expand the "Tables" tree and select all of the tables you wish to export the scheme and data for, then click Next

  4. In the next screen choose how you wish to save the script (the Output Type must remain set as "Save scripts to a specific location"), then click the Advanced button in the top right corner

  5. In the newly opened window, under the General section is a setting called "Types of data to script", set this to "Scheme and data" and click OK

  6. Click Next, review the export summary and click Next again. This will generate the script to your selected destination.

To restore your database, simply create a new database and change the first line of your generated script to USE [Your.New.Database.Name], then execute. Your new database will now have all of the tables and data you selected from the original database.

HashMap to return default value for non-found keys?

I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:

public static String getString( final JSONObject response, 
                                final String key ) 
{ return getString( response, key, "" ); }  
public static String getString( final JSONObject response, 
                                final String key, final String defVal ) 
{ return response.containsKey( key ) ? (String)response.get( key ) : defVal; }

public static long getLong( final JSONObject response, 
                            final String key ) 
{ return getLong( response, key, 0 ); } 
public static long getLong( final JSONObject response, 
                            final String key, final long defVal ) 
{ return response.containsKey( key ) ? (long)response.get( key ) : defVal; }

public static float getFloat( final JSONObject response, 
                              final String key ) 
{ return getFloat( response, key, 0.0f ); } 
public static float getFloat( final JSONObject response, 
                              final String key, final float defVal ) 
{ return response.containsKey( key ) ? (float)response.get( key ) : defVal; }

public static List<JSONObject> getList( final JSONObject response, 
                                        final String key ) 
{ return getList( response, key, new ArrayList<JSONObject>() ); }   
public static List<JSONObject> getList( final JSONObject response, 
                                        final String key, final List<JSONObject> defVal ) { 
    try { return response.containsKey( key ) ? (List<JSONObject>) response.get( key ) : defVal; }
    catch( ClassCastException e ) { return defVal; }
}   

What is an index in SQL?

INDEXES - to find data easily

UNIQUE INDEX - duplicate values are not allowed

Syntax for INDEX

CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);

Syntax for UNIQUE INDEX

CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);

How do I output coloured text to a Linux terminal?

You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.

Example:

 cout << "\033[1;31mbold red text\033[0m\n";

Here, \033 is the ESC character, ASCII 27. It is followed by [, then zero or more numbers separated by ;, and finally the letter m. The numbers describe the colour and format to switch to from that point onwards.

The codes for foreground and background colours are:

         foreground background
black        30         40
red          31         41
green        32         42
yellow       33         43
blue         34         44
magenta      35         45
cyan         36         46
white        37         47

Additionally, you can use these:

reset             0  (everything back to normal)
bold/bright       1  (often a brighter shade of the same colour)
underline         4
inverse           7  (swap foreground and background colours)
bold/bright off  21
underline off    24
inverse off      27

See the table on Wikipedia for other, less widely supported codes.


To determine whether your terminal supports colour sequences, read the value of the TERM environment variable. It should specify the particular terminal type used (e.g. vt100, gnome-terminal, xterm, screen, ...). Then look that up in the terminfo database; check the colors capability.

How to Use UTF-8 Collation in SQL Server database?

Looks like this will be finally supported in the SQL Server 2019! SQL Server 2019 - whats new?

From BOL:

UTF-8 support

Full support for the widely used UTF-8 character encoding as an import or export encoding, or as database-level or column-level collation for text data. UTF-8 is allowed in the CHAR and VARCHAR datatypes, and is enabled when creating or changing an object’s collation to a collation with the UTF8 suffix.

For example,LATIN1_GENERAL_100_CI_AS_SC to LATIN1_GENERAL_100_CI_AS_SC_UTF8. UTF-8 is only available to Windows collations that support supplementary characters, as introduced in SQL Server 2012. NCHAR and NVARCHAR allow UTF-16 encoding only, and remain unchanged.

This feature may provide significant storage savings, depending on the character set in use. For example, changing an existing column data type with ASCII strings from NCHAR(10) to CHAR(10) using an UTF-8 enabled collation, translates into nearly 50% reduction in storage requirements. This reduction is because NCHAR(10) requires 22 bytes for storage, whereas CHAR(10) requires 12 bytes for the same Unicode string.

2019-05-14 update:

Documentation seems to be updated now and explains our options staring in MSSQL 2019 in section "Collation and Unicode Support".

2019-07-24 update:

Article by Pedro Lopes - Senior Program Manager @ Microsoft about introducing UTF-8 support for Azure SQL Database

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

A simple inline JavaScript confirm would suffice:

<form onsubmit="return confirm('Do you really want to submit the form?');">

No need for an external function unless you are doing validation, which you can do something like this:

<script>
function validate(form) {

    // validation code here ...


    if(!valid) {
        alert('Please correct the errors in the form!');
        return false;
    }
    else {
        return confirm('Do you really want to submit the form?');
    }
}
</script>
<form onsubmit="return validate(this);">

Make an existing Git branch track a remote branch?

In very short

git branch --set-upstream yourLocalBranchName origin/develop

This will make your yourLocalBranchName track the remote branch called develop.

How to verify if a file exists in a batch file?

You can use IF EXIST to check for a file:

IF EXIST "filename" (
  REM Do one thing
) ELSE (
  REM Do another thing
)

If you do not need an "else", you can do something like this:

set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=

Here's a working example of searching for a file or a folder:

REM setup

echo "some text" > filename
mkdir "foldername"

REM finds file    

IF EXIST "filename" (
  ECHO file filename exists
) ELSE (
  ECHO file filename does not exist
)

REM does not find file

IF EXIST "filename2.txt" (
  ECHO file filename2.txt exists
) ELSE (
  ECHO file filename2.txt does not exist
)

REM folders must have a trailing backslash    

REM finds folder

IF EXIST "foldername\" (
  ECHO folder foldername exists
) ELSE (
  ECHO folder foldername does not exist
)

REM does not find folder

IF EXIST "filename\" (
  ECHO folder filename exists
) ELSE (
  ECHO folder filename does not exist
)