Programs & Examples On #Cellspacing

Cellspacing is the amount of space in between the individual table cells.

Html: Difference between cell spacing and cell padding

CellSpacing as the name suggests it is the Space between the Adjacent cells and CellPadding on the other hand means the padding around the cell content.

Adding an item to an associative array

You can simply do this

$data += array($category => $question);

If your're running on php 5.4+

$data += [$category => $question];

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Try using the property ForeColor. Like this :

TextBox1.ForeColor = Color.Red;

how to get right offset of an element? - jQuery

Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).

var offset = $('#whatever').offset();

offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));

Gradle to execute Java class (without modifying build.gradle)

You just need to use the Gradle Application plugin:

apply plugin:'application'
mainClassName = "org.gradle.sample.Main"

And then simply gradle run.

As Teresa points out, you can also configure mainClassName as a system property and run with a command line argument.

How do I use WebRequest to access an SSL encrypted site using https?

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

Creating a new dictionary in Python

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}

How to hide/show div tags using JavaScript?

Set your HTML as

 <div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

     function changeDiv()
      {
      document.getElementById('body').hidden = "hidden"; // hide body div tag
      document.getElementById('body1').hidden = ""; // show body1 div tag
      document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
      // display text if JavaScript worked
       }

Check, it works.

Detecting an "invalid date" Date instance in JavaScript

I've written this function. Pass it a string parameter and it will determine whether it's a valid date or not based on this format "dd/MM/yyyy".

here is a test

input: "hahaha",output: false.

input: "29/2/2000",output: true.

input: "29/2/2001",output: false.

function isValidDate(str) {
    var parts = str.split('/');
    if (parts.length < 3)
        return false;
    else {
        var day = parseInt(parts[0]);
        var month = parseInt(parts[1]);
        var year = parseInt(parts[2]);
        if (isNaN(day) || isNaN(month) || isNaN(year)) {
            return false;
        }
        if (day < 1 || year < 1)
            return false;
        if(month>12||month<1)
            return false;
        if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 31)
            return false;
        if ((month == 4 || month == 6 || month == 9 || month == 11 ) && day > 30)
            return false;
        if (month == 2) {
            if (((year % 4) == 0 && (year % 100) != 0) || ((year % 400) == 0 && (year % 100) == 0)) {
                if (day > 29)
                    return false;
            } else {
                if (day > 28)
                    return false;
            }      
        }
        return true;
    }
}

Windows command to get service status?

Maybe this could be the best way to start a service and check the result

Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:

@ECHO OFF

REM Put whatever your Batch may do before trying to start the service

net start NameOfSercive 2>nul
if errorlevel 2 goto AlreadyRunning
if errorlevel 1 goto Error

REM Put Whatever you want in case Service was not running and start correctly

GOTO ContinueWithBatch

:AlreadyRunning
REM Put Whatever you want in case Service was already running
GOTO ContinueWithBatch

:Error
REM Put Whatever you want in case Service fail to start
GOTO ContinueWithBatch

:ContinueWithBatch

REM Put whatever else your Batch may do

Another thing is to check for its state without changing it, for that there is a much more simple way to do it, just run:

net start

As that, without parameters it will show a list with all services that are started...

So a simple grep or find after it on a pipe would fit...

Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:

@ECHO OFF

REM Put here any code to be run before check for Service

SET TemporalFile=TemporalFile.TXT
NET START | FIND /N "NameOfSercive" > %TemporalFile%
SET CountLines=0
FOR /F %%X IN (%TemporalFile%) DO SET /A CountLines=1+CountLines
IF 0==%CountLines% GOTO ServiceIsNotRunning

REM Put here any code to be run if Service Is Running

GOTO ContinueWithBatch

:ServiceIsNotRunning

REM Put here any code to be run if Service Is Not Running

GOTO ContinueWithBatch
:ContinueWithBatch
DEL -P %TemporalFile% 2>nul
SET TemporalFile=

REM Put here any code to be run after check for Service

Hope this can help!! It is what i normally use.

iterate through a map in javascript

I'd use standard javascript:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

Note the different ways of treating objects and arrays.

How to implement "confirmation" dialog in Jquery UI dialog?

$("ul li a").live('click', function (e) {
            e.preventDefault();

            $('<div></div>').appendTo('body')
                    .html('<div><h6>Are you sure about this?</h6></div>')
                    .dialog({
                        modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
                        width: 'auto', modal: true, resizable: false,
                        buttons: {
                            Confirm: function () {
                                // $(obj).removeAttr('onclick');                                
                                // $(obj).parents('.Parent').remove();

                                $(this).dialog("close");

                                window.location.reload();
                            },
                            No: function () {
                                $(this).dialog("close");
                            }
                        },
                        Cancel: function (event, ui) {
                            $(this).remove();
                        }
                    });

            return false;
        });

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

can you try if.else

> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true"  "false"

> cbind(df1$col)
     [,1]   
[1,] "true" 
[2,] "false"
> cbind(df1$col,col2)
             col2
[1,] "true"  "1" 
[2,] "false" "0" 

How to reload page every 5 seconds?

setTimeout(function () { location.reload(1); }, 5000);

But as development tools go, you are probably better off with https://addons.mozilla.org/en-US/firefox/addon/115

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give each input a name attribute. Only the clicked input's name attribute will be sent to the server.

<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">

And then

<?php
    if (isset($_POST['publish'])) {
        # Publish-button was clicked
    }
    elseif (isset($_POST['save'])) {
        # Save-button was clicked
    }
?>

Edit: Changed value attributes to alt. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]?

Edit: Since this keeps getting upvotes I went ahead and changed the weird alt/value code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image].

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

In my case the solution was that I had mariadb installed, which was aliased to mysql. So all service commands relating to mysql were not recognised... I just needed:

service mariadb start

And for good measure:

chkconfig mariadb on

Android SharedPreferences in Fragment

getActivity() and onAttach() didnot help me in same situation
maybe I did something wrong
but! I found another decision
I have created a field Context thisContext inside my Fragment
And got a current context from method onCreateView
and now I can work with shared pref from fragment

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {   
...   
thisContext = container.getContext();   
...   
}

Passing arguments to "make run"

Not too proud of this, but I didn't want to pass in environment variables so I inverted the way to run a canned command:

run:
    @echo command-you-want

this will print the command you want to run, so just evaluate it in a subshell:

$(make run) args to my command

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5).

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

How to put scroll bar only for modal-body?

A simple js solution to set modal height proportional to body's height :

$(document).ready(function () {
    $('head').append('<style type="text/css">.modal .modal-body {max-height: ' + ($('body').height() * .8) + 'px;overflow-y: auto;}.modal-open .modal{overflow-y: hidden !important;}</style>');
});

body's height has to be 100% :

html, body {
    height: 100%;
    min-height: 100%;
}

I set modal body height to 80% of body, this can be of course customized.

Hope it helps.

Converting Array to List

If you don't want to alter the list:

List<Integer> list = Arrays.asList(array)

But if you want to modify it then you can use this:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(ints));

Or just use java8 like the following:

List<Integer> list = Arrays.stream(ints).collect(Collectors.toList());

Java9 has introduced this method:

List<Integer> list = List.of(ints);

However, this will return an immutable list that you can't add to.

You need to do the following to make it mutable:

List<Integer> list = new ArrayList<Integer>(List.of(ints));

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

How to execute a bash command stored as a string with quotes and asterisk

Have you tried:

eval $cmd

For the follow-on question of how to escape * since it has special meaning when it's naked or in double quoted strings: use single quotes.

MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"

Bonus: It also reads nice: eval mysql query ;-)

Jupyter Notebook not saving: '_xsrf' argument missing from post

Open the developer setting and click console and type the following

JSON.parse(document.getElementById('jupyter-config-data').textContent).token

Then try saving the Notebook. The notebook that was not saving previously will save now.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Binding value to input in Angular JS

Use ng-value for set value of input box after clicking on a button:

"input type="email"  class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"

and

Set Value as:

 $scope.myForm.email2 = $scope.names[0].success;

Android Studio Gradle Configuration with name 'default' not found

I recently encountered this error when I refereneced a project that was initiliazed via a git submodule.

I ended up finding out that the root build.gradle file of the submodule (a java project) did not have the java plugin applied at the root level.

It only had

apply plugin: 'idea'

I added the java plugin:

apply plugin: 'idea'
apply plugin: 'java'

Once I applied the java plugin the 'default not found' message disappeared and the build succeeded.

checking for typeof error in JS

You can use Object.prototype.toString to easily check if an object is an Error, which will work for different frames as well.

function isError(obj){
    return Object.prototype.toString.call(obj) === "[object Error]";
}

_x000D_
_x000D_
function isError(obj){
    return Object.prototype.toString.call(obj) === "[object Error]";
}
console.log("Error:", isError(new Error));
console.log("RangeError:", isError(new RangeError));
console.log("SyntaxError:", isError(new SyntaxError));
console.log("Object:", isError({}));
console.log("Array:", isError([]));
_x000D_
_x000D_
_x000D_

This behavior is guaranteed by the ECMAScript Language Specification.

Object.prototype.toString:

When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

Properties of Error Instances:

Error instances inherit properties from the Error prototype object and their [[Class]] internal property value is "Error". Error instances have no special properties.

Linq select object from list depending on objects attribute

First, Single throws an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if the Correct property is true. Right now, you are checking if a is equal to a.Correct (which will not even compile).

You should use First (which will throw if there are no such elements), or FirstOrDefault (which will return null for a reference type if there isn't such element):

// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct); 

// this will return the first correct answer, 
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct); 

// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();

How can I make a div not larger than its contents?

_x000D_
_x000D_
div{
width:fit-content;
}
_x000D_
<div>
    <table>
    </table>
</div>
_x000D_
_x000D_
_x000D_

Plotting time in Python with Matplotlib

I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.

graph with centered stack of bubbles

I "fixed" the problem by adding another line:

plt.plot([],[])

The entire code snippet becomes:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

This produces an image with the bubbles distributed as desired.

graph with bubbles distributed over time

How do I decode a string with escaped unicode?

I don't have enough rep to put this under comments to the existing answers:

unescape is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent converts a js string to escaped UTF-8 and decodeURIComponent only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // © So you need to know your data when using decodeURIComponent.

decodeURIComponent won't work on "%C2" or any lone byte over 0x7f because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you © Unescape wouldn't work properly on that // © AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.

Change all files and folders permissions of a directory to 644/755

The easiest way is to do:

chmod -R u+rwX,go+rX,go-w /path/to/dir

which basically means:

to change file modes -Recursively by giving:

  • user: read, write and eXecute permissions,
  • group and other users: read and eXecute permissions, but not -write permission.

Please note that X will make a directory executable, but not a file, unless it's already searchable/executable.

+X - make a directory or file searchable/executable by everyone if it is already searchable/executable by anyone.

Please check man chmod for more details.

See also: How to chmod all directories except files (recursively)? at SU

MySQL Trigger - Storing a SELECT in a variable

You can declare local variables in MySQL triggers, with the DECLARE syntax.

Here's an example:

DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
  i SERIAL PRIMARY KEY
);

DELIMITER //
DROP TRIGGER IF EXISTS bar //

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = NEW.i;
  SET @a = x; -- set user variable outside trigger
END//

DELIMITER ;

SET @a = 0;

SELECT @a; -- returns 0

INSERT INTO foo () VALUES ();

SELECT @a; -- returns 1, the value it got during the trigger

When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT age FROM users WHERE name = 'Bill'); 
  -- ERROR 1242 if more than one row with 'Bill'
END//

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
  -- OK even when more than one row with 'Bill'
END//

Is this very likely to create a memory leak in Tomcat?

I added the following to @PreDestroy method in my CDI @ApplicationScoped bean, and when I shutdown TomEE 1.6.0 (tomcat7.0.39, as of today), it clears the thread locals.

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

import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;

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

/**
 *
 * @author Administrator
 * 
 * google-gson issue # 402: Memory Leak in web application; comment # 25
 * https://code.google.com/p/google-gson/issues/detail?id=402
 */
public class ThreadLocalImmolater {

    final Logger logger = LoggerFactory.getLogger(ThreadLocalImmolater.class);

    Boolean debug;

    public ThreadLocalImmolater() {
        debug = true;
    }

    public Integer immolate() {
        int count = 0;
        try {
            final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
            threadLocalsField.setAccessible(true);
            final Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
            inheritableThreadLocalsField.setAccessible(true);
            for (final Thread thread : Thread.getAllStackTraces().keySet()) {
                    count += clear(threadLocalsField.get(thread));
                    count += clear(inheritableThreadLocalsField.get(thread));
            }
            logger.info("immolated " + count + " values in ThreadLocals");
        } catch (Exception e) {
            throw new Error("ThreadLocalImmolater.immolate()", e);
        }
        return count;
    }

    private int clear(final Object threadLocalMap) throws Exception {
        if (threadLocalMap == null)
                return 0;
        int count = 0;
        final Field tableField = threadLocalMap.getClass().getDeclaredField("table");
        tableField.setAccessible(true);
        final Object table = tableField.get(threadLocalMap);
        for (int i = 0, length = Array.getLength(table); i < length; ++i) {
            final Object entry = Array.get(table, i);
            if (entry != null) {
                final Object threadLocal = ((WeakReference)entry).get();
                if (threadLocal != null) {
                    log(i, threadLocal);
                    Array.set(table, i, null);
                    ++count;
                }
            }
        }
        return count;
    }

    private void log(int i, final Object threadLocal) {
        if (!debug) {
            return;
        }
        if (threadLocal.getClass() != null &&
            threadLocal.getClass().getEnclosingClass() != null &&
            threadLocal.getClass().getEnclosingClass().getName() != null) {

            logger.info("threadLocalMap(" + i + "): " +
                        threadLocal.getClass().getEnclosingClass().getName());
        }
        else if (threadLocal.getClass() != null &&
                 threadLocal.getClass().getName() != null) {
            logger.info("threadLocalMap(" + i + "): " + threadLocal.getClass().getName());
        }
        else {
            logger.info("threadLocalMap(" + i + "): cannot identify threadlocal class name");
        }
    }

}

How can you use php in a javascript function

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

Is there a concise way to iterate over a stream with indices in Java 8?

You can create a static inner class to encapsulate the indexer as I needed to do in example below:

static class Indexer {
    int i = 0;
}

public static String getRegex() {
    EnumSet<MeasureUnit> range = EnumSet.allOf(MeasureUnit.class);
    StringBuilder sb = new StringBuilder();
    Indexer indexer = new Indexer();
    range.stream().forEach(
            measureUnit -> {
                sb.append(measureUnit.acronym);
                if (indexer.i < range.size() - 1)
                    sb.append("|");

                indexer.i++;
            }
    );
    return sb.toString();
}

MySQL Workbench not opening on Windows

There are two prerequisite requirements need to install MySql Workbench as follows.

  1. .Net Framework 4.0
  2. Microsoft Visual C++ 2010

When .Net Framework 4.0 does not exist your computer installation will be corrupted. But if Microsoft Visual C++ 2010 does not exist your computer then you will continue the installation but cannot open MySql Workbench program. Sometimes you will need Microsoft Visual C++ 2013 instead of Microsoft Visual C++ 2010. So I recommend to install Microsoft Visual C++ 2013.

Microsoft Visual C++ 2013

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

Passing HTML input value as a JavaScript Function Parameter

You can get the values with use of ID. But ID should be Unique.

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    a = $('#a').val();
    b = $('#b').val();
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

Do I commit the package-lock.json file created by npm 5?

I don't commit this file in my projects. What's the point ?

  1. It's generated
  2. It's the cause of a SHA1 code integrity err in gitlab with gitlab-ci.yml builds

Though it's true that I never use ^ in my package.json for libs because I had bad experiences with it.

JWT (JSON Web Token) automatic prolongation of expiration

Good question- and there is wealth of information in the question itself.

The article Refresh Tokens: When to Use Them and How They Interact with JWTs gives a good idea for this scenario. Some points are:-

  • Refresh tokens carry the information necessary to get a new access token.
  • Refresh tokens can also expire but are rather long-lived.
  • Refresh tokens are usually subject to strict storage requirements to ensure they are not leaked.
  • They can also be blacklisted by the authorization server.

Also take a look at auth0/angular-jwt angularjs

For Web API. read Enable OAuth Refresh Tokens in AngularJS App using ASP .NET Web API 2, and Owin

How to use awk sort by column 3

awk -F "," '{print $0}' user.csv | sort -nk3 -t ','

This should work

Ruby: Calling class method from instance

Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever.

class Foo
    def self.some_class_method
        puts self
    end

    def some_instance_method
        self.class.some_class_method
    end
end

print "Class method: "
Foo.some_class_method

print "Instance method: "
Foo.new.some_instance_method

Outputs:

Class method: Foo
Instance method: Foo

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

$dom->@loadHTML($html);

This is incorrect, use this instead:

@$dom->loadHTML($html);

CSS white space at bottom of page despite having both min-height and height tag

I faced this issue because my web page was zoomed out to 90% and as I was viewing my page in responsive mode through the browser developer tools, I did not notice it right away.

How to get a value from the last inserted row?

Since PostgreSQL JDBC driver version 8.4-701 the PreparedStatement#getGeneratedKeys() is finally fully functional. We use it here almost one year in production to our full satisfaction.

In "plain JDBC" the PreparedStatement needs to be created as follows to make it to return the keys:

statement = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);

You can download the current JDBC driver version here (which is at the moment still 8.4-701).

What command means "do nothing" in a conditional in Bash?

Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.

I try to give a general rule by using the OPs example

do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"

we have to avoid a branch where $a gets more than 10, so $a < 10 as a general condition can be applied to every other, following condition.

In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.

So the OPs example with the rule applied may be restructured as:

if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
    echo "1"
elif [ "$a" -lt 10 ]
then
    echo "2"
fi

Just a variation of the above, enclosing everything in the $a < 10 condition:

if [ "$a" -lt 10 ]
then
    if [ "$a" -le 5 ]
    then
        echo "1"
    else
        echo "2"
    fi
fi

(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)

How to check if a double value has no decimal part

You could simply do

d % 1 == 0

to check if double d is a whole.

Spring Bean Scopes

Detailed explanation for each scope can be found here in Spring bean scopes. Below is the summary

Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype - Scopes a single bean definition to any number of object instances.

request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

SQL Server Case Statement when IS NULL

  case isnull(B.[stat],0)
  when 0 then dateadd(dd,10,(c.[Eventdate]))
  end

you can add in else statement if you want to add 30 days to the same .

Disable autocomplete via CSS

Thanks to @ahhmarr's solution I was able to solve the same problem in my Angular+ui-router environment, which I'll share here for whoever's interested.

In my index.html I've added the following script:

<script type="text/javascript">
    setTimeout(function() {
        $('input').attr('autocomplete', 'off');
    }, 2000);
</script>

Then to cover state changes, I've added the following in my root controller:

$rootScope.$on('$stateChangeStart', function() {
                $timeout(function () {
                    $('input').attr('autocomplete', 'off');
                }, 2000);
            });

The timeouts are for the html to render before applying the jquery.

If you find a better solution please let me know.

How to drop columns by name in a data frame

I changed the code to:

# read data
dat<-read.dta("file.dta")

# vars to delete
var.in<-c("iden", "name", "x_serv", "m_serv")

# what I'm keeping
var.out<-setdiff(names(dat),var.in)

# keep only the ones I want       
dat <- dat[var.out]

Anyway, juba's answer is the best solution to my problem!

Query-string encoding of a Javascript Object

Addition for accepted solution, this works with objects & array of objects:

parseJsonAsQueryString = function (obj, prefix, objName) {
    var str = [];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            var v = obj[p];
            if (typeof v == "object") {
                var k = (objName ? objName + '.' : '') + (prefix ? prefix + "[" + p + "]" : p);
                str.push(parseJsonAsQueryString(v, k));
            } else {
                var k = (objName ? objName + '.' : '') + (prefix ? prefix + '.' + p : p);
                str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
                //str.push(k + "=" + v);
            }
        }
    }
    return str.join("&");
}

Also have added objName if you're using object parameters like in asp.net mvc action methods.

Basic HTTP authentication with Node and Express 4

TL;DR:

? express.basicAuth is gone
? basic-auth-connect is deprecated
? basic-auth doesn't have any logic
? http-auth is an overkill
? express-basic-auth is what you want

More info:

Since you're using Express then you can use the express-basic-auth middleware.

See the docs:

Example:

const app = require('express')();
const basicAuth = require('express-basic-auth');
 
app.use(basicAuth({
    users: { admin: 'supersecret123' },
    challenge: true // <--- needed to actually show the login dialog!
}));

Disable Logback in SpringBoot

Following works for me

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

How to use this boolean in an if statement?

Try this:-

private String getWhoozitYs(){
    StringBuffer sb = new StringBuffer();
    boolean stop = generator.nextBoolean();
    if(stop)
    {
        sb.append("y");
        getWhoozitYs();
    }
    return sb.toString();
}

Instagram how to get my user id from username?

You can do this by using Instagram API ( User Endpoints: /users/search )

how-to in php :

function Request($url) {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt($ch, CURLOPT_HEADER, 0);  

    $result = curl_exec($ch);

    curl_close($ch);

    return $result;

}

function GetUserID($username, $access_token) {

    $url = "https://api.instagram.com/v1/users/search?q=" . $username . "&access_token=" . $access_token;

    if($result = json_decode(Request($url), true)) {

        return $result['data'][0]['id'];

    }

}

// example:
echo GetUserID('rathienth', $access_token);

How to get today's Date?

Use this code to easy get Date & Time :

package date.time;

import java.text.SimpleDateFormat;    
import java.util.Date;

public class DateTime {

    public static void main(String[] args) {
        SimpleDateFormat dnt = new SimpleDateFormat("dd/MM/yy :: HH:mm:ss");
        Date date = new Date();
        System.out.println("Today Date & Time at Now :"+dnt.format(date));  
    } 
}

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

Xpath for href element

This will get you the generic link:

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do')")).Click();

If you want to have it specify a parameter then you will have to test for each one:

...
int i = 1;

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...

The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.

Please excuse if the code is not perfect, I have not tested myself.

How do I connect C# with Postgres?

Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):

In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.

How to read input with multiple lines in Java

Look into BufferedReader. If that isn't general/high-level enough, I recommend reading the I/O tutorial.

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

how to load CSS file into jsp

css href link is incorrect. Use relative path instead:

<link href="../css/loginstyle.css" rel="stylesheet" type="text/css">

CSS Input field text color of inputted text

replace:

input, select, textarea{
    color: #000;
}

with:

input, select, textarea{
    color: #f00;
}

or color: #ff0000;

Send text to specific contact programmatically (whatsapp)

I have done it!

private void openWhatsApp() {
    String smsNumber = "7****"; // E164 format without '+' sign
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
    sendIntent.setPackage("com.whatsapp");
    if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
        Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
        return;    
    }
    startActivity(sendIntent);
}

How to replicate vector in c?

You can use "Gena" library. It closely resembles stl::vector in pure C89.

From the README, it features:

  • Access vector elements just like plain C arrays: vec[k][j];
  • Have multi-dimentional arrays;
  • Copy vectors;
  • Instantiate necessary vector types once in a separate module, instead of doing this every time you needed a vector;
  • You can choose how to pass values into a vector and how to return them from it: by value or by pointer.

You can check it out here:

https://github.com/cher-nov/Gena

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Get query from java.sql.PreparedStatement

I have made a workaround to solve this problem. Visit the below link for more details http://code-outofbox.blogspot.com/2015/07/java-prepared-statement-print-values.html

Solution:

// Initialize connection
PreparedStatement prepStmt = connection.prepareStatement(sql);

PreparedStatementHelper prepHelper = new PreparedStatementHelper(prepStmt);

// User prepHelper.setXXX(indx++, value);
// .....

try {
   Pattern pattern = Pattern.compile("\\?");
   Matcher matcher = pattern.matcher(sql);
   StringBuffer sb = new StringBuffer();
   int indx = 1;  // Parameter begin with index 1
   while (matcher.find()) {
 matcher.appendReplacement(sb, prepHelper.getParameter(indx++));
   }
   matcher.appendTail(sb);
   LOGGER.debug("Executing Query [" + sb.toString() + "] with Database[" + /*db name*/ + "] ...");
   } catch (Exception ex) {
    LOGGER.debug("Executing Query [" + sql + "] with Database[" +  /*db name*/+ "] ...");
}

/****************************************************/

package java.sql;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;

public class PreparedStatementHelper implements PreparedStatement {

 private PreparedStatement prepStmt;
 private String[] values;

 public PreparedStatementHelper(PreparedStatement prepStmt) throws SQLException {
  this.prepStmt = prepStmt;
  this.values = new String[this.prepStmt.getParameterMetaData().getParameterCount()];
 }

 public String getParameter(int index) {
  String value = this.values[index-1];
  return String.valueOf(value);
 }

 private void setParameter(int index, Object value) {
  String valueStr = "";
  if (value instanceof String) {
   valueStr = "'" + String.valueOf(value).replaceAll("'", "''") + "'";
  } else if (value instanceof Integer) {
   valueStr = String.valueOf(value);
  } else if (value instanceof Date || value instanceof Time || value instanceof Timestamp) {
   valueStr = "'" + String.valueOf(value) + "'";
  } else {
   valueStr = String.valueOf(value);
  }
  this.values[index-1] = valueStr;
 }

 @Override
 public ResultSet executeQuery(String sql) throws SQLException {
  return this.prepStmt.executeQuery(sql);
 }

 @Override
 public int executeUpdate(String sql) throws SQLException {
  return this.prepStmt.executeUpdate(sql);
 }

 @Override
 public void close() throws SQLException {
  this.prepStmt.close();

 }

 @Override
 public int getMaxFieldSize() throws SQLException {
  return this.prepStmt.getMaxFieldSize();
 }

 @Override
 public void setMaxFieldSize(int max) throws SQLException {
  this.prepStmt.setMaxFieldSize(max);
 }

 @Override
 public int getMaxRows() throws SQLException {
  return this.prepStmt.getMaxRows();
 }

 @Override
 public void setMaxRows(int max) throws SQLException {
  this.prepStmt.setMaxRows(max);
 }

 @Override
 public void setEscapeProcessing(boolean enable) throws SQLException {
  this.prepStmt.setEscapeProcessing(enable);
 }

 @Override
 public int getQueryTimeout() throws SQLException {
  return this.prepStmt.getQueryTimeout();
 }

 @Override
 public void setQueryTimeout(int seconds) throws SQLException {
  this.prepStmt.setQueryTimeout(seconds);
 }

 @Override
 public void cancel() throws SQLException {
  this.prepStmt.cancel();
 }

 @Override
 public SQLWarning getWarnings() throws SQLException {
  return this.prepStmt.getWarnings();
 }

 @Override
 public void clearWarnings() throws SQLException {
  this.prepStmt.clearWarnings();
 }

 @Override
 public void setCursorName(String name) throws SQLException {
  this.prepStmt.setCursorName(name);
 }

 @Override
 public boolean execute(String sql) throws SQLException {
  return this.prepStmt.execute(sql);
 }

 @Override
 public ResultSet getResultSet() throws SQLException {
  return this.prepStmt.getResultSet();
 }

 @Override
 public int getUpdateCount() throws SQLException {
  return this.prepStmt.getUpdateCount();
 }

 @Override
 public boolean getMoreResults() throws SQLException {
  return this.prepStmt.getMoreResults();
 }

 @Override
 public void setFetchDirection(int direction) throws SQLException {
  this.prepStmt.setFetchDirection(direction);
 }

 @Override
 public int getFetchDirection() throws SQLException {
  return this.prepStmt.getFetchDirection();
 }

 @Override
 public void setFetchSize(int rows) throws SQLException {
  this.prepStmt.setFetchSize(rows);
 }

 @Override
 public int getFetchSize() throws SQLException {
  return this.prepStmt.getFetchSize();
 }

 @Override
 public int getResultSetConcurrency() throws SQLException {
  return this.prepStmt.getResultSetConcurrency();
 }

 @Override
 public int getResultSetType() throws SQLException {
  return this.prepStmt.getResultSetType();
 }

 @Override
 public void addBatch(String sql) throws SQLException {
  this.prepStmt.addBatch(sql);
 }

 @Override
 public void clearBatch() throws SQLException {
  this.prepStmt.clearBatch();
 }

 @Override
 public int[] executeBatch() throws SQLException {
  return this.prepStmt.executeBatch();
 }

 @Override
 public Connection getConnection() throws SQLException {
  return this.prepStmt.getConnection();
 }

 @Override
 public boolean getMoreResults(int current) throws SQLException {
  return this.prepStmt.getMoreResults(current);
 }

 @Override
 public ResultSet getGeneratedKeys() throws SQLException {
  return this.prepStmt.getGeneratedKeys();
 }

 @Override
 public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
  return this.prepStmt.executeUpdate(sql, autoGeneratedKeys);
 }

 @Override
 public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
  return this.prepStmt.executeUpdate(sql, columnIndexes);
 }

 @Override
 public int executeUpdate(String sql, String[] columnNames) throws SQLException {
  return this.prepStmt.executeUpdate(sql, columnNames);
 }

 @Override
 public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
  return this.prepStmt.execute(sql, autoGeneratedKeys);
 }

 @Override
 public boolean execute(String sql, int[] columnIndexes) throws SQLException {
  return this.prepStmt.execute(sql, columnIndexes);
 }

 @Override
 public boolean execute(String sql, String[] columnNames) throws SQLException {
  return this.prepStmt.execute(sql, columnNames);
 }

 @Override
 public int getResultSetHoldability() throws SQLException {
  return this.prepStmt.getResultSetHoldability();
 }

 @Override
 public boolean isClosed() throws SQLException {
  return this.prepStmt.isClosed();
 }

 @Override
 public void setPoolable(boolean poolable) throws SQLException {
  this.prepStmt.setPoolable(poolable);
 }

 @Override
 public boolean isPoolable() throws SQLException {
  return this.prepStmt.isPoolable();
 }

 @Override
 public <T> T unwrap(Class<T> iface) throws SQLException {
  return this.prepStmt.unwrap(iface);
 }

 @Override
 public boolean isWrapperFor(Class<?> iface) throws SQLException {
  return this.prepStmt.isWrapperFor(iface);
 }

 @Override
 public ResultSet executeQuery() throws SQLException {
  return this.prepStmt.executeQuery();
 }

 @Override
 public int executeUpdate() throws SQLException {
  return this.prepStmt.executeUpdate();
 }

 @Override
 public void setNull(int parameterIndex, int sqlType) throws SQLException {
  this.prepStmt.setNull(parameterIndex, sqlType);
  setParameter(parameterIndex, null);
 }

 @Override
 public void setBoolean(int parameterIndex, boolean x) throws SQLException {
  this.prepStmt.setBoolean(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setByte(int parameterIndex, byte x) throws SQLException {
  this.prepStmt.setByte(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setShort(int parameterIndex, short x) throws SQLException {
  this.prepStmt.setShort(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setInt(int parameterIndex, int x) throws SQLException {
  this.prepStmt.setInt(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setLong(int parameterIndex, long x) throws SQLException {
  this.prepStmt.setLong(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setFloat(int parameterIndex, float x) throws SQLException {
  this.prepStmt.setFloat(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setDouble(int parameterIndex, double x) throws SQLException {
  this.prepStmt.setDouble(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
  this.prepStmt.setBigDecimal(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setString(int parameterIndex, String x) throws SQLException {
  this.prepStmt.setString(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBytes(int parameterIndex, byte[] x) throws SQLException {
  this.prepStmt.setBytes(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setDate(int parameterIndex, Date x) throws SQLException {
  this.prepStmt.setDate(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTime(int parameterIndex, Time x) throws SQLException {
  this.prepStmt.setTime(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
  this.prepStmt.setTimestamp(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x, length);
 }

 @SuppressWarnings("deprecation")
 @Override
 public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setUnicodeStream(parameterIndex, x, length);
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x, length);
 }

 @Override
 public void clearParameters() throws SQLException {
  this.prepStmt.clearParameters();
 }

 @Override
 public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x, targetSqlType);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setObject(int parameterIndex, Object x) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public boolean execute() throws SQLException {
  return this.prepStmt.execute();
 }

 @Override
 public void addBatch() throws SQLException {
  this.prepStmt.addBatch();
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader, length);
 }

 @Override
 public void setRef(int parameterIndex, Ref x) throws SQLException {
  this.prepStmt.setRef(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setBlob(int parameterIndex, Blob x) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, x);
 }

 @Override
 public void setClob(int parameterIndex, Clob x) throws SQLException {
  this.prepStmt.setClob(parameterIndex, x);
 }

 @Override
 public void setArray(int parameterIndex, Array x) throws SQLException {
  this.prepStmt.setArray(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public ResultSetMetaData getMetaData() throws SQLException {
  return this.prepStmt.getMetaData();
 }

 @Override
 public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
  this.prepStmt.setDate(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
  this.prepStmt.setTime(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
  this.prepStmt.setTimestamp(parameterIndex, x, cal);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
  this.prepStmt.setNull(parameterIndex, sqlType, typeName);
  setParameter(parameterIndex, null);
 }

 @Override
 public void setURL(int parameterIndex, URL x) throws SQLException {
  this.prepStmt.setURL(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public ParameterMetaData getParameterMetaData() throws SQLException {
  return this.prepStmt.getParameterMetaData();
 }

 @Override
 public void setRowId(int parameterIndex, RowId x) throws SQLException {
  this.prepStmt.setRowId(parameterIndex, x);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setNString(int parameterIndex, String value) throws SQLException {
  this.prepStmt.setNString(parameterIndex, value);
  setParameter(parameterIndex, value);
 }

 @Override
 public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
  this.prepStmt.setNCharacterStream(parameterIndex, value, length);
 }

 @Override
 public void setNClob(int parameterIndex, NClob value) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, value);
 }

 @Override
 public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setClob(parameterIndex, reader, length);
 }

 @Override
 public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, inputStream, length);
 }

 @Override
 public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, reader, length);
 }

 @Override
 public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
  this.prepStmt.setSQLXML(parameterIndex, xmlObject);
  setParameter(parameterIndex, xmlObject);
 }

 @Override
 public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
  this.prepStmt.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
  setParameter(parameterIndex, x);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x, length);
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x, length);
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader, length);
 }

 @Override
 public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
  this.prepStmt.setAsciiStream(parameterIndex, x);
  // TODO Add to tree set
 }

 @Override
 public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
  this.prepStmt.setBinaryStream(parameterIndex, x);
 }

 @Override
 public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setCharacterStream(parameterIndex, reader);
 }

 @Override
 public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
  this.prepStmt.setNCharacterStream(parameterIndex, value);
 }

 @Override
 public void setClob(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setClob(parameterIndex, reader);
  // TODO Add to tree set
 }

 @Override
 public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
  this.prepStmt.setBlob(parameterIndex, inputStream);
 }

 @Override
 public void setNClob(int parameterIndex, Reader reader) throws SQLException {
  this.prepStmt.setNClob(parameterIndex, reader);
 }

}

PHP Array to CSV

Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php

slideToggle JQuery right to left

I know it's been a year since this was asked, but just for people that are going to visit this page I am posting my solution.

By using what @Aldi Unanto suggested here is a more complete answer:

  jQuery('.show_hide').click(function(e) {
    e.preventDefault();
    if (jQuery('.slidingDiv').is(":visible") ) {
      jQuery('.slidingDiv').stop(true,true).hide("slide", { direction: "left" }, 200);
    } else {
      jQuery('.slidingDiv').stop(true,true).show("slide", { direction: "left" }, 200);
    }
  });

First I prevent the link from doing anything on click. Then I add a check if the element is visible or not. When visible I hide it. When hidden I show it. You can change direction to left or right and duration from 200 ms to anything you like.

Edit: I have also added

.stop(true,true)

in order to clearQueue and jumpToEnd. Read about jQuery stop here

Android studio Gradle icon error, Manifest Merger

I had this problem changing the icon from drawable to mipmap.

I only missed the line

tools:replace="android:icon"

in the manifest.

jquery $(window).height() is returning the document height

I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.

How to strip HTML tags with jQuery?

Use the .text() function:

var text = $("<p> example ive got a string</P>").text();

Update: As Brilliand points out below, if the input string does not contain any tags and you are unlucky enough, it might be treated as a CSS selector. So this version is more robust:

var text = $("<div/>").html("<p> example ive got a string</P>").text();

Android new Bottom Navigation bar or BottomNavigationView

I have referred this github post and I have set the three layouts for three fragment pages in bottom tab bar.

FourButtonsActivity.java:

bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
            new BottomBarFragment(LibraryFragment.newInstance(R.layout.library_fragment_layout), R.drawable.ic_update_white_24dp, "Recents"),
            new BottomBarFragment(PhotoEffectFragment.newInstance(R.layout.photo_effect_fragment), R.drawable.ic_local_dining_white_24dp, "Food"),
            new BottomBarFragment(VideoFragment.newInstance(R.layout.video_layout), R.drawable.ic_favorite_white_24dp, "Favorites")

    );

To set the badge count :

  BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(1, "#E91E63", 4);
  unreadMessages.show();
  unreadMessages.setCount(4);
  unreadMessages.setAnimationDuration(200);
  unreadMessages.setAutoShowAfterUnSelection(true);

LibraryFragment.java:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LibraryFragment extends Fragment {
    private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";

    public LibraryFragment() {
    }

    public static LibraryFragment newInstance(int resource) {
        Bundle args = new Bundle();
        args.putInt(STARTING_TEXT, resource);

        LibraryFragment sampleFragment = new LibraryFragment();
        sampleFragment.setArguments(args);

        return sampleFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        View view = LayoutInflater.from(getActivity()).inflate(
                getArguments().getInt(STARTING_TEXT), null);
        return view;


    }

Setting graph figure size

 figure (1)
 hFig = figure(1);
 set(gcf,'PaperPositionMode','auto')
 set(hFig, 'Position', [0 0 xwidth ywidth])
 plot(x,y)
 print -depsc2 correlation.eps;       % for saving in eps, look up options for saving as png or other formats you may need

This saves the figure in the dimensions specified

How do I replace a character in a string in Java?

The simple answer is:

token = token.replace("&", "&amp;");

Despite the name as compared to replaceAll, replace does do a replaceAll, it just doesn't use a regular expression, which seems to be in order here (both from a performance and a good practice perspective - don't use regular expressions by accident as they have special character requirements which you won't be paying attention to).

Sean Bright's answer is probably as good as is worth thinking about from a performance perspective absent some further target requirement on performance and performance testing, if you already know this code is a hot spot for performance, if that is where your question is coming from. It certainly doesn't deserve the downvotes. Just use StringBuilder instead of StringBuffer unless you need the synchronization.

That being said, there is a somewhat deeper potential problem here. Escaping characters is a known problem which lots of libraries out there address. You may want to consider wrapping the data in a CDATA section in the XML, or you may prefer to use an XML library (including the one that comes with the JDK now) to actually generate the XML properly (so that it will handle the encoding).

Apache also has an escaping library as part of Commons Lang.

boto3 client NoRegionError: You must specify a region error only sometimes

One way or another you must tell boto3 in which region you wish the kms client to be created. This could be done explicitly using the region_name parameter as in:

kms = boto3.client('kms', region_name='us-west-2')

or you can have a default region associated with your profile in your ~/.aws/config file as in:

[default]
region=us-west-2

or you can use an environment variable as in:

export AWS_DEFAULT_REGION=us-west-2

but you do need to tell boto3 which region to use.

How do you fix the "element not interactable" exception?

For those discovering this now and the above answers didn't work, the issue I had was the screen wasn't big enough. I added this when initializing my ChromeDriver, and it fixed the problem:

options.add_argument("window-size=1200x600")

Why would a JavaScript variable start with a dollar sign?

${varname} is just a naming convention jQuery developers use to distinguish variables that are holding jQuery elements.

Plain {varname} is used to store general stuffs like texts and strings. ${varname} holds elements returned from jQuery.

You can use plain {varname} to store jQuery elements as well, but as I said in the beginning this distinguishes it from the plain variables and makes it much easier to understand (imagine confusing it for a plain variable and searching all over to understand what it holds).

For example :

var $blah = $(this).parents('.blahblah');

Here, blah is storing a returned jQuery element.

So, when someone else see the $blah in the code, they'll understand it's not just a string or a number, it's a jQuery element.

Call a Vue.js component method from outside the component

Say you have a child_method() in the child component:

export default {
    methods: {
        child_method () {
            console.log('I got clicked')
        }
    }
}

Now you want to execute the child_method from parent component:

<template>
    <div>
        <button @click="exec">Execute child component</button>
        <child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
    </div>
</template>

export default {
    methods: {
        exec () { //accessing the child component instance through $refs
            this.$refs.child.child_method() //execute the method belongs to the child component
        }
    }
}

If you want to execute a parent component method from child component:

this.$parent.name_of_method()

NOTE: It is not recommended to access the child and parent component like this.

Instead as best practice use Props & Events for parent-child communication.

If you want communication between components surely use vuex or event bus

Please read this very helpful article


'git' is not recognized as an internal or external command

  1. Search for GitHubDesktop\app-2.5.0\resources\app\git\cmd
  2. Open the File
  3. Copy File location.
  4. Search for environment.
  5. open edit system environment variable.
  6. open Environment Variables.
  7. on user variable double-click on Path.
  8. click on new
  9. past
  10. OK
  11. Open path on system variables.
  12. New, past the add \ (backslash), then OK
  13. Search for GitHubDesktop\app-2.5.0\resources\app\git\usr\bin\ 14 Copy the Address again and repeat pasting from step 4 to 12.

Close Bootstrap modal on form submit

give id to submit button

<button id="btnSave" type="submit" class="btn btn-success"><i class="glyphicon glyphicon-trash"></i> Save</button>

$('#btnSave').click(function() {
   $('#StudentModal').modal('hide');
});

Also you forgot to close last div.

</div>

Hope this helps.

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

Set font-weight using Bootstrap classes

You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;

you can find all the documentation at http://getbootstrap.com/css.

How to open the Chrome Developer Tools in a new window?

As of Chrome 52, the UI has changed. When the Developer Tools dialog is open, you select the vertical ellipsis and can then choose the docking position:

enter image description here

Select the icon on the left to open the Chrome Developer Tools in a new window: multiple windows icon


Previously

Click and hold the button next to the close button of the Developer Tool in order to reveal the "Undock into separate window" option.

enter image description here

Note: A "press" is not enough in that state.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

Here is a pretty simple stored procedure that does the trick as well...

    CREATE PROCEDURE GetBCPTable
    @table_name varchar(200)
AS
BEGIN
    DECLARE @raw_sql nvarchar(3000)

    DECLARE @columnHeader VARCHAR(8000)
    SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

    DECLARE @ColumnList VARCHAR(8000)
    SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+ 'CAST('+column_name +' AS VARCHAR)' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

    SELECT @raw_sql = 'SELECT '+ @columnHeader +' UNION ALL SELECT ' + @ColumnList + ' FROM ' + @table_name
    --PRINT @raw_SQL
    EXECUTE sp_executesql  @raw_sql
END
GO

How to refresh a Page using react-route Link

Try like this.

You must give a function as value to onClick()

You button:

<button type="button" onClick={ refreshPage }> <span>Reload</span> </button> 

refreshPage function:

function refreshPage(){ 
    window.location.reload(); 
}

Convert time in HH:MM:SS format to seconds only?

Try this:

$time = "21:30:10";
$timeArr = array_reverse(explode(":", $time));
$seconds = 0;
foreach ($timeArr as $key => $value)
{
    if ($key > 2) break;
    $seconds += pow(60, $key) * $value;
}
echo $seconds;

Incorrect integer value: '' for column 'id' at row 1

This is because your data sending column type is integer and your are sending a string value to it.

So, the following way worked for me. Try with this one.

$insertQuery = "INSERT INTO workorders VALUES (
                    null,
                    '$priority',
                    '$requestType',
                    '$purchaseOrder',
                    '$nte',
                    '$jobSiteNumber'
                )";

Don't use 'null'. use it as null without single quotes.

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

Vim: insert the same characters across multiple lines

An alternative that can be more flexible:

Example: To enter the text XYZ at the beginning of the line

:%norm IXYZ

What's happening here?

  • % == Execute on every line
  • norm == Execute the following keys in normal mode
  • I == Insert at beginning of line
  • XYZ == The text you want to enter

Then you hit Enter, and it executes.

Specific to your request:

:%norm Ivendor_

You can also choose a particular range:

:2,4norm Ivendor_

Or execute over a selected visual range:

:'<,'>norm Ivendor_

Integer to IP Address - C

Here's a simple method to do it: The (ip >> 8), (ip >> 16) and (ip >> 24) moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF isolates the least significant byte at each step.

void print_ip(unsigned int ip)
{
    unsigned char bytes[4];
    bytes[0] = ip & 0xFF;
    bytes[1] = (ip >> 8) & 0xFF;
    bytes[2] = (ip >> 16) & 0xFF;
    bytes[3] = (ip >> 24) & 0xFF;   
    printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);        
}

There is an implied bytes[0] = (ip >> 0) & 0xFF; at the first step.

Use snprintf() to print it to a string.

urlencoded Forward slash is breaking URL

Use a different character and replace the slashes server side

e.g. Drupal.org uses %21 (the excalamation mark character !) to represent the slash in a url parameter.

Both of the links below work:

https://api.drupal.org/api/drupal/includes%21common.inc/7

https://api.drupal.org/api/drupal/includes!common.inc/7

If you're worried that the character may clash with a character in the parameter then use a combination of characters.

So your url would be http://project_name/browse_by_exam/type/tutor_search/keyword/one_-!two/new_search/1/search_exam/0/search_subject/0

change it out with js and convert it back to a slash server side.

How to get the last character of a string in a shell?

I know this is a very old thread, but no one mentioned which to me is the cleanest answer:

echo -n $str | tail -c 1

Note the -n is just so the echo doesn't include a newline at the end.

Why doesn't java.util.Set have get(int index)?

Actually this is a recurring question when writing JavaEE applications which use Object-Relational Mapping (for example with Hibernate); and from all the people who replied here, Andreas Petersson is the only one who understood the real issue and offered the correct answer to it: Java is missing a UniqueList! (or you can also call it OrderedSet, or IndexedSet).

Maxwing mentioned this use-case (in which you need ordered AND unique data) and he suggested the SortedSet, but this is not what Marty Pitt really needed.

This "IndexedSet" is NOT the same as a SortedSet - in a SortedSet the elements are sorted by using a Comparator (or using their "natural" ordering).

But instead it is closer to a LinkedHashSet (which others also suggested), or even more so to an (also inexistent) "ArrayListSet", because it guarantees that the elements are returned in the same order as they were inserted.

But the LinkedHashSet is an implementation, not an interface! What is needed is an IndexedSet (or ListSet, or OrderedSet, or UniqueList) interface! This will allow the programmer to specify that he needs a collection of elements that have a specific order and without duplicates, and then instantiate it with any implementation (for example an implementation provided by Hibernate).

Since JDK is open-source, maybe this interface will be finally included in Java 7...

How to get the pure text without HTML element using JavaScript?

function get_content(){
 var returnInnerHTML = document.getElementById('A').innerHTML + document.getElementById('B').innerHTML + document.getElementById('A').innerHTML;
 document.getElementById('txt').innerHTML = returnInnerHTML;
}

That should do it.

Advantages of std::for_each over for loop

With C++11 and two simple templates, you can write

        for ( auto x: range(v1+4,v1+6) ) {
                x*=2;
                cout<< x <<' ';
        }

as a replacement for for_each or a loop. Why choose it boils down to brevity and safety, there's no chance of error in an expression that's not there.

For me, for_each was always better on the same grounds when the loop body is already a functor, and I'll take any advantage I can get.

You still use the three-expression for, but now when you see one you know there's something to understand there, it's not boilerplate. I hate boilerplate. I resent its existence. It's not real code, there's nothing to learn by reading it, it's just one more thing that needs checking. The mental effort can be measured by how easy it is to get rusty at checking it.

The templates are

template<typename iter>
struct range_ { 
                iter begin() {return __beg;}    iter end(){return __end;}
            range_(iter const&beg,iter const&end) : __beg(beg),__end(end) {}
            iter __beg, __end;
};

template<typename iter>
range_<iter> range(iter const &begin, iter const &end)
    { return range_<iter>(begin,end); }

Redirecting to previous page after login? PHP

You should probably place the url to redirect to in a POST variable.

What is dtype('O'), in pandas?

'O' stands for object.

#Loading a csv file as a dataframe
import pandas as pd 
train_df = pd.read_csv('train.csv')
col_name = 'Name of Employee'

#Checking the datatype of column name
train_df[col_name].dtype

#Instead try printing the same thing
print train_df[col_name].dtype

The first line returns: dtype('O')

The line with the print statement returns the following: object

How to execute a Windows command on a remote PC?

You can use native win command:

WMIC /node:ComputerName process call create “cmd.exe /c start.exe”

The WMIC is part of wbem win folder: C:\Windows\System32\wbem

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

How to check the version of scipy

Using command line:

python -c "import scipy; print(scipy.__version__)"

How do I connect to a MySQL Database in Python?

SqlAlchemy


SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

Installation

pip install sqlalchemy

RAW query

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()

ORM way

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
width: 100%;
height: 30vh;
object-fit: contain;
}

Contain will help in getting Complete Image displayed inside Card.

Adjust height "30vh" according to your need!

ETag vs Header Expires

Etag and Last-modified headers are validators.

They help the browser and/or the cache (reverse proxy) to understand if a file/page, has changed, even if it preserves the same name.

Expires and Cache-control are giving refresh information.

This means that they inform, the browser and the reverse in-between proxies, up to what time or for how long, they may keep the page/file at their cache.

So the question usually is which one validator to use, etag or last-modified, and which refresh infomation header to use, expires or cache-control.

Return in Scala

It's not as simple as just omitting the return keyword. In Scala, if there is no return then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.

An example:

def f() = {
  if (something)
    "A"
  else
    "B"
}

Here the last expression of the function f is an if/else expression that evaluates to a String. Since there is no explicit return marked, Scala will infer that you wanted to return the result of this if/else expression: a String.

Now, if we add something after the if/else expression:

def f() = {
  if (something)
    "A"
  else
    "B"

  if (somethingElse)
    1
  else
    2
}

Now the last expression is an if/else expression that evaluates to an Int. So the return type of f will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.

Finally, we can avoid the return keyword even with a nested if-else expression like yours:

def f() = {
  if(somethingFirst) {
    if (something)      // Last expression of `if` returns a String
     "A"
    else
     "B"
  }
  else {
    if (somethingElse)
      1
    else
      2

    "C"                // Last expression of `else` returns a String
  }

}

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

As you've already identified, you cannot save from within a foreach that is still drawing from the database via an active reader.

Calling ToList() or ToArray() is fine for small data sets, but when you have thousands of rows, you will be consuming a large amount of memory.

It's better to load the rows in chunks.

public static class EntityFrameworkUtil
{
    public static IEnumerable<T> QueryInChunksOf<T>(this IQueryable<T> queryable, int chunkSize)
    {
        return queryable.QueryChunksOfSize(chunkSize).SelectMany(chunk => chunk);
    }

    public static IEnumerable<T[]> QueryChunksOfSize<T>(this IQueryable<T> queryable, int chunkSize)
    {
        int chunkNumber = 0;
        while (true)
        {
            var query = (chunkNumber == 0)
                ? queryable 
                : queryable.Skip(chunkNumber * chunkSize);
            var chunk = query.Take(chunkSize).ToArray();
            if (chunk.Length == 0)
                yield break;
            yield return chunk;
            chunkNumber++;
        }
    }
}

Given the above extension methods, you can write your query like this:

foreach (var client in clientList.OrderBy(c => c.Id).QueryInChunksOf(100))
{
    // do stuff
    context.SaveChanges();
}

The queryable object you call this method on must be ordered. This is because Entity Framework only supports IQueryable<T>.Skip(int) on ordered queries, which makes sense when you consider that multiple queries for different ranges require the ordering to be stable. If the ordering isn't important to you, just order by primary key as that's likely to have a clustered index.

This version will query the database in batches of 100. Note that SaveChanges() is called for each entity.

If you want to improve your throughput dramatically, you should call SaveChanges() less frequently. Use code like this instead:

foreach (var chunk in clientList.OrderBy(c => c.Id).QueryChunksOfSize(100))
{
    foreach (var client in chunk)
    {
        // do stuff
    }
    context.SaveChanges();
}

This results in 100 times fewer database update calls. Of course each of those calls takes longer to complete, but you still come out way ahead in the end. Your mileage may vary, but this was worlds faster for me.

And it gets around the exception you were seeing.

EDIT I revisited this question after running SQL Profiler and updated a few things to improve performance. For anyone who is interested, here is some sample SQL that shows what is created by the DB.

The first loop doesn't need to skip anything, so is simpler.

SELECT TOP (100)                     -- the chunk size 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
FROM [dbo].[Clients] AS [Extent1]
ORDER BY [Extent1].[Id] ASC

Subsequent calls need to skip previous chunks of results, so introduces usage of row_number:

SELECT TOP (100)                     -- the chunk size
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
FROM (
    SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], row_number()
    OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]
    FROM [dbo].[Clients] AS [Extent1]
) AS [Extent1]
WHERE [Extent1].[row_number] > 100   -- the number of rows to skip
ORDER BY [Extent1].[Id] ASC

Disable Proximity Sensor during call

edit build.prop in folder /system if below line is exist change the value and if not exist add this line and save.(device must be rooted)

ro.lge.proximity.delay=25
mot.proximity.delay=25  

Python Dictionary contains List as Value - How to update?

An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it's in a dictionary or not:

l = dictionary.get('C1')
for i in range(len(l)):
    l[i] += 10

How to sort a file in-place

To sort file in place, try:

echo "$(sort your_file)" > your_file

As explained in other answers, you cannot directly redirect the output back to the input file. But you can evaluate the sort command first and then redirect it back to the original file. In this way you can implement in-place sort.

Similarly, you can also apply this trick to other command like paste to implement row-wise appending.

Bootstrap Element 100% Width

Sorry, should have asked for your css as well. As is, basically what you need to look at is giving your container div the style .container { width: 100%; } in your css and then the enclosed divs will inherit this as long as you don't give them their own width. You were also missing a few closing tags, and the </center> closes a <center> without it ever being open, at least in this section of code. I wasn't sure if you wanted the image in the same div that contains your content or separate, so I created two examples. I changed the width of the img to 100px simply because jsfiddle offers a small viewing area. Let me know if it's not what you're looking for.

content and image separate: http://jsfiddle.net/QvqKS/2/

content and image in same div (img floated left): http://jsfiddle.net/QvqKS/3/

Reading a file character by character in C

I think the most significant problem is that you're incrementing code as you read stuff in, and then returning the final value of code, i.e. you'll be returning a pointer to the end of the string. You probably want to make a copy of code before the loop, and return that instead.

Also, C strings need to be null-terminated. You need to make sure that you place a '\0' directly after the final character that you read in.

Note: You could just use fgets() to get the entire line in one hit.

How do I make entire div a link?

You need to assign display: block; property to the wrapping anchor. Otherwise it won't wrap correctly.

<a style="display:block" href="http://justinbieber.com">
  <div class="xyz">My div contents</div>
</a>

What static analysis tools are available for C#?

Optimyth Software has just launched a static analysis service in the cloud www.checkinginthecloud.com. Just securely upload your code run the analysis and get the results. No hassles.

It supports several languages including C# more info can be found at wwww.optimyth.com

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

How can I refresh a page with jQuery?

It is shortest in JavaScript.

window.location = '';

I want to vertical-align text in select box

Try to set the "line-height" attribute

Like this:

select{
    height: 28px !important;
    line-height: 28px;
}

Here you are some documentation about this attribute:

http://www.w3.org/wiki/CSS/Properties/line-height

http://www.w3schools.com/cssref/pr_dim_line-height.asp

TypeError: method() takes 1 positional argument but 2 were given

Pass cls parameter into @classmethod to resolve this problem.

@classmethod
def test(cls):
    return ''

How to make shadow on border-bottom?

New method for an old question

enter image description here

It seems like in the answers provided the issue was always how the box border would either be visible on the left and right of the object or you'd have to inset it so far that it didn't shadow the whole length of the container properly.

This example uses the :after pseudo element along with a linear gradient with transparency in order to put a drop shadow on a container that extends exactly to the sides of the element you wish to shadow.

Worth noting with this solution is that if you use padding on the element that you wish to drop shadow, it won't display correctly. This is because the after pseudo element appends it's content directly after the elements inner content. So if you have padding, the shadow will appear inside the box. This can be overcome by eliminating padding on outer container (where the shadow applies) and using an inner container where you apply needed padding.

Example with padding and background color on the shadowed div:

enter image description here

If you want to change the depth of the shadow, simply increase the height style in the after pseudo element. You can also obviously darken, lighten, or change colors in the linear gradient styles.

_x000D_
_x000D_
body {_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.bottom-shadow {_x000D_
  width: 80%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
.bottom-shadow:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  height: 8px;_x000D_
  background: transparent;_x000D_
  background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */_x000D_
  background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */_x000D_
  background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(   startColorstr='#a6000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.bottom-shadow div {_x000D_
  padding: 18px;_x000D_
  background: #fff;_x000D_
}
_x000D_
<div class="bottom-shadow">_x000D_
  <div>_x000D_
    Shadows, FTW!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Editing dictionary values in a foreach loop

You need to create a new Dictionary from the old rather than modifying in place. Somethine like (also iterate over the KeyValuePair<,> rather than using a key lookup:

int otherCount = 0;
int totalCounts = colStates.Values.Sum();
var newDict = new Dictionary<string,int>();
foreach (var kv in colStates) {
  if (kv.Value/(double)totalCounts < 0.05) {
    otherCount += kv.Value;
  } else {
    newDict.Add(kv.Key, kv.Value);
  }
}
if (otherCount > 0) {
  newDict.Add("Other", otherCount);
}

colStates = newDict;

T-SQL stored procedure that accepts multiple Id values

Try This One:

@list_of_params varchar(20) -- value 1, 2, 5, 7, 20 

SELECT d.[Name]
FROM Department d
where @list_of_params like ('%'+ CONVERT(VARCHAR(10),d.Id)  +'%')

very simple.

Cause of No suitable driver found for

I was facing similar problem and to my surprise the problem was in the version of Java. java.sql.DriverManager comes from rt.jar was unable to load my driver "COM.ibm.db2.jdbc.app.DB2Driver".

I upgraded from jdk 5 and jdk 6 and it worked.

How can I insert data into a MySQL database?

Here is OOP:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = '123'
    db = 'test'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
        self.cursor = self.connection.cursor()

    def insert(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
        except:
            self.connection.rollback()



    def query(self, query):
        cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
        cursor.execute(query)

        return cursor.fetchall()

    def __del__(self):
        self.connection.close()


if __name__ == "__main__":

    db = Database()

    #CleanUp Operation
    del_query = "DELETE FROM basic_python_database"
    db.insert(del_query)

    # Data Insert into the table
    query = """
        INSERT INTO basic_python_database
        (`name`, `age`)
        VALUES
        ('Mike', 21),
        ('Michael', 21),
        ('Imran', 21)
        """

    # db.query(query)
    db.insert(query)

    # Data retrieved from the table
    select_query = """
        SELECT * FROM basic_python_database
        WHERE age = 21
        """

    people = db.query(select_query)

    for person in people:
        print "Found %s " % person['name']

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.

Try disabling all non-essential modules (in php.ini), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.

If that doesn't help, you should report a php bug.

MySQL > Table doesn't exist. But it does (or it should)

One other answer I think is worth bringing up here (because I came here with that same problem and this turned out to be the answer for me):

Double check that the table name in your query is spelled exactly the same as it is in the database.

Kind of an obvious, newbie thing, but things like "user" vs "users" can trip people up and I thought it would be a helpful answer to have in the list here. :)

proper way to logout from a session in PHP

From the session_destroy() page in the PHP manual:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

How do I set the timeout for a JAX-WS webservice client?

the easiest way to avoid slow retrieval of the remote WSDL when you instantiate your SEI is to not retrieve the WSDL from the remote service endpoint at runtime.

this means that you have to update your local WSDL copy any time the service provider makes an impacting change, but it also means that you have to update your local copy any time the service provider makes an impacting change.

When I generate my client stubs, I tell the JAX-WS runtime to annotate the SEI in such a way that it will read the WSDL from a pre-determined location on the classpath. by default the location is relative to the package location of the Service SEI


<wsimport
    sourcedestdir="${dao.helter.dir}/build/generated"
    destdir="${dao.helter.dir}/build/bin/generated"
    wsdl="${dao.helter.dir}/src/resources/schema/helter/helterHttpServices.wsdl"
    wsdlLocation="./wsdl/helterHttpServices.wsdl"
    package="com.helter.esp.dao.helter.jaxws"
    >
    <binding dir="${dao.helter.dir}/src/resources/schema/helter" includes="*.xsd"/>
</wsimport>
<copy todir="${dao.helter.dir}/build/bin/generated/com/helter/esp/dao/helter/jaxws/wsdl">
    <fileset dir="${dao.helter.dir}/src/resources/schema/helter" includes="*" />
</copy>

the wsldLocation attribute tells the SEI where is can find the WSDL, and the copy makes sure that the wsdl (and supporting xsd.. etc..) is in the correct location.

since the location is relative to the SEI's package location, we create a new sub-package (directory) called wsdl, and copy all the wsdl artifacts there.

all you have to do at this point is make sure you include all *.wsdl, *.xsd in addition to all *.class when you create your client-stub artifact jar file.

(in case your curious, the @webserviceClient annotation is where this wsdl location is actually set in the java code

@WebServiceClient(name = "httpServices", targetNamespace = "http://www.helter.com/schema/helter/httpServices", wsdlLocation = "./wsdl/helterHttpServices.wsdl")

When to use the different log levels

I think that SYSLOG levels NOTICE and ALERT/EMERGENCY are largely superfluous for application-level logging - while CRITICAL/ALERT/EMERGENCY may be useful alert levels for an operator that may trigger different actions and notifications, to an application admin it's all the same as FATAL. And I just cannot sufficiently distinguish between being given a notice or some information. If the information is not noteworthy, it's not really information :)

I like Jay Cincotta's interpretation best - tracing your code's execution is something very useful in tech support, and putting trace statements into the code liberally should be encouraged - especially in combination with a dynamic filtering mechanism for logging the trace messages from specific application components. However DEBUG level to me indicates that we're still in the process of figuring out what's going on - I see DEBUG level output as a development-only option, not as something that should ever show up in a production log.

There is however a logging level that I like to see in my error logs when wearing the hat of a sysadmin as much as that of tech support, or even developer: OPER, for OPERATIONAL messages. This I use for logging a timestamp, the type of operation invoked, the arguments supplied, possibly a (unique) task identifier, and task completion. It's used when e.g. a standalone task is fired off, something that is a true invocation from within the larger long-running app. It's the sort of thing I want always logged, no matter whether anything goes wrong or not, so I consider the level of OPER to be higher than FATAL, so you can only turn it off by going to totally silent mode. And it's much more than mere INFO log data - a log level often abused for spamming logs with minor operational messages of no historical value whatsoever.

As the case dictates this information may be directed to a separate invocation log, or may be obtained by filtering it out of a large log recording more information. But it's always needed, as historical info, to know what was being done - without descending to the level of AUDIT, another totally separate log level that has nothing to do with malfunctions or system operation, doesn't really fit within the above levels (as it needs its own control switch, not a severity classification) and which definitely needs its own separate log file.

Use awk to find average of a column

Try this:

ls -l  | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'

NR is an AWK builtin variable to count the no. of records

How do I add FTP support to Eclipse?

have you checked RSE (Remote System Explorer) ? I think it's pretty close to what you want to achieve.

a blog post about it, with screenshots

Docker: How to use bash with an Alpine based docker image?

Try using RUN /bin/sh instead of bash.

mysql update column with value from another table

If you have common field in both table then it's so easy !....

Table-1 = table where you want to update. Table-2 = table where you from take data.

  1. make query in Table-1 and find common field value.
  2. make a loop and find all data from Table-2 according to table 1 value.
  3. again make update query in table 1.

$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");

$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}



foreach($resultArray as $rec) {

    $a = $rec['primary key field'];

    $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");

    $cuttable = mysql_fetch_assoc($cuttable_qry);



    echo $x= $cuttable['Table-2 field']; echo " ! ";
    echo $y= $cuttable['Table-2 field'];echo " ! ";
    echo $z= $cuttable['Table-2 field'];echo " ! ";


    $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");

    if ($k) {
        echo "done";
    } else {
        echo mysql_error();
    }


}

EF 5 Enable-Migrations : No context type was found in the assembly

I got this problem first: PM> add-migration first

No migrations configuration type was found in the assembly 'MyProjectName'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

then i tried this:

PM> Enable-Migrations No context type was found in the assembly 'MyProjectName'.

Then the right command for me :

PM> Enable-Migrations -ProjectName MyProjectName -ContextTypeName MyProjectName.Data.Context

After that i got this error message even though Context inherits from DbContext

The type 'Context' does not inherit from DbContext. The DbMigrationsConfiguration.ContextType property must be set to a type that inherits from DbContext.

Then i Installed Microsoft.EntityFrameworkCore.Tools

ITS OK NOW but the message is funny. i already tried add migrations at first :D

Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework6\Enable-Migrations' for Entity Framework 6. Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.

Unable to Resolve Module in React Native App

I had the exact same problem — fix was babel-preset-react-native-stage-0, instead of babel-preset-react-native.

How does DHT in torrents work?

With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.

So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.

In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I have similar problems, in my case seem to be related to network connectivity:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."

Things to check:

  • Is there any chance that your server is not able to respond within some time limit? Like 60 seconds or 4 minutes?
  • Is there a possibility that your device is switching networks (WiFi, 3G, VPN)?
  • Could someone (client vs. server) be waiting for authentication?

Sorry, no ideas how to fix. Just debugging this, trying to find out what the problem is (-1021, -1001, -1009)

Update: Google search was very kind to find this:

  • -1001 TimedOut - it took longer than the timeout which was alotted.
  • -1003 CannotFindHost - the host could not be found.
  • -1004 CannotConnectToHost - the host would not let us establish a connection.

how to change text box value with jQuery?

$('#cd').click(function() {
  $(this).val('dasf');  // update the value of submit button
  $('#dsf').val('Changed Value') // update the text input value
});

textbox is not a valid selector.

Also, when you hit the submit button it will submit the form as default behavior. So don't forget to stop default form submission.

Better if you do like this:

$('form').on('submit', function() {

  // write all your codes

  return false; // Prevent default form submission
});

Don't forget to user jQuery DOM ready $(function() { .. });

D3.js: How to get the computed width and height for an arbitrary element?

For SVG elements

Using something like selection.node().getBBox() you get values like

{
    height: 5, 
    width: 5, 
    y: 50, 
    x: 20
} 

For HTML elements

Use selection.node().getBoundingClientRect()

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

Ellipsis for overflow text in dropdown boxes

Found this absolute hack that actually works quite well:

https://codepen.io/nikitahl/pen/vyZbwR

Not CSS only though.

The basic gist is to have a container on the dropdown, .select-container in this case. That container has it's ::before set up to display content based on its data-content attribute/dataset, along with all of the overflow:hidden; text-overflow: ellipsis; and sizing necessary to make the ellipsis work.

When the select changes, javascript assigns the value (or you could retrieve the text of the option out of the select.options list) to the dataset.content of the container, and voila!

Copying content of the codepen here:

_x000D_
_x000D_
var selectContainer = document.querySelector(".select-container");_x000D_
var select = selectContainer.querySelector(".select");_x000D_
select.value = "lingua latina non penis canina";_x000D_
_x000D_
selectContainer.dataset.content = select.value;_x000D_
_x000D_
function handleChange(e) {_x000D_
  selectContainer.dataset.content = e.currentTarget.value;_x000D_
  console.log(select.value);_x000D_
}_x000D_
_x000D_
select.addEventListener("change", handleChange);
_x000D_
span {_x000D_
  margin: 0 10px 0 0;_x000D_
}_x000D_
_x000D_
.select-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.select-container::before {_x000D_
  content: attr(data-content);_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 10px;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  padding: 7px;_x000D_
  font: 11px Arial, sans-serif;_x000D_
  white-space: nowrap;_x000D_
  text-overflow: ellipsis;_x000D_
  overflow: hidden;_x000D_
  text-transform: capitalize;_x000D_
  pointer-events: none;_x000D_
}_x000D_
_x000D_
.select {_x000D_
  width: 80px;_x000D_
  padding: 5px;_x000D_
  appearance: none;_x000D_
  background: transparent url("https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-down-b-128.png") no-repeat calc(~"100% - 5px") 7px;_x000D_
  background-size: 10px 10px;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.regular {_x000D_
  display: inline-block;_x000D_
  margin: 10px 0 0;_x000D_
  .select {_x000D_
    color: #000;_x000D_
  }_x000D_
}
_x000D_
<span>Hack:</span><div class="select-container" data-content="">_x000D_
  <select class="select" id="words">_x000D_
    <option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
    <option value="lorem">Lorem</option>_x000D_
    <option value="ipsum">Ipsum</option>_x000D_
    <option value="dolor">Dolor</option>_x000D_
    <option value="sit">Sit</option>_x000D_
    <option value="amet">Amet</option>_x000D_
    <option value="lingua">Lingua</option>_x000D_
    <option value="latina">Latina</option>_x000D_
    <option value="non">Non</option>_x000D_
    <option value="penis">Penis</option>_x000D_
    <option value="canina">Canina</option>_x000D_
  </select>_x000D_
</div>_x000D_
<br />_x000D_
_x000D_
<span>Regular:</span>_x000D_
<div class="regular">_x000D_
  <select style="width: 80px;">_x000D_
    <option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
    <option value="lorem">Lorem</option>_x000D_
    <option value="ipsum">Ipsum</option>_x000D_
    <option value="dolor">Dolor</option>_x000D_
    <option value="sit">Sit</option>_x000D_
    <option value="amet">Amet</option>_x000D_
    <option value="lingua">Lingua</option>_x000D_
    <option value="latina">Latina</option>_x000D_
    <option value="non">Non</option>_x000D_
    <option value="penis">Penis</option>_x000D_
    <option value="canina">Canina</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

is there a 'block until condition becomes true' function in java?

Lock-free solution(?)

I had the same issue, but I wanted a solution that didn't use locks.

Problem: I have at most one thread consuming from a queue. Multiple producer threads are constantly inserting into the queue and need to notify the consumer if it's waiting. The queue is lock-free so using locks for notification causes unnecessary blocking in producer threads. Each producer thread needs to acquire the lock before it can notify the waiting consumer. I believe I came up with a lock-free solution using LockSupport and AtomicReferenceFieldUpdater. If a lock-free barrier exists within the JDK, I couldn't find it. Both CyclicBarrier and CoundDownLatch use locks internally from what I could find.

This is my slightly abbreviated code. Just to be clear, this code will only allow one thread to wait at a time. It could be modified to allow for multiple awaiters/consumers by using some type of atomic collection to store multiple owner (a ConcurrentMap may work).

I have used this code and it seems to work. I have not tested it extensively. I suggest you read the documentation for LockSupport before use.

/* I release this code into the public domain.
 * http://unlicense.org/UNLICENSE
 */

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;

/**
 * A simple barrier for awaiting a signal.
 * Only one thread at a time may await the signal.
 */
public class SignalBarrier {
    /**
     * The Thread that is currently awaiting the signal.
     * !!! Don't call this directly !!!
     */
    @SuppressWarnings("unused")
    private volatile Thread _owner;

    /** Used to update the owner atomically */
    private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
        AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");

    /** Create a new SignalBarrier without an owner. */
    public SignalBarrier() {
        _owner = null;
    }

    /**
     * Signal the owner that the barrier is ready.
     * This has no effect if the SignalBarrer is unowned.
     */
    public void signal() {
        // Remove the current owner of this barrier.
        Thread t = ownerAccess.getAndSet(this, null);

        // If the owner wasn't null, unpark it.
        if (t != null) {
            LockSupport.unpark(t);
        }
    }

    /**
     * Claim the SignalBarrier and block until signaled.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     */
    public void await() throws InterruptedException {
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
        }

        // The current thread has taken ownership of this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        LockSupport.park(this);
        // If a thread has called #signal() the owner should already be null.
        // However the documentation for LockSupport.unpark makes it clear that
        // threads can wake up for absolutely no reason. Do a compare and set
        // to make sure we don't wipe out a new owner, keeping in mind that only
        // thread should be awaiting at any given moment!
        ownerAccess.compareAndSet(this, t, null);

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();
    }

    /**
     * Claim the SignalBarrier and block until signaled or the timeout expires.
     *
     * @throws IllegalStateException If the SignalBarrier already has an owner.
     * @throws InterruptedException If the thread is interrupted while waiting.
     *
     * @param timeout The timeout duration in nanoseconds.
     * @return The timeout minus the number of nanoseconds that passed while waiting.
     */
    public long awaitNanos(long timeout) throws InterruptedException {
        if (timeout <= 0)
            return 0;
        // Get the thread that would like to await the signal.
        Thread t = Thread.currentThread();

        // If a thread is attempting to await, the current owner should be null.
        if (!ownerAccess.compareAndSet(this, null, t)) {
            throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
        }

        // The current thread owns this barrier.
        // Park the current thread until the signal. Record this
        // signal barrier as the 'blocker'.
        // Time the park.
        long start = System.nanoTime();
        LockSupport.parkNanos(this, timeout);
        ownerAccess.compareAndSet(this, t, null);
        long stop = System.nanoTime();

        // Check to see if we've been unparked because of a thread interrupt.
        if (t.isInterrupted())
            throw new InterruptedException();

        // Return the number of nanoseconds left in the timeout after what we
        // just waited.
        return Math.max(timeout - stop + start, 0L);
    }
}

To give a vague example of usage, I'll adopt james large's example:

SignalBarrier barrier = new SignalBarrier();

Consumer thread (singular, not plural!):

try {
    while(!conditionIsTrue()) {
        barrier.await();
    }
    doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
    handleInterruption();
}

Producer thread(s):

doSomethingThatMakesConditionTrue();
barrier.signal();

How to change the size of the font of a JLabel to take the maximum size

JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));

Count unique values with pandas per groups

df.domain.value_counts()

>>> df.domain.value_counts()

vk.com          5

twitter.com     2

google.com      1

facebook.com    1

Name: domain, dtype: int64

What does "where T : class, new()" mean?

That means that type T must be a class and have a constructor that does not take any arguments.

For example, you must be able to do this:

T t = new T();

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)


1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

how to calculate binary search complexity

A binary search works by dividing the problem in half repeatedly, something like this (details omitted):

Example looking for 3 in [4,1,3,8,5]

  1. Order your list of items [1,3,4,5,8]
  2. Look at the middle item (4),
    • If it is what you are looking for, stop
    • If it is greater, look at the first half
    • If it is less, look at the second half
  3. Repeat step 2 with the new list [1, 3], find 3 and stop

It is a bi-nary search when you divide the problem in 2.

The search only requires log2(n) steps to find the correct value.

I would recommend Introduction to Algorithms if you want to learn about algorithmic complexity.

Maven Error: Could not find or load main class

The first thing i would suggest is to use the correct configuration for predefined descriptors.

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        [...]
</project>

To configure the main class you need to know the package and name of the class you would like to use which should be given into <mainClass>...</mainClass> parameter.

Furthermore i recommend to stop using Maven 2 and move to Maven 3 instead.

Scala best way of turning a Collection into a Map-by-key?

For what it's worth, here are two pointless ways of doing it:

scala> case class Foo(bar: Int)
defined class Foo

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> val c = Vector(Foo(9), Foo(11))
c: scala.collection.immutable.Vector[Foo] = Vector(Foo(9), Foo(11))

scala> c.map(((_: Foo).bar) &&& identity).toMap
res30: scala.collection.immutable.Map[Int,Foo] = Map(9 -> Foo(9), 11 -> Foo(11))

scala> c.map(((_: Foo).bar) >>= (Pair.apply[Int, Foo] _).curried).toMap
res31: scala.collection.immutable.Map[Int,Foo] = Map(9 -> Foo(9), 11 -> Foo(11))

"google is not defined" when using Google Maps V3 in Firefox remotely

In my case I was loading the google script via http while my server had SSL and its being loaded over https. So I had to load script via https

Test if characters are in a string

Use the grepl function

grepl( needle, haystack, fixed = TRUE)

like so:

grepl(value, chars, fixed = TRUE)
# TRUE

Use ?grepl to find out more.

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

How can I check out a GitHub pull request with git?

For Bitbucket, you need replace the word pull to pull-requests.

First, you can confirm the pull request URL style by git ls-remote origin command.

$ git ls-remote origin |grep pull
f3f40f2ca9509368c959b0b13729dc0ae2fbf2ae    refs/pull-requests/1503/from
da4666bd91eabcc6f2c214e0bbd99d543d94767e    refs/pull-requests/1503/merge
...

As you can see, it is refs/pull-requests/1503/from instead of refs/pull/1503/from

Then you can use the commands of any of the answers.

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

Why use multiple columns as primary keys (composite primary key)

You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.

What is the difference between <p> and <div>?

The previous code was

<p class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></p>

So I have to changed it to

<div class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></div>

It was the easy fix. And the CSS for the above code is

.item {
    position: relative;
    border: 1px solid green;
    height: 30px;
}

.item .name {
    position: absolute;
    top: 0px;
    left: 0px;
}

.item .price {
    position: absolute;
    right: 0px;
    bottom: 0px;
}

So div tag can contain other elements. P should not be forced to do that.

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);

Is putting a div inside an anchor ever correct?

If you change it to a block-style element, then no, it's no longer 'wrong', but it probably won't validate. But it doesn't make much sense to do what you're doing. You should either just keep the anchor tag as a block level element with no inner div, or put the div on the outside.

Can "git pull --all" update all my local branches?

A script I wrote for my GitBash. Accomplishes the following:

  • By default pulls from origin for all branches that are setup to track origin, allows you to specify a different remote if desired.
  • If your current branch is in a dirty state then it stashes your changes and will attempt to restore these changes at the end.
  • For each local branch that is set up to track a remote branch will:
    • git checkout branch
    • git pull origin
  • Finally, will return you to your original branch and restore state.

** I use this but have not tested thoroughly, use at own risk. See an example of this script in a .bash_alias file here.

    # Do a pull on all branches that are tracking a remote branches, will from origin by default.
    # If current branch is dirty, will stash changes and reply after pull.
    # Usage: pullall [remoteName]
    alias pullall=pullAll
    function pullAll (){
     # if -h then show help
     if [[ $1 == '-h' ]]
    then
      echo "Description: Pulls new changes from upstream on all branches that are tracking remotes."
      echo 
      echo "Usage: "
      echo "- Default: pullall"
      echo "- Specify upstream to pull from: pullall [upstreamName]"
      echo "- Help: pull-all -h"
    else

     # default remote to origin
     remote="origin"
     if [ $1 != "" ]
     then
       remote=$1
     fi

     # list all branches that are tracking remote
     # git branch -vv : list branches with their upstreams
     # grep origin : keep only items that have upstream of origin
     # sed "s/^.."... : remove leading *
     # sed "s/^"..... : remove leading white spaces
     # cut -d" "..... : cut on spaces, take first item
     # cut -d splits on space, -f1 grabs first item
     branches=($(git branch -vv | grep $remote | sed "s/^[ *]*//" | sed "s/^[ /t]*//" | cut -d" " -f1))

     # get starting branch name
     startingBranch=$(git rev-parse --abbrev-ref HEAD)

     # get starting stash size
     startingStashSize=$(git stash list | wc -l)

     echo "Saving starting branch state: $startingBranch"
     git stash

     # get the new stash size
     newStashSize=$(git stash list | wc -l)

     # for each branch in the array of remote tracking branches
     for branch in ${branches[*]}
     do
       echo "Switching to $branch"
       git checkout $branch

       echo "Pulling $remote"
       git pull $remote

     done

     echo "Switching back to $startingBranch"
     git checkout $startingBranch

     # compare before and after stash size to see if anything was stashed
     if [ "$startingStashSize" -lt "$newStashSize" ]
     then
       echo "Restoring branch state"
       git stash pop
     fi
    fi
    }

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

Get environment variable value in Dockerfile

You should use the ARG directive in your Dockerfile which is meant for this purpose.

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

So your Dockerfile will have this line:

ARG request_domain

or if you'd prefer a default value:

ARG request_domain=127.0.0.1

Now you can reference this variable inside your Dockerfile:

ENV request_domain=$request_domain

then you will build your container like so:

$ docker build --build-arg request_domain=mydomain Dockerfile


Note 1: Your image will not build if you have referenced an ARG in your Dockerfile but excluded it in --build-arg.

Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:

[Warning] One or more build-args [foo] were not consumed.

Best Practice: Access form elements by HTML id or name attribute?

It’s not really answering your question, but just on this part:

[3] requires both an id and a name... having both is somewhat redundant

You’ll most likely need to have an id attribute on each form field anyway, so that you can associate its <label> element with it, like this:

<label for="foo">Foo:</label>
<input type="text" name="foo" id="foo" />

This is required for accessibility (i.e. if you don’t associate form labels and controls, why do you hate blind people so much?).

It is somewhat redundant, although less so when you have checkboxes/radio buttons, where several of them can share a name. Ultimately, id and name are for different purposes, even if both are often set to the same value.

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

Below is my code.I also had the same error but the problem was that i gave my password wrong.The below code will work perfectly..try it

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");              
            mail.From = new MailAddress("[email protected]");
            mail.To.Add("[email protected]");
            mail.To.Add("[email protected]");
            mail.Subject = "Password Recovery ";
            mail.Body += " <html>";
            mail.Body += "<body>";
            mail.Body += "<table>";

            mail.Body += "<tr>";
            mail.Body += "<td>User Name : </td><td> HAi </td>";
            mail.Body += "</tr>";

            mail.Body += "<tr>";
            mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
            mail.Body += "</tr>";

            mail.Body += "</table>";
            mail.Body += "</body>";
            mail.Body += "</html>";

            mail.IsBodyHtml = true;
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("sendfrommailaddress.com", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);

You can reffer it in Sending mail

How do I get a file's directory using the File object?

String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length()); 

This would be my solution

How to print colored text to the terminal?

If you are using Django:

>>> from django.utils.termcolors import colorize
>>> print colorize("Hello, World!", fg="blue", bg='red',
...                 opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)

Snapshot:

Image

(I generally use colored output for debugging on runserver terminal, so I added it.)

You can test if it is installed in your machine: $ python -c "import django; print django.VERSION". To install it, check: How to install Django

Give it a try!!

Refreshing all the pivot tables in my excel workbook with a macro

If you are using MS Excel 2003 then go to view->Tool bar->Pivot Table From this tool bar we can do refresh by clicking ! this symbol.

What is the difference between an abstract function and a virtual function?

An abstract function is "just" a signature, without an implementation. It is used in an interface to declare how the class can be used. It must be implemented in one of the derived classes.

Virtual function (method actually), is a function you declare as well, and should implemented in one of the inheritance hierarchy classes.

The inherited instances of such class, inherit the implementation as well, unless you implement it, in a lower hierarchy class.

What's an Aggregate Root?

From Evans DDD:

An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary. The boundary defines what is inside the AGGREGATE. The root is a single, specific ENTITY contained in the AGGREGATE.

And:

The root is the only member of the AGGREGATE that outside objects are allowed to hold references to[.]

This means that aggregate roots are the only objects that can be loaded from a repository.

An example is a model containing a Customer entity and an Address entity. We would never access an Address entity directly from the model as it does not make sense without the context of an associated Customer. So we could say that Customer and Address together form an aggregate and that Customer is an aggregate root.

SQL Logic Operator Precedence: And and Or

  1. Arithmetic operators
  2. Concatenation operator
  3. Comparison conditions
  4. IS [NOT] NULL, LIKE, [NOT] IN
  5. [NOT] BETWEEN
  6. Not equal to
  7. NOT logical condition
  8. AND logical condition
  9. OR logical condition

You can use parentheses to override rules of precedence.

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

You may connect to Oracle database using sqlplus:

sqlplus "/as sysdba"

Then create new users and assign privileges.

grant all privileges to dac;

Setting PHPMyAdmin Language

sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set:

$cfg['Lang'] = 'en-utf-8';

PHP preg_replace special characters

$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);

I put them on two separate lines to make the code a little more clear.

Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z.

IIS: Where can I find the IIS logs?

C:\inetpub\logs\LogFiles

Check the identity of the site going to sites and advanced settings

Javascript Regex: How to put a variable inside a regular expression?

You can create regular expressions in JS in one of two ways:

  1. Using regular expression literal - /ab{2}/g
  2. Using the regular expression constructor - new RegExp("ab{2}", "g") .

Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is

new RegExp(regularExpressionString, modifiersString)

You can embed variables as part of the regularExpressionString. For example,

var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g") 

This will match any appearance of the pattern cdcdcd.

How can I selectively merge or pick changes from another branch in Git?

The easiest way is to set your repository to the branch you want to merge with, and then run

git checkout [branch with file] [path to file you would like to merge]

If you run

git status

you will see the file already staged...

Then run

git commit -m "Merge changes on '[branch]' to [file]"

Simple.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

You would mostly be using COUNT to summarize over a UID. Therefore

COUNT([uid]) will produce the warning:

Warning: Null value is eliminated by an aggregate or other SET operation.

whilst being used with a left join, where the counted object does not exist.

Using COUNT(*) in this case would also render incorrect results, as you would then be counting the total number of results (ie parents) that exist.

Using COUNT([uid]) IS a valid way of counting, and the warning is nothing more than a warning. However if you are concerned, and you want to get a true count of uids in this case then you could use:

SUM(CASE WHEN [uid] IS NULL THEN 0 ELSE 1 END) AS [new_count]

This would not add a lot of overheads to your query. (tested mssql 2008)

Peak signal detection in realtime timeseries data

Perl implementation of @Jean-Paul's algorithm.

#!/usr/bin/perl

use strict;
use Data::Dumper;

sub mean {
    my $data = shift;
    my $sum = 0;
    my $mean_val = 0;
    for my $item (@$data) {
        $sum += $item;
    }
    $mean_val = $sum / (scalar @$data) if @$data;
    return $mean_val;
}

sub variance {
    my $data = shift;
    my $variance_val = 0;
    my $mean_val = mean($data);
    my $sum = 0;
    for my $item (@$data) {
        $sum += ($item - $mean_val)**2;
    }
    $variance_val = $sum / (scalar @$data) if @$data;
    return $variance_val;
}

sub std {
    my $data = shift;
    my $variance_val = variance($data);
    return sqrt($variance_val);
}

# @param y - The input vector to analyze
# @parameter lag - The lag of the moving window
# @parameter threshold - The z-score at which the algorithm signals
# @parameter influence - The influence (between 0 and 1) of new signals on the mean and standard deviation
sub thresholding_algo {
    my ($y, $lag, $threshold, $influence) = @_;

    my @signals = (0) x @$y;
    my @filteredY = @$y;
    my @avgFilter = (0) x @$y;
    my @stdFilter = (0) x @$y;

    $avgFilter[$lag - 1] = mean([@$y[0..$lag-1]]);
    $stdFilter[$lag - 1] = std([@$y[0..$lag-1]]);

    for (my $i=$lag; $i <= @$y - 1; $i++) {
        if (abs($y->[$i] - $avgFilter[$i-1]) > $threshold * $stdFilter[$i-1]) {
            if ($y->[$i] > $avgFilter[$i-1]) {
                $signals[$i] = 1;
            } else {
                $signals[$i] = -1;
            }

            $filteredY[$i] = $influence * $y->[$i] + (1 - $influence) * $filteredY[$i-1];
            $avgFilter[$i] = mean([@filteredY[($i-$lag)..($i-1)]]);
            $stdFilter[$i] = std([@filteredY[($i-$lag)..($i-1)]]);
        }
        else {
            $signals[$i] = 0;
            $filteredY[$i] = $y->[$i];
            $avgFilter[$i] = mean([@filteredY[($i-$lag)..($i-1)]]);
            $stdFilter[$i] = std([@filteredY[($i-$lag)..($i-1)]]);
        }
    }

    return {
        signals => \@signals,
        avgFilter => \@avgFilter,
        stdFilter => \@stdFilter
    };
}

my $y = [1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
       1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
       2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1];

my $lag = 30;
my $threshold = 5;
my $influence = 0;

my $result = thresholding_algo($y, $lag, $threshold, $influence);

print Dumper $result;

Disable a textbox using CSS

Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:

.style1[disabled] { ... }

Worked ok on IE8.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Other than using the Navigator/Proj Explorer and choosing files and doing 'Compare With'->'Each other'... I prefer opening both files in Eclipse and using 'Compare With'->'Opened Editor'->(pick the opened tab)... You can get this feature via the AnyEdit eclipse plugin located here (you can use Install Software via Eclipse->Help->Install New Software screen): http://andrei.gmxhome.de/eclipse/

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

The SETX command does not modify the current environment.

If you run the following batch file:

setx AAA aaa
echo AAA=%AAA%

It will print

AAA=

So your batch file is wrong. You have to use set:

set AAA=aaa

See What is the difference between SETX and SET in environment variables in Windows.

ModuleNotFoundError: No module named 'sklearn'

SOLVED:

The above did not help. Then I simply installed sklearn from within Jypyter-lab, even though sklearn 0.0 shows in 'pip list':

!pip install sklearn
import sklearn

What I learned later is that pip installs, in my case, packages in a different folder than Jupyter. This can be seen by executing:

import sys
print(sys.path)

Once from within Jupyter_lab notebook, and once from the command line using 'py notebook.py'.

In my case Jupyter list of paths where subfolders of 'anaconda' whereas Python list where subfolders of c:\users[username]...

How to concatenate strings in django templates?

In my project I did it like this:

@register.simple_tag()
def format_string(string: str, *args: str) -> str:
    """
    Adds [args] values to [string]
    String format [string]: "Drew %s dad's %s dead."
    Function call in template: {% format_string string "Dodd's" "dog's" %}
    Result: "Drew Dodd's dad's dog's dead."
    """
    return string % args

Here, the string you want concatenate and the args can come from the view, for example.

In template and using your case:

{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}

The nice part is that format_string can be reused for any type of string formatting in templates

clearInterval() not working

setInterval returns an ID which you then use to clear the interval.

var intervalId;
on.onclick = function() {
    if (intervalId) {
        clearInterval(intervalId);
    }
    intervalId = setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(intervalId);
}; 

Best way to randomize an array with .NET

Ok, this is clearly a bump from my side (apologizes...), but I often use a quite general and cryptographically strong method.

public static class EnumerableExtensions
{
    static readonly RNGCryptoServiceProvider RngCryptoServiceProvider = new RNGCryptoServiceProvider();
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> enumerable)
    {
        var randomIntegerBuffer = new byte[4];
        Func<int> rand = () =>
                             {
                                 RngCryptoServiceProvider.GetBytes(randomIntegerBuffer);
                                 return BitConverter.ToInt32(randomIntegerBuffer, 0);
                             };
        return from item in enumerable
               let rec = new {item, rnd = rand()}
               orderby rec.rnd
               select rec.item;
    }
}

Shuffle() is an extension on any IEnumerable so getting, say, numbers from 0 to 1000 in random order in a list can be done with

Enumerable.Range(0,1000).Shuffle().ToList()

This method also wont give any surprises when it comes to sorting, since the sort value is generated and remembered exactly once per element in the sequence.

How to make g++ search for header files in a specific directory?

A/code.cpp

#include <B/file.hpp>

A/a/code2.cpp

#include <B/file.hpp>

Compile using:

g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp

Edit:

You can use environment variables to change the path g++ looks for header files. From man page:

Some additional environments variables affect the behavior of the preprocessor.

   CPATH
   C_INCLUDE_PATH
   CPLUS_INCLUDE_PATH
   OBJC_INCLUDE_PATH

Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.

CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.

The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.

In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.

There are many ways you can change an environment variable. On bash prompt you can do this:

$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp

You can of course add this in your Makefile etc.

Core Data: Quickest way to delete all instances of an entity

iOS 10 and later

Works with all versions. Pass entity name and iterate through to delete all the entries and save the context.

func deleteData(entityToFetch: String, completion: @escaping(_ returned: Bool) ->()) {
        let context = NSManagedObjectContext()
        context = your managedObjectContext

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
        fetchRequest.entity = NSEntityDescription.entity(forEntityName: entityToFetch, in: context)
        fetchRequest.includesPropertyValues = false
         do {   
            let results = try context.fetch(fetchRequest) as! [NSManagedObject]
            for result in results {
                context.delete(result)
            }
            try context.save()
            completion(true)
        } catch {
            completion(false)
            print("fetch error -\(error.localizedDescription)")
        }
    }

When creating a service with sc.exe how to pass in context parameters?

I couldn't handle the issue with your proposals, at the end with the x86 folder it only worked in power shell (windows server 2012) using environment variables:

{sc.exe create svnserve binpath= "${env:programfiles(x86)}/subversion/bin/svnserve.exe --service -r C:/svnrepositories/"   displayname= "Subversion Server" depend= Tcpip start= auto}

MySQL Like multiple values

Like @Alexis Dufrenoy proposed, the query could be:

SELECT * FROM `table` WHERE find_in_set('sports', interests)>0 OR find_in_set('pub', interests)>0

More information in the manual.

JPA: How to get entity based on field value other than ID?

Best practice is using @NaturalId annotation. It can be used as the business key for some cases it is too complicated, so some fields are using as the identifier in the real world. For example, I have user class with user id as primary key, and email is also unique field. So we can use email as our natural id

@Entity
@Table(name="user")
public class User {
  @Id
  @Column(name="id")
  private int id;

  @NaturalId
  @Column(name="email")
  private String email;

  @Column(name="name")
  private String name;
}

To get our record, just simply use 'session.byNaturalId()'

Session session = sessionFactory.getCurrentSession();
User user = session.byNaturalId(User.class)
                   .using("email","[email protected]")
                   .load()

Inherit CSS class

i think you can use more than one class in a tag

for example:

<div class="whatever base"></div>
<div class="whatever2 base"></div>

so when you want to chage all div's color you can just change the .base

...i dont know how to inherit in CSS

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

You can try to add @Transactional annotation to your bean or method (if declaration of all variables places in method).