Programs & Examples On #Prepared statement

A Prepared Statement (or parameterized statement) is a precompiled SQL statement that serves to improve performance and mitigate SQL injection attacks. Prepared statements are used in many popular Relational Database Management Systems.

PDO Prepared Inserts multiple rows in single query

Here is my solution: https://github.com/sasha-ch/Aura.Sql based on auraphp/Aura.Sql library.

Usage example:

$q = "insert into t2(id,name) values (?,?), ... on duplicate key update name=name"; 
$bind_values = [ [[1,'str1'],[2,'str2']] ];
$pdo->perform($q, $bind_values);

Bugreports are welcome.

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Using "like" wildcard in prepared statement

PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');

Try this out.

PreparedStatement with list of parameters in a IN clause

What you can do is dynamically build the select string (the 'IN (?)' part) by a simple for loop as soon as you know how many values you need to put inside the IN clause. You can then instantiate the PreparedStatement.

How can I get the SQL of a PreparedStatement?

To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.

Take a look at log4jdbc

What does "if (rs.next())" mean?

The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

Moves the cursor down one row from its current position.

This method return true if there's another row or false otherwise.

PreparedStatement IN clause alternatives?

instead of using

SELECT my_column FROM my_table where search_column IN (?)

use the Sql Statement as

select id, name from users where id in (?, ?, ?)

and

preparedStatement.setString( 1, 'A');
preparedStatement.setString( 2,'B');
preparedStatement.setString( 3, 'C');

or use a stored procedure this would be the best solution, since the sql statements will be compiled and stored in DataBase server

Can I bind an array to an IN() condition?

If the column can only contain integers, you could probably do this without placeholders and just put the ids in the query directly. You just have to cast all the values of the array to integers. Like this:

$listOfIds = implode(',',array_map('intval', $ids));
$stmt = $db->prepare(
    "SELECT *
     FROM table
     WHERE id IN($listOfIds)"
);
$stmt->execute();

This shouldn't be vulnerable to any SQL injection.

Get query from java.sql.PreparedStatement

For those of you looking for a solution for Oracle, I made a method from the code of Log4Jdbc. You will need to provide the query and the parameters passed to the preparedStatement since retrieving them from it is a bit of a pain:

private String generateActualSql(String sqlQuery, Object... parameters) {
    String[] parts = sqlQuery.split("\\?");
    StringBuilder sb = new StringBuilder();

    // This might be wrong if some '?' are used as litteral '?'
    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];
        sb.append(part);
        if (i < parameters.length) {
            sb.append(formatParameter(parameters[i]));
        }
    }

    return sb.toString();
}

private String formatParameter(Object parameter) {
    if (parameter == null) {
        return "NULL";
    } else {
        if (parameter instanceof String) {
            return "'" + ((String) parameter).replace("'", "''") + "'";
        } else if (parameter instanceof Timestamp) {
            return "to_timestamp('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS").
                    format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss.ff3')";
        } else if (parameter instanceof Date) {
            return "to_date('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").
                    format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss')";
        } else if (parameter instanceof Boolean) {
            return ((Boolean) parameter).booleanValue() ? "1" : "0";
        } else {
            return parameter.toString();
        }
    }
}

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

Where's my invalid character (ORA-00911)

One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

How can prepared statements protect from SQL injection attacks?

The idea is very simple - the query and the data are sent to the database server separately.
That's all.

The root of the SQL injection problem is in the mixing of the code and the data.

In fact, our SQL query is a legitimate program. And we are creating such a program dynamically, adding some data on the fly. Thus, the data may interfere with the program code and even alter it, as every SQL injection example shows it (all examples in PHP/Mysql):

$expected_data = 1;
$query = "SELECT * FROM users where id=$expected_data";

will produce a regular query

SELECT * FROM users where id=1

while this code

$spoiled_data = "1; DROP TABLE users;"
$query        = "SELECT * FROM users where id=$spoiled_data";

will produce a malicious sequence

SELECT * FROM users where id=1; DROP TABLE users;

It works because we are adding the data directly to the program body and it becomes a part of the program, so the data may alter the program, and depending on the data passed, we will either have a regular output or a table users deleted.

While in case of prepared statements we don't alter our program, it remains intact
That's the point.

We are sending a program to the server first

$db->prepare("SELECT * FROM users where id=?");

where the data is substituted by some variable called a parameter or a placeholder.

Note that exactly the same query is sent to the server, without any data in it! And then we're sending the data with the second request, essentially separated from the query itself:

$db->execute($data);

so it can't alter our program and do any harm.
Quite simple - isn't it?

The only thing I have to add that always omitted in the every manual:

Prepared statements can protect only data literals, but cannot be used with any other query part.
So, once we have to add, say, a dynamical identifier - a field name, for example - prepared statements can't help us. I've explained the matter recently, so I won't repeat myself.

Using prepared statements with JDBCTemplate

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

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

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

MySQLi prepared statements error reporting

Not sure if this answers your question or not. Sorry if not

To get the error reported from the mysql database about your query you need to use your connection object as the focus.

so:

echo $mysqliDatabaseConnection->error

would echo the error being sent from mysql about your query.

Hope that helps

Using setDate in PreparedStatement

The docs explicitly says that java.sql.Date will throw:

  • IllegalArgumentException - if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d)

Also you shouldn't need to convert a date to a String then to a sql.date, this seems superfluous (and bug-prone!). Instead you could:

java.sql.Date sqlDate := new java.sql.Date(now.getTime());
prs.setDate(2, sqlDate);
prs.setDate(3, sqlDate);

What does a question mark represent in SQL queries?

The ? is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.

How does a PreparedStatement avoid or prevent SQL injection?

PreparedStatement:

1) Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

2) Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the value.

Java: Insert multiple rows into MySQL with PreparedStatement

When MySQL driver is used you have to set connection param rewriteBatchedStatements to true ( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**).

With this param the statement is rewritten to bulk insert when table is locked only once and indexes are updated only once. So it is much faster.

Without this param only advantage is cleaner source code.

PHP Function with Optional Parameters

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Example Using ... to access variable arguments

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

The above example will output:

10

Variable-length argument lists PHP Documentation

Convert java.util.Date to String

Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");

How to print an unsigned char in C?

In case you cannot change the declaration for whatever reason, you can do:

char ch = 212;
printf("%d", (unsigned char) ch);

jQuery returning "parsererror" for ajax request

Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

ssh: check if a tunnel is alive

#!/bin/bash

# Check do we have tunnel to example.com server
lsof -i tcp@localhost:6000 > /dev/null

# If exit code wasn't 0 then tunnel doesn't exist.
if [ $? -eq 1 ]
then
  echo ' > You missing ssh tunnel. Creating one..'
  ssh -L 6000:localhost:5432 example.com
fi

echo ' > DO YOUR STUFF < '

SwiftUI - How do I change the background color of a View?

NavigationView Example:

var body: some View {
    var body: some View {
        NavigationView {
            ZStack {
                // Background
                Color.blue.edgesIgnoringSafeArea(.all)

                content
            }
            //.navigationTitle(Constants.navigationTitle)
            //.navigationBarItems(leading: cancelButton, trailing: doneButton)
            //.navigationViewStyle(StackNavigationViewStyle())
        }
    }
}

var content: some View {
    // your content here; List, VStack etc - whatever you want
    VStack {
       Text("Hello World")
    }
}

SVN icon overlays not showing properly

In my case all icons suddenly disappeared .

Solution :

  1. Go To Task Manager and kill Explorer
  2. In Task Manager File (New Task (Run) ) => explorer

and all appeared again...

Change <select>'s option and trigger events with JavaScript

These questions may be relevant to what you're asking for:

Here are my thoughts: You can stack up more than one call in your onclick event like this:

<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true; alert("changed");' value="Change option to 2" />

You could also call a function to do this.

If you really want to call one function and have both behave the same way, I think something like this should work. It doesn't really follow the best practice of "Functions should do one thing and do it well", but it does allow you to call one function to handle both ways of changing the dropdown. Basically I pass (value) on the onchange event and (null, index of option) on the onclick event.

Here is the codepen: http://codepen.io/mmaynar1/pen/ZYJaaj

<select id="sel" onchange='doThisOnChange(this.value)'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" onclick='doThisOnChange(null,1);' value="Change option to 2"/>

<script>
doThisOnChange = function( value, optionIndex)
{
    if ( optionIndex != null )
    {
       var option = document.getElementById( "sel" ).options[optionIndex];
       option.selected = true;
       value = option.value;
    }
    alert( "Do something with the value: " + value );
}
</script>

static linking only some libraries

gcc objectfiles -o program -Wl,-Bstatic -ls1 -ls2 -Wl,-Bdynamic -ld1 -ld2

you can also use: -static-libgcc -static-libstdc++ flags for gcc libraries

keep in mind that if libs1.so and libs1.a both exists, the linker will pick libs1.so if it's before -Wl,-Bstatic or after -Wl,-Bdynamic. Don't forget to pass -L/libs1-library-location/ before calling -ls1.

Cancel a UIView animation?

Use:

#import <QuartzCore/QuartzCore.h>

.......

[myView.layer removeAllAnimations];

PHP array: count or sizeof?

According to the website, sizeof() is an alias of count(), so they should be running the same code. Perhaps sizeof() has a little bit of overhead because it needs to resolve it to count()? It should be very minimal though.

Sort Array of object by object field in Angular 6

You can simply use Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

Working Example :

_x000D_
_x000D_
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
 _x000D_
 console.log(array);
_x000D_
_x000D_
_x000D_

Rails update_attributes without save?

For mass assignment of values to an ActiveRecord model without saving, use either the assign_attributes or attributes= methods. These methods are available in Rails 3 and newer. However, there are minor differences and version-related gotchas to be aware of.

Both methods follow this usage:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }

@user.attributes = { model: "Sierra", year: "2012", looks: "Sexy" }

Note that neither method will perform validations or execute callbacks; callbacks and validation will happen when save is called.

Rails 3

attributes= differs slightly from assign_attributes in Rails 3. attributes= will check that the argument passed to it is a Hash, and returns immediately if it is not; assign_attributes has no such Hash check. See the ActiveRecord Attribute Assignment API documentation for attributes=.

The following invalid code will silently fail by simply returning without setting the attributes:

@user.attributes = [ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ]

attributes= will silently behave as though the assignments were made successfully, when really, they were not.

This invalid code will raise an exception when assign_attributes tries to stringify the hash keys of the enclosing array:

@user.assign_attributes([ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ])

assign_attributes will raise a NoMethodError exception for stringify_keys, indicating that the first argument is not a Hash. The exception itself is not very informative about the actual cause, but the fact that an exception does occur is very important.

The only difference between these cases is the method used for mass assignment: attributes= silently succeeds, and assign_attributes raises an exception to inform that an error has occurred.

These examples may seem contrived, and they are to a degree, but this type of error can easily occur when converting data from an API, or even just using a series of data transformation and forgetting to Hash[] the results of the final .map. Maintain some code 50 lines above and 3 functions removed from your attribute assignment, and you've got a recipe for failure.

The lesson with Rails 3 is this: always use assign_attributes instead of attributes=.

Rails 4

In Rails 4, attributes= is simply an alias to assign_attributes. See the ActiveRecord Attribute Assignment API documentation for attributes=.

With Rails 4, either method may be used interchangeably. Failure to pass a Hash as the first argument will result in a very helpful exception: ArgumentError: When assigning attributes, you must pass a hash as an argument.

Validations

If you're pre-flighting assignments in preparation to a save, you might be interested in validating before save, as well. You can use the valid? and invalid? methods for this. Both return boolean values. valid? returns true if the unsaved model passes all validations or false if it does not. invalid? is simply the inverse of valid?

valid? can be used like this:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }.valid?

This will give you the ability to handle any validations issues in advance of calling save.

How to use placeholder as default value in select2 framework

The simplest way to add empty "option" before all.

<option></option>

Example:

<select class="select2" lang="ru" tabindex="-1">
    <option></option>
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
</select>

Also js code, if you need:

$(document).ready(function() {
    $(".select2").select2({
            placeholder: "Select a state",
            allowClear: true
        });
    });
}

Floating Div Over An Image

Change your positioning a bit:

.container {
    border: 1px solid #DDDDDD;
    width: 200px;
    height: 200px;
    position:relative;
}
.tag {
    float: left;
    position: absolute;
    left: 0px;
    top: 0px;
    background-color: green;
}

jsFiddle example

You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

Is it possible to ignore one single specific line with Pylint?

Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:

If the message is "No name ... in module ...", use the search:

No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers

Or, to get fewer results:

"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers

GitHub will show you:

"E0611": (
    "No name %r in module %r",
    "no-name-in-module",
    "Used when a name cannot be found in a module.",

You can then do:

from collections import Sequence # pylint: disable=no-name-in-module

CSS: transition opacity on mouse-out?

I managed to find a solution using css/jQuery that I'm comfortable with. The original issue: I had to force the visibility to be shown while animating as I have elements hanging outside the area. Doing so, made large blocks of text now hang outside the content area during animation as well.

The solution was to start the main text elements with an opacity of 0 and use addClass to inject and transition to an opacity of 1. Then removeClass when clicked on again.

I'm sure there's an all jQquery way to do this. I'm just not the guy to do it. :)

So in it's most basic form...

.slideDown().addClass("load");
.slideUp().removeClass("load");

Thanks for the help everyone.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Pass multiple complex objects to a post/put Web API method

Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class.

HttpClient.PostAsJsonAsync("http://Server/WebService/Controller/ServiceMethod?number=" + number + "&name" + name, Tuple.Create(args1, args2, args3, args4));

[HttpPost]
[Route("ServiceMethod")]
[ResponseType(typeof(void))]
public IHttpActionResult ServiceMethod(int number, string name, Tuple<Class1, Class2, Class3, Class4> args)
{
    Class1 c1 = (Class1)args.Item1;
    Class2 c2 = (Class2)args.Item2;
    Class3 c3 = (Class3)args.Item3;
    Class4 c4 = (Class4)args.Item4;
    /* do your actions */
    return Ok();
}

No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.

How do I pre-populate a jQuery Datepicker textbox with today's date?

You've got 2 options:

OPTION A) Marks as "active" in your calendar, only when you click in the input.

Js:

$('input.datepicker').datepicker(
                        {   
                            changeMonth: false,
                            changeYear: false,
                            beforeShow: function(input, instance) { 
                                $(input).datepicker('setDate', new Date());
                            }
                        }                         
                     );

Css:

div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,
        div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active  {
            background: #1ABC9C;
            border-radius: 50%;
            color: #fff;
            cursor: pointer;
            display: inline-block;
            width: 24px; height: 24px;
        }?

OPTION B) Input by default with today. You've to populate first the datepicker .

$("input.datepicker").datepicker().datepicker("setDate", new Date());

Get file version in PowerShell

This is based on the other answers, but is exactly what I was after:

(Get-Command C:\Path\YourFile.Dll).FileVersionInfo.FileVersion

Meaning of 'const' last in a function declaration of a class?

when you use const in the method signature (like your said: const char* foo() const;) you are telling the compiler that memory pointed to by this can't be changed by this method (which is foo here).

Sleep for milliseconds

In C++11, you can do this with standard library facilities:

#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));

Clear and readable, no more need to guess at what units the sleep() function takes.

While variable is not defined - wait

I prefer something simple like this:

function waitFor(variable, callback) {
  var interval = setInterval(function() {
    if (window[variable]) {
      clearInterval(interval);
      callback();
    }
  }, 200);
}

And then to use it with your example variable of someVariable:

waitFor('someVariable', function() {
  // do something here now that someVariable is defined
});

Note that there are various tweaks you can do. In the above setInterval call, I've passed 200 as how often the interval function should run. There is also an inherent delay of that amount of time (~200ms) before the variable is checked for -- in some cases, it's nice to check for it right away so there is no delay.

Reverse ip, find domain names on ip address

From about section of Reverse IP Domain Check tool on yougetsignal:

A reverse IP domain check takes a domain name or IP address pointing to a web server and searches for other sites known to be hosted on that same web server. Data is gathered from search engine results, which are not guaranteed to be complete.

How can I compare two ordered lists in python?

Just use the classic == operator:

>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False

Lists are equal if elements at the same index are equal. Ordering is taken into account then.

Django: How can I call a view function from template?

Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.

inside templateHTML.html:

<form action="#" method="get">
 <input type="text" value="8" name="mytextbox" size="1"/>
 <input type="submit" class="btn" value="Click" name="mybtn">
</form>

inside view.py:

import mypythoncode

def request_page(request):
  if(request.GET.get('mybtn')):
    mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')

PHP function to generate v4 UUID

$uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));

Batch file to perform start, run, %TEMP% and delete all

The following batch commands are used to delete all your temp, recent and prefetch files on your System.

Save the following code as "Clear.bat" on your local system

*********START CODE************

@ECHO OFF

del /s /f /q %userprofile%\Recent\*.*

del /s /f /q C:\Windows\Prefetch\*.*

del /s /f /q C:\Windows\Temp\*.*

del /s /f /q %USERPROFILE%\appdata\local\temp\*.*


/Below command to Show the folder after deleted files

Explorer %userprofile%\Recent

Explorer C:\Windows\Prefetch

Explorer C:\Windows\Temp

Explorer %USERPROFILE%\appdata\local\temp


*********END CODE************

Escape a string in SQL Server so that it is safe to use in LIKE expression

To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)

For example this escapes the % symbol, using \ as the escape char:

select * from table where myfield like '%15\% off%' ESCAPE '\'

If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:

set @myString = replace( 
                replace( 
                replace( 
                replace( @myString
                ,    '\', '\\' )
                ,    '%', '\%' )
                ,    '_', '\_' )
                ,    '[', '\[' )

(Note that you have to escape your escape char too, and make sure that's the inner replace so you don't escape the ones added from the other replace statements). Then you can use something like this:

select * from table where myfield like '%' + @myString + '%' ESCAPE '\'

Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.

Correct use for angular-translate in controllers

Actually, you should use the translate directive for such stuff instead.

<h1 translate="{{pageTitle}}"></h1>

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

However, if there's no way around and you really have to use $translate service in the controller, you should wrap the call in a $translateChangeSuccess event using $rootScope in combination with $translate.instant() like this:

.controller('foo', function ($rootScope, $scope, $translate) {
  $rootScope.$on('$translateChangeSuccess', function () {
    $scope.pageTitle = $translate.instant('PAGE.TITLE');
  });
})

So why $rootScope and not $scope? The reason for that is, that in angular-translate's events are $emited on $rootScope rather than $broadcasted on $scope because we don't need to broadcast through the entire scope hierarchy.

Why $translate.instant() and not just async $translate()? When $translateChangeSuccess event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant() which is synchronous and just assumes that translations are available.

Since version 2.8.0 there is also $translate.onReady(), which returns a promise that is resolved as soon as translations are ready. See the changelog.

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

Git push error: "origin does not appear to be a git repository"

I had this problem cause i had already origin remote defined locally. So just change "origin" into another name:

git remote add originNew https://github.com/UAwebM...

git push -u originNew

or u can remove your local origin. to check your remote name type:

git remote

to remove remote - log in your clone repository and type:

git remote remove origin(depending on your remote's name)

How to generate all permutations of a list?

One can indeed iterate over the first element of each permutation, as in tzwenn's answer. It is however more efficient to write this solution this way:

def all_perms(elements):
    if len(elements) <= 1:
        yield elements  # Only permutation possible = no permutation
    else:
        # Iteration over the first element in the result permutation:
        for (index, first_elmt) in enumerate(elements):
            other_elmts = elements[:index]+elements[index+1:]
            for permutation in all_perms(other_elmts): 
                yield [first_elmt] + permutation

This solution is about 30 % faster, apparently thanks to the recursion ending at len(elements) <= 1 instead of 0. It is also much more memory-efficient, as it uses a generator function (through yield), like in Riccardo Reyes's solution.

Using setattr() in python

The Python docs say all that needs to be said, as far as I can see.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

If this isn't enough, explain what you don't understand.

Non-invocable member cannot be used like a method?

Where you've written "OffenceBox.Text()", you need to replace this with "OffenceBox.Text". It's a property, not a method - the clue's in the error!

Adding a new entry to the PATH variable in ZSH

Here, add this line to .zshrc:

export PATH=/home/david/pear/bin:$PATH

EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH. This approach is standard for bash, but as far as I know, there is no reason to use it when ZSH provides better alternatives.

Regex to check with starts with http://, https:// or ftp://

I think the regex / string parsing solutions are great, but for this particular context, it seems like it would make sense just to use java's url parser:

https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

Taken from that page:

import java.net.*;
import java.io.*;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("authority = " + aURL.getAuthority());
        System.out.println("host = " + aURL.getHost());
        System.out.println("port = " + aURL.getPort());
        System.out.println("path = " + aURL.getPath());
        System.out.println("query = " + aURL.getQuery());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("ref = " + aURL.getRef());
    }
}

yields the following:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

Display only date and no time

If you have a for loop such as the one below.

Change @item.StartDate to @item.StartDate.Value.ToShortDateString()

This will remove the time just in case you can't annotate your property in the model like in my case.

<table>
  <tr>
   <th>Type</th>
   <th>Start Date</th>
  </tr>
    @foreach (var item in Model.TestList) {
      <tr>
        <td>@item.TypeName</td>
        <td>@item.StartDate.Value.ToShortDateString()</td>
      </tr>
      }
</table>

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

Bring a window to the front in WPF

I have found a solution that brings the window to the top, but it behaves as a normal window:

if (!Window.IsVisible)
{
    Window.Show();
}

if (Window.WindowState == WindowState.Minimized)
{
    Window.WindowState = WindowState.Normal;
}

Window.Activate();
Window.Topmost = true;  // important
Window.Topmost = false; // important
Window.Focus();         // important

Why should we include ttf, eot, woff, svg,... in a font-face

WOFF 2.0, based on the Brotli compression algorithm and other improvements over WOFF 1.0 giving more than 30 % reduction in file size, is supported in Chrome, Opera, and Firefox.

http://en.wikipedia.org/wiki/Web_Open_Font_Format http://en.wikipedia.org/wiki/Brotli

http://sth.name/2014/09/03/Speed-up-webfonts/ has an example on how to use it.

Basically you add a src url to the woff2 file and specify the woff2 format. It is important to have this before the woff-format: the browser will use the first format that it supports.

Merge a Branch into Trunk

If your working directory points to the trunk, then you should be able to merge your branch with:

svn merge https://HOST/repository/branches/branch_1

be sure to be to issue this command in the root directory of your trunk

update to python 3.7 using anaconda

This can be installed via conda with the command conda install -c anaconda python=3.7 as per https://anaconda.org/anaconda/python.

Though not all packages support 3.7 yet, running conda update --all may resolve some dependency failures.

Squaring all elements in a list

import numpy as np
a = [2 ,3, 4]
np.square(a)

Github Windows 'Failed to sync this branch'

One more thing that can cause this is when you map a network drive or connect a VHD after GitHub Desktop has already been started. The reason for this is that GitHub Desktop uses ssh-agent from the portable GIT install to establish connections, and never closes it... even if you uninstall the application. The process starts with no knowledge of the new drive and never refreshes itself, and when it is used to run the GIT commands to work on your repo it fails because it doesn't understand the paths.

The solution in this instance is to close GitHub Desktop and use Task Manager to terminate the running ssh-agent before starting it again. This will start a new instance of ssh-agent when needed which will pick up the new drive mappings, etc.

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

adding to scotty's answer:

Option 1: Either include this in your JS file:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

Option 2: or just use the URL to download 'angular-route.min.js' to your local.

and then (whatever option you choose) add this 'ngRoute' as dependency.

explained: var app = angular.module('myapp', ['ngRoute']);

Cheers!!!

a href link for entire div in HTML/CSS

Two things you can do:

  1. Change #childdivimage to a span element, and change #parentdivimage to an anchor tag. This may require you to add some more styling to get things looking perfect. This is preffered, since it uses semantic markup, and does not rely on javascript.

  2. Use Javascript to bind a click event to #parentdivimage. You must redirect the browser window by modifying window.location inside this event. This is TheEasyWayTM, but will not degrade gracefully.

async/await - when to return a Task vs void?

My answer is simple you can not await void method

Error   CS4008  Cannot await 'void' TestAsync   e:\test\TestAsync\TestAsyncProgram.cs

So if the method is async it is better to be awaitable, because you can loose async advantage.

JavaScript - Use variable in string match

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g');
xxx.match(re);

Any flags you need (such as /g) can go into the second parameter.

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

In Python, when to use a Dictionary, List or Set?

In combination with lists, dicts and sets, there are also another interesting python objects, OrderedDicts.

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

OrderedDicts could be useful when you need to preserve the order of the keys, for example working with documents: It's common to need the vector representation of all terms in a document. So using OrderedDicts you can efficiently verify if a term has been read before, add terms, extract terms, and after all the manipulations you can extract the ordered vector representation of them.

"Could not find a version that satisfies the requirement opencv-python"

I had the same error. The first time I used the 32-bit version of python but my computer is 64-bit. I then reinstalled the 64-bit version and succeeded.

An unhandled exception occurred during the execution of the current web request. ASP.NET

I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.

Also, you should try this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

Authorize a non-admin developer in Xcode / Mac OS

Ned Deily's solution works perfectly fine, provided your user is allowed to sudo.

If he's not, you can su to an admin account, then use his dscl . append /Groups/_developer GroupMembership $user, where $user is the username.

However, I mistakenly thought it did not because I wrongly typed in the user's name in the command and it silently fails.

Therefore, after entering this command, you should proof-check it. This will check if $user is in $group, where the variables represent respectively the user name and the group name.

dsmemberutil checkmembership -U $user -G $group

This command will either print the message user is not a member of the group or user is a member of the group.

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

ORACLE convert number to string

Using the FM format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.. You can use rtrim to get rid of that:

select to_char(a, '99D90'),
    to_char(a, '90D90'),
    to_char(a, 'FM90D99'),
    rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
    select 50 a from dual
    union all select 50.57 from dual
    union all select 5.57 from dual
    union all select 0.35 from dual
    union all select 0.4 from dual
)
order by a;

TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
   .35   0.35 0.35   0.35
   .40   0.40 0.4    0.4
  5.57   5.57 5.57   5.57
 50.00  50.00 50.    50
 50.57  50.57 50.57  50.57

Note that I'm using to_char(0, 'D') to generate the character to trim, to match the decimal separator - so it looks for the same character, , or ., as the first to_char adds.

The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad, which starts to make it look a bit complicated:

...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...

TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
   .35   0.35 0.35   0.35     0.35
   .40   0.40 0.4    0.4       0.4
  5.57   5.57 5.57   5.57     5.57
 50.00  50.00 50.    50         50
 50.57  50.57 50.57  50.57   50.57

Is there a way to ignore a single FindBugs warning?

Update Gradle

dependencies {
    compile group: 'findbugs', name: 'findbugs', version: '1.0.0'
}

Locate the FindBugs Report

file:///Users/your_user/IdeaProjects/projectname/build/reports/findbugs/main.html

Find the specific message

find bugs

Import the correct version of the annotation

import edu.umd.cs.findbugs.annotations.SuppressWarnings;

Add the annotation directly above the offending code

@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX")

See here for more info: findbugs Spring Annotation

How to detect if a string contains at least a number?

Use this:

SELECT * FROM Table WHERE Column LIKE '%[0-9]%'

MSDN - LIKE (Transact-SQL)

How to compare two double values in Java?

Instead of using doubles for decimal arithemetic, please use java.math.BigDecimal. It would produce the expected results.

For reference take a look at this stackoverflow question

How to make an AJAX call without jQuery?

<html>
  <script>
    var xmlDoc = null ;

  function load() {
    if (typeof window.ActiveXObject != 'undefined' ) {
      xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
      xmlDoc.onreadystatechange = process ;
    }
    else {
      xmlDoc = new XMLHttpRequest();
      xmlDoc.onload = process ;
    }
    xmlDoc.open( "GET", "background.html", true );
    xmlDoc.send( null );
  }

  function process() {
    if ( xmlDoc.readyState != 4 ) return ;
    document.getElementById("output").value = xmlDoc.responseText ;
  }

  function empty() {
    document.getElementById("output").value = '<empty>' ;
  }
</script>

<body>
  <textarea id="output" cols='70' rows='40'><empty></textarea>
  <br></br>
  <button onclick="load()">Load</button> &nbsp;
  <button onclick="empty()">Clear</button>
</body>
</html>

Change jsp on button click

Just use two forms.

In the first form action attribute will have name of the second jdp page and your 1st button. In the second form there will be 2nd button with action attribute thats giving the name of your 3rd jsp page.

It will be like this :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form name="main1"  method="get" action="2nd.jsp">
        <input type="submit" name="ter" value="LOGOUT" >
    </form>
    <DIV ALIGN="left"><form name="main0" action="3rd.jsp" method="get">
        <input type="submit" value="FEEDBACK">
    </form></DIV>
</body>
</html>

jQuery access input hidden value

You can access hidden fields' values with val(), just like you can do on any other input element:

<input type="hidden" id="foo" name="zyx" value="bar" />

alert($('input#foo').val());
alert($('input[name=zyx]').val());
alert($('input[type=hidden]').val());
alert($(':hidden#foo').val());
alert($('input:hidden[name=zyx]').val());

Those all mean the same thing in this example.

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Reading/writing an INI file

I found this simple implementation:

http://bytes.com/topic/net/insights/797169-reading-parsing-ini-file-c

Works well for what I need.

Here is how you use it:

public class TestParser
{
    public static void Main()
    {
        IniParser parser = new IniParser(@"C:\test.ini");

        String newMessage;

        newMessage = parser.GetSetting("appsettings", "msgpart1");
        newMessage += parser.GetSetting("appsettings", "msgpart2");
        newMessage += parser.GetSetting("punctuation", "ex");

        //Returns "Hello World!"
        Console.WriteLine(newMessage);
        Console.ReadLine();
    }
}

Here is the code:

using System;
using System.IO;
using System.Collections;

public class IniParser
{
    private Hashtable keyPairs = new Hashtable();
    private String iniFilePath;

    private struct SectionPair
    {
        public String Section;
        public String Key;
    }

    /// <summary>
    /// Opens the INI file at the given path and enumerates the values in the IniParser.
    /// </summary>
    /// <param name="iniPath">Full path to INI file.</param>
    public IniParser(String iniPath)
    {
        TextReader iniFile = null;
        String strLine = null;
        String currentRoot = null;
        String[] keyPair = null;

        iniFilePath = iniPath;

        if (File.Exists(iniPath))
        {
            try
            {
                iniFile = new StreamReader(iniPath);

                strLine = iniFile.ReadLine();

                while (strLine != null)
                {
                    strLine = strLine.Trim().ToUpper();

                    if (strLine != "")
                    {
                        if (strLine.StartsWith("[") && strLine.EndsWith("]"))
                        {
                            currentRoot = strLine.Substring(1, strLine.Length - 2);
                        }
                        else
                        {
                            keyPair = strLine.Split(new char[] { '=' }, 2);

                            SectionPair sectionPair;
                            String value = null;

                            if (currentRoot == null)
                                currentRoot = "ROOT";

                            sectionPair.Section = currentRoot;
                            sectionPair.Key = keyPair[0];

                            if (keyPair.Length > 1)
                                value = keyPair[1];

                            keyPairs.Add(sectionPair, value);
                        }
                    }

                    strLine = iniFile.ReadLine();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (iniFile != null)
                    iniFile.Close();
            }
        }
        else
            throw new FileNotFoundException("Unable to locate " + iniPath);

    }

    /// <summary>
    /// Returns the value for the given section, key pair.
    /// </summary>
    /// <param name="sectionName">Section name.</param>
    /// <param name="settingName">Key name.</param>
    public String GetSetting(String sectionName, String settingName)
    {
        SectionPair sectionPair;
        sectionPair.Section = sectionName.ToUpper();
        sectionPair.Key = settingName.ToUpper();

        return (String)keyPairs[sectionPair];
    }

    /// <summary>
    /// Enumerates all lines for given section.
    /// </summary>
    /// <param name="sectionName">Section to enum.</param>
    public String[] EnumSection(String sectionName)
    {
        ArrayList tmpArray = new ArrayList();

        foreach (SectionPair pair in keyPairs.Keys)
        {
            if (pair.Section == sectionName.ToUpper())
                tmpArray.Add(pair.Key);
        }

        return (String[])tmpArray.ToArray(typeof(String));
    }

    /// <summary>
    /// Adds or replaces a setting to the table to be saved.
    /// </summary>
    /// <param name="sectionName">Section to add under.</param>
    /// <param name="settingName">Key name to add.</param>
    /// <param name="settingValue">Value of key.</param>
    public void AddSetting(String sectionName, String settingName, String settingValue)
    {
        SectionPair sectionPair;
        sectionPair.Section = sectionName.ToUpper();
        sectionPair.Key = settingName.ToUpper();

        if (keyPairs.ContainsKey(sectionPair))
            keyPairs.Remove(sectionPair);

        keyPairs.Add(sectionPair, settingValue);
    }

    /// <summary>
    /// Adds or replaces a setting to the table to be saved with a null value.
    /// </summary>
    /// <param name="sectionName">Section to add under.</param>
    /// <param name="settingName">Key name to add.</param>
    public void AddSetting(String sectionName, String settingName)
    {
        AddSetting(sectionName, settingName, null);
    }

    /// <summary>
    /// Remove a setting.
    /// </summary>
    /// <param name="sectionName">Section to add under.</param>
    /// <param name="settingName">Key name to add.</param>
    public void DeleteSetting(String sectionName, String settingName)
    {
        SectionPair sectionPair;
        sectionPair.Section = sectionName.ToUpper();
        sectionPair.Key = settingName.ToUpper();

        if (keyPairs.ContainsKey(sectionPair))
            keyPairs.Remove(sectionPair);
    }

    /// <summary>
    /// Save settings to new file.
    /// </summary>
    /// <param name="newFilePath">New file path.</param>
    public void SaveSettings(String newFilePath)
    {
        ArrayList sections = new ArrayList();
        String tmpValue = "";
        String strToSave = "";

        foreach (SectionPair sectionPair in keyPairs.Keys)
        {
            if (!sections.Contains(sectionPair.Section))
                sections.Add(sectionPair.Section);
        }

        foreach (String section in sections)
        {
            strToSave += ("[" + section + "]\r\n");

            foreach (SectionPair sectionPair in keyPairs.Keys)
            {
                if (sectionPair.Section == section)
                {
                    tmpValue = (String)keyPairs[sectionPair];

                    if (tmpValue != null)
                        tmpValue = "=" + tmpValue;

                    strToSave += (sectionPair.Key + tmpValue + "\r\n");
                }
            }

            strToSave += "\r\n";
        }

        try
        {
            TextWriter tw = new StreamWriter(newFilePath);
            tw.Write(strToSave);
            tw.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// Save settings back to ini file.
    /// </summary>
    public void SaveSettings()
    {
        SaveSettings(iniFilePath);
    }
}

JavaScript and getElementById for multiple elements with the same ID

I know this is an old question and that an HTML page with multiple IDs is invalid. However, I ran into this issues while needing to scrape and reformat someone else's API's HTML documentation that contained duplicate IDs (invalid HTML).

So for anyone else, here is the code I used to work around the issue using querySelectorAll:

var elms = document.querySelectorAll("[id='duplicateID']");

for(var i = 0; i < elms.length; i++) 
  elms[i].style.display='none'; // <-- whatever you need to do here.

How to list all available Kafka brokers in a cluster?

If you are using new version of Kafka e.g. 5.3.3, you can use

kafka-broker-api-versions  --bootstrap-server BROKER | grep 9092

You just need to pass one of the brokers

Returning a C string from a function

You can create the array in the caller, which is the main function, and pass the array to the callee which is your myFunction(). Thus myFunction can fill the string into the array. However, you need to declare myFunction() as

char* myFunction(char * buf, int buf_len){
  strncpy(buf, "my string", buf_len);
  return buf;
}

And in main function, myFunction should be called in this way:

char array[51];
memset(array, 0, 51); /* All bytes are set to '\0' */
printf("%s", myFunction(array, 50)); /* The buf_len argument  is 50, not 51. This is to make sure the string in buf is always null-terminated (array[50] is always '\0') */

However, a pointer is still used.

How do I make a textbox that only accepts numbers?

I am assuming from context and the tags you used that you are writing a .NET C# app. In this case, you can subscribe to the text changed event, and validate each key stroke.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
    {
        MessageBox.Show("Please enter only numbers.");
        textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
    }
}

Java integer to byte array

How about:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

The idea is not mine. I've taken it from some post on dzone.com.

Padding between ActionBar's home icon and title

this work for me to add padding to the title and for ActionBar icon i have set that programmatically.

 getActionBar().setTitle(Html.fromHtml("<font color='#fffff'>&nbsp;&nbsp;&nbsp;Boat App </font>"));

Environment variables in Eclipse

You can also start eclipse within a shell.

You export the enronment, before calling eclipse.

Example :

#!/bin/bash
export MY_VAR="ADCA"
export PATH="/home/lala/bin;$PATH"
$ECLIPSE_HOME/eclipse -data $YOUR_WORK_SPACE_PATH

Then you can have multiple instances on eclipse with their own custome environment including workspace.

Python `if x is not None` or `if not x is None`?

if not x is None is more similar to other programming languages, but if x is not None definitely sounds more clear (and is more grammatically correct in English) to me.

That said it seems like it's more of a preference thing to me.

Error: unmappable character for encoding UTF8 during maven compilation

Set incodign attribute in maven-compiler plugin work for me. The code example is the following

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <encoding>UTF-8</encoding>
    </configuration>
</plugin>

C# catch a stack overflow exception

You can't. The CLR won't let you. A stack overflow is a fatal error and can't be recovered from.

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

How to convert file to base64 in JavaScript?

TypeScript version

const file2Base64 = (file:File):Promise<string> => {
    return new Promise<string> ((resolve,reject)=> {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result.toString());
         reader.onerror = error => reject(error);
     })
    }

use regular expression in if-condition in bash

@OP,

Is glob pettern not only used for file names?

No, "glob" pattern is not only used for file names. you an use it to compare strings as well. In your examples, you can use case/esac to look for strings patterns.

 gg=svm-grid-ch 
 # looking for the word "grid" in the string $gg
 case "$gg" in
    *grid* ) echo "found";;
 esac

 # [[ $gg =~ ^....grid* ]]
 case "$gg" in ????grid*) echo "found";; esac 

 # [[ $gg =~ s...grid* ]]
 case "$gg" in s???grid*) echo "found";; esac

In bash, when to use glob pattern and when to use regular expression? Thanks!

Regex are more versatile and "convenient" than "glob patterns", however unless you are doing complex tasks that "globbing/extended globbing" cannot provide easily, then there's no need to use regex. Regex are not supported for version of bash <3.2 (as dennis mentioned), but you can still use extended globbing (by setting extglob ). for extended globbing, see here and some simple examples here.

Update for OP: Example to find files that start with 2 characters (the dots "." means 1 char) followed by "g" using regex

eg output

$ shopt -s dotglob
$ ls -1 *
abg
degree
..g

$ for file in *; do [[ $file =~ "..g" ]] && echo $file ; done
abg
degree
..g

In the above, the files are matched because their names contain 2 characters followed by "g". (ie ..g).

The equivalent with globbing will be something like this: (look at reference for meaning of ? and * )

$ for file in ??g*; do echo $file; done
abg
degree
..g

best way to get folder and file list in Javascript

fs/promises and fs.Dirent

Here's an efficient, non-blocking ls program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist or fs.stat calls on every path -

// main.js
import { readdir } from "fs/promises"
import { join } from "path"

async function* ls (path = ".")
{ yield path
  for (const dirent of await readdir(path, { withFileTypes: true }))
    if (dirent.isDirectory())
      yield* ls(join(path, dirent.name))
    else
      yield join(path, dirent.name)
}

async function* empty () {}

async function toArray (iter = empty())
{ let r = []
  for await (const x of iter)
    r.push(x)
  return r
}

toArray(ls(".")).then(console.log, console.error)

Let's get some sample files so we can see ls working -

$ yarn add immutable     # (just some example package)
$ node main.js
[
  '.',
  'main.js',
  'node_modules',
  'node_modules/.yarn-integrity',
  'node_modules/immutable',
  'node_modules/immutable/LICENSE',
  'node_modules/immutable/README.md',
  'node_modules/immutable/contrib',
  'node_modules/immutable/contrib/cursor',
  'node_modules/immutable/contrib/cursor/README.md',
  'node_modules/immutable/contrib/cursor/__tests__',
  'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
  'node_modules/immutable/contrib/cursor/index.d.ts',
  'node_modules/immutable/contrib/cursor/index.js',
  'node_modules/immutable/dist',
  'node_modules/immutable/dist/immutable-nonambient.d.ts',
  'node_modules/immutable/dist/immutable.d.ts',
  'node_modules/immutable/dist/immutable.es.js',
  'node_modules/immutable/dist/immutable.js',
  'node_modules/immutable/dist/immutable.js.flow',
  'node_modules/immutable/dist/immutable.min.js',
  'node_modules/immutable/package.json',
  'package.json',
  'yarn.lock'
]

For added explanation and other ways to leverage async generators, see this Q&A.

What does 'foo' really mean?

Among my colleagues, the meaning (or perhaps more accurately - the use) of the term "foo" has been to serve as a placeholder to represent an example for a name. Examples include, but not limited to, yourVariableName, yourObjectName, or yourColumnName.

Today, I avoid using "foo" and prefer using this type of named substitution for a couple of reasons.

  • In my earlier days, I originally found the use of "foo" as a placement in any example to represent something as f'd-up to be confusing. I wanted a working example, not something that was foobar.
  • Your results may vary, but I always, 100%, everytime, never-failed, got more follow-up questions about the meaning of the actual variable where "foo" was used.

Convert JSONObject to Map

This is what worked for me:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonobj.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            Object value = jsonobj.get(key);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }   
            map.put(key, value);
        }   return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }
            else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }   return list;
}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java

enable cors in .htaccess

Will be work 100%, Apply in .htaccess:

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

Best way to track onchange as-you-type in input type="text"?

These days listen for oninput. It feels like onchange without the need to lose focus on the element. It is HTML5.

It’s supported by everyone (even mobile), except IE8 and below. For IE add onpropertychange. I use it like this:

_x000D_
_x000D_
const source = document.getElementById('source');_x000D_
const result = document.getElementById('result');_x000D_
_x000D_
const inputHandler = function(e) {_x000D_
  result.innerHTML = e.target.value;_x000D_
}_x000D_
_x000D_
source.addEventListener('input', inputHandler);_x000D_
source.addEventListener('propertychange', inputHandler); // for IE8_x000D_
// Firefox/Edge18-/IE9+ don’t fire on <select><option>_x000D_
// source.addEventListener('change', inputHandler); 
_x000D_
<input id="source">_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

What is the most efficient way to store tags in a database?

If you don't mind using a bit of non-standard stuff, Postgres version 9.4 and up has an option of storing a record of type JSON text array.

Your schema would be:

Table: Items
Columns: Item_ID:int, Title:text, Content:text

Table: Tags
Columns: Item_ID:int, Tag_Title:text[]

For more info, see this excellent post by Josh Berkus: http://www.databasesoup.com/2015/01/tag-all-things.html

There are more various options compared thoroughly for performance and the one suggested above is the best overall.

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

How to add title to seaborn boxplot

Try adding this at the end of your code:

import matplotlib.pyplot as plt

plt.title('add title here')

Why can I not switch branches?

Try this if you don't want any of the merges listed in git status:

git reset --merge

This resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).

If a file that is different between <commit> and the index has unstaged changes -- reset is aborted.

More about this - https://www.techpurohit.com/list-some-useful-git-commands & Doc link - https://git-scm.com/docs/git-reset

Visualizing branch topology in Git

Tortoise Git has a tool called "Revision Graph". If you're on Windows it's as easy as right click on your repo --> Tortoise Git --> Revision Graph.

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

If you look at characters a-z, you'll see that all of them have the 6th bit is set to 1. Where in A-Z 6th bit is not set.

A = 1000001    a = 1100001
B = 1000010    b = 1100010
C = 1000011    c = 1100011
D = 1000100    d = 1100100     
...
Z = 1011010    z = 1111010

So all we need to do is to iterate through each character from a given string and then do XOR(^) with 32. In this way, the 6th bit can swap.

Look at the below code for simply changing the string case without using any if-else conditions.

public final class ChangeStringCase {
    public static void main(String[] args) {
        String str = "Hello World";
        for (int i = 0; i < str.length(); i++) {
            char ans = (char)(str.charAt(i) ^ 32);
            System.out.print(ans); // Final Output: hELLO wORLD
        }
    }
}

Time Complexity: O(N) where N = Length of the string.

Space Complexity: O(1)

My docker container has no internet

I also encountered such an issue while trying to set up a project using Docker-Compose on Ubuntu.

The Docker had no access to internet at all, when I tried to ping any IP address or nslookup some URL - it failed all the time.

I tried all the possible solutions with DNS resolution described above to no avail.

I spent the whole day trying to find out what the heck is going on, and finally found out that the cause of all the trouble was the antivirus, in particular it's firewall which for some reason blocked Docker from getting the IP address and port.

When I disabled it - everything worked fine.

So, if you have an antivirus installed and nothing helps fix the issue - the problem could be the firewall of the antivirus.

What are the advantages and disadvantages of recursion?

Recursion gets a bad rep, I'm always surprised by the number of developers that wont even touch recursion because someone told them it was evil incarnate.

I've learned through trial and error that when done properly recursion can be one of the fastest ways to iterate over something, it is not a steadfast rule and each language/ compiler/ engine has it's own quirks so mileage will vary.

In javascript I can reliably speed up almost any iterative process by introducing recursion with the added benefit of reducing side effects and making the code more clear concise and reusable. Also pro tip its possible to get around the stack overflow issue (and no you dont disable the warning).

My personal Pros & Cons:

Pros:

- Reduces side effects.
- Makes code more concise and easier to reason about.
- Reduces system resource usage and performs better than the traditional for loop.

Cons:

- Can lead to stack overflow.
- More complicated to setup than a traditional for loop.

Mileage will vary depending on language/ complier/ engine.

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this

 $(function(){
   $("input[type='number']").prop('min',1);
   $("input[type='number']").prop('max',10);
});

Demo

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

This problem may occur because your MySQL server is not installed and running. To do that start command prompt as admin and enter command:

"C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin\mysqld" --install

If you get "service successfully installed" message then you need to start the MySQL service. To do that: go to Services window (Task Manager -> Services -> Open Services) Search for MySQL and Start it from the top navigation bar. Then if try to open mysql.exe it will work.

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

Java :Add scroll into text area

After adding JTextArea into JScrollPane here:

scroll = new JScrollPane(display);

You don't need to add it again into other container like you do:

middlePanel.add(display);

Just remove that last line of code and it will work fine. Like this:

    middlePanel=new JPanel();
    middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));

    // create the middle panel components

    display = new JTextArea(16, 58);
    display.setEditable(false); // set textArea non-editable
    scroll = new JScrollPane(display);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    //Add Textarea in to middle panel
    middlePanel.add(scroll);

JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:

new JScrollPane( myComponent ) 

or set view like this:

JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );

Additional:

Here is fully working example since you still did not get it working:

public static void main ( String[] args )
{
    JPanel middlePanel = new JPanel ();
    middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

    // create the middle panel components

    JTextArea display = new JTextArea ( 16, 58 );
    display.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane ( display );
    scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

    //Add Textarea in to middle panel
    middlePanel.add ( scroll );

    // My code
    JFrame frame = new JFrame ();
    frame.add ( middlePanel );
    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}

And here is what you get: enter image description here

How to check if a character is upper-case in Python?

words = x.split("_")
for word in words:
    if word[0] == word[0].upper() and word[1:] == word[1:].lower():
        print word, "is conformant"
    else:
        print word, "is non conformant"

Python - 'ascii' codec can't decode byte

In case you're dealing with Unicode, sometimes instead of encode('utf-8'), you can also try to ignore the special characters, e.g.

"??".encode('ascii','ignore')

or as something.decode('unicode_escape').encode('ascii','ignore') as suggested here.

Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.

Alternatively you can consider replacing particular character using replace().

Laravel-5 'LIKE' equivalent (Eloquent)

I have scopes for this, hope it help somebody. https://laravel.com/docs/master/eloquent#local-scopes

public function scopeWhereLike($query, $column, $value)
{
    return $query->where($column, 'like', '%'.$value.'%');
}

public function scopeOrWhereLike($query, $column, $value)
{
    return $query->orWhere($column, 'like', '%'.$value.'%');
}

Usage:

$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();

Create a date from day month and year with T-SQL

Try CONVERT instead of CAST.

CONVERT allows a third parameter indicating the date format.

List of formats is here: http://msdn.microsoft.com/en-us/library/ms187928.aspx

Update after another answer has been selected as the "correct" answer:

I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.

Custom "confirm" dialog in JavaScript?

You might want to consider abstracting it out into a function like this:

function dialog(message, yesCallback, noCallback) {
    $('.title').html(message);
    var dialog = $('#modal_dialog').dialog();

    $('#btnYes').click(function() {
        dialog.dialog('close');
        yesCallback();
    });
    $('#btnNo').click(function() {
        dialog.dialog('close');
        noCallback();
    });
}

You can then use it like this:

dialog('Are you sure you want to do this?',
    function() {
        // Do something
    },
    function() {
        // Do something else
    }
);

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

python getoutput() equivalent in subprocess

To catch errors with subprocess.check_output(), you can use CalledProcessError. If you want to use the output as string, decode it from the bytecode.

# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
    import subprocess
    try:
        byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
        return byteOutput.decode('UTF-8').rstrip()
    except subprocess.CalledProcessError as e:
        print("Error in ls -a:\n", e.output)
        return None

How can I check if PostgreSQL is installed or not via Linux script?

If it is debian based.

aptitude show postgresql | grep State

But I guess you can just try to launch it with some flag like --version, that simply prints some info and exits.

Updated using "service postgres status". Try:

service postgres status
if [ "$?" -gt "0" ]; then
  echo "Not installed".
else
  echo "Intalled"
fi

GitHub Error Message - Permission denied (publickey)

this worked for me:

1- remove all origins

git remote rm origin  

(cf. https://www.kernel.org/pub/software/scm/git/docs/git-remote.html)

*remote : "Manage the set of repositories ("remotes") whose branches you track.

*rm : "Remove the remote named . All remote-tracking branches and configuration settings for the remote are removed."

2- check all has been removed :

git remote -v  

3- add new origin master

git remote add origin [email protected]:YOUR-GIT/YOUR-REPO.git

that's all folks!

Generate war file from tomcat webapp folder

Create the war file in a different directory to where the content is otherwise the jar command might try to zip up the file it is creating.

#!/bin/bash

set -euo pipefail

war=app.war
src=contents

# Clean last war build
if [ -e ${war} ]; then
    echo "Removing old war ${war}"
    rm -rf ${war}
fi

# Build war
if [ -d ${src} ]; then
    echo "Found source at ${src}"
    cd ${src}
    jar -cvf ../${war} *
    cd ..
fi

# Show war details
ls -la ${war}

When to use async false and async true in ajax function in jquery

It is best practice to go asynchronous if you can do several things in parallel (no inter-dependencies). If you need it to complete to continue loading the next thing you could use synchronous, but note that this option is deprecated to avoid abuse of sync:

jQuery.ajax() method's async option deprecated, what now?

JavaScript calculate the day of the year (1 - 366)

This might be useful to those who need the day of the year as a string and have jQuery UI available.

You can use jQuery UI Datepicker:

day_of_year_string = $.datepicker.formatDate("o", new Date())

Underneath it works the same way as some of the answers already mentioned ((date_ms - first_date_of_year_ms) / ms_per_day):

function getDayOfTheYearFromDate(d) {
    return Math.round((new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() 
- new Date(d.getFullYear(), 0, 0).getTime()) / 86400000);
}

day_of_year_int = getDayOfTheYearFromDate(new Date())

Quick way to list all files in Amazon S3 bucket?

After zach I would also recommend boto, but I needed to make a slight difference to his code:

conn = boto.connect_s3('access-key', 'secret'key')
bucket = conn.lookup('bucket-name')
for key in bucket:
    print key.name

Anaconda Installed but Cannot Launch Navigator

This is what I did

  • Reinstall anacoda with ticked first check box
  • Remember to Restart

How to use table variable in a dynamic sql statement?

Well, I figured out the way and thought to share with the people out there who might run into the same problem.

Let me start with the problem I had been facing,

I had been trying to execute a Dynamic Sql Statement that used two temporary tables I declared at the top of my stored procedure, but because that dynamic sql statment created a new scope, I couldn't use the temporary tables.

Solution:

I simply changed them to Global Temporary Variables and they worked.

Find my stored procedure underneath.

CREATE PROCEDURE RAFCustom_Room_GetRelatedProducts
-- Add the parameters for the stored procedure here
@PRODUCT_SKU nvarchar(15) = Null

AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;

IF OBJECT_ID('tempdb..##RelPro', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##RelPro
END

Create Table ##RelPro
(
    RowID int identity(1,1),
    ID int,
    Item_Name nvarchar(max),
    SKU nvarchar(max),
    Vendor nvarchar(max),
    Product_Img_180 nvarchar(max),
    rpGroup int,
    Assoc_Item_1 nvarchar(max),
    Assoc_Item_2 nvarchar(max),
    Assoc_Item_3 nvarchar(max),
    Assoc_Item_4 nvarchar(max),
    Assoc_Item_5 nvarchar(max),
    Assoc_Item_6 nvarchar(max),
    Assoc_Item_7 nvarchar(max),
    Assoc_Item_8 nvarchar(max),
    Assoc_Item_9 nvarchar(max),
    Assoc_Item_10 nvarchar(max)
);

Begin
    Insert ##RelPro(ID, Item_Name, SKU, Vendor, Product_Img_180, rpGroup)

    Select distinct zp.ProductID, zp.Name, zp.SKU,
        (Select m.Name From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID),
        'http://s0001.server.com/is/sw11/DG/' + 
        (Select m.Custom1 From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID) +
        '_' + zp.SKU + '_3?$SC_3243$', ep.RoomID
    From Product zp(nolock) Inner Join RF_ExtendedProduct ep(nolock) On ep.ProductID = zp.ProductID
    Where zp.ActiveInd = 1 And SUBSTRING(zp.SKU, 1, 2) <> 'GC' AND zp.Name <> 'PLATINUM' AND zp.SKU = (Case When @PRODUCT_SKU Is Not Null Then @PRODUCT_SKU Else zp.SKU End)
End

declare @curr_row int = 0,
        @tot_rows int= 0,
        @sku nvarchar(15) = null;

IF OBJECT_ID('tempdb..##TSku', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##TSku
END
Create Table ##TSku (tid int identity(1,1), relsku nvarchar(15));

Select @curr_row = (Select MIN(RowId) From ##RelPro);
Select @tot_rows = (Select MAX(RowId) From ##RelPro);

while @curr_row <= @tot_rows
Begin
    select @sku = SKU from ##RelPro where RowID = @curr_row;

    truncate table ##TSku;

    Insert ##TSku(relsku)
    Select distinct top(10) tzp.SKU From Product tzp(nolock) INNER JOIN 
    [INTRANET].raf_FocusAssociatedItem assoc(nolock) ON assoc.associatedItemID = tzp.SKU
    Where (assoc.isActive=1) And (tzp.ActiveInd = 1) AND (assoc.productID = @sku)

    declare @curr_row1 int = (Select Min(tid) From ##TSku),
            @tot_rows1 int = (Select Max(tid) From ##TSku);

    If(@tot_rows1 <> 0)
    Begin
        While @curr_row1 <= @tot_rows1
        Begin
            declare @col_name nvarchar(15) = null,
                    @sqlstat nvarchar(500) = null;
            set @col_name =  'Assoc_Item_' + Convert(nvarchar(2), @curr_row1);
            set @sqlstat = 'update ##RelPro set ' + @col_name + ' = (Select relsku From ##TSku Where tid = ' + Convert(nvarchar(2), @curr_row1) + ') Where RowID = ' + Convert(nvarchar(2), @curr_row);
            Exec(@sqlstat);
            set @curr_row1 = @curr_row1 + 1;
        End
    End
    set @curr_row = @curr_row + 1;
End

Select * From ##RelPro;

END GO

How can one check to see if a remote file exists using PHP?

As Pies say you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.

Here is example:

function remoteFileExists($url) {
    $curl = curl_init($url);

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}

$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
    echo 'file exists';
} else {
    echo 'file does not exist';   
}

Comparing two NumPy arrays for equality, element-wise

(A==B).all()

test if all values of array (A==B) are True.

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

Special cases and alternatives (from dbaupp's answer and yoavram's comment)

It should be noted that:

  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values

How to create Gmail filter searching for text only at start of subject line?

I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:

Matches: subject:([test])
Do this: Skip Inbox

And then I sent a message with the subject

[test] foo

And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.

Where to find extensions installed folder for Google Chrome on Mac?

They are found on either one of the below locations depending on how chrome was installed

  • When chrome is installed at the user level, it's located at:

~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions

  • When installed at the root level, it's at:

/Library/Application\ Support/Google/Chrome/Default/Extensions

How do you remove all the options of a select box and then add one option and select it with jQuery?

Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including "selected" in the option that I wanted selected.

_x000D_
_x000D_
$(function() {_x000D_
  $('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected_x000D_
  $("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1_x000D_
  // Bind click event to each radio button._x000D_
  $("input[name='myRadio']").bind("click",_x000D_
                                  function() {_x000D_
    switch(this.value) {_x000D_
      case "1":_x000D_
        $('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;_x000D_
        break ;_x000D_
      case "2":_x000D_
        $('#mySelect').find('option').remove() ;_x000D_
        var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo_x000D_
        var options = '' ;_x000D_
        for (var i = 0; i < items.length; i++) {_x000D_
          if (i==0) {_x000D_
            options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';_x000D_
          }_x000D_
          else {_x000D_
            options += '<option value="' + items[i] + '">' + items[i] + '</option>';_x000D_
          }_x000D_
        }_x000D_
        $('#mySelect').html(options);   // Populate select box with array_x000D_
        break ;_x000D_
    } // Switch end_x000D_
  } // Bind function end_x000D_
                                 ); // bind end_x000D_
}); // Event listener end
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>One<input  name="myRadio" type="radio" value="1"  /></label>_x000D_
<label>Two<input name="myRadio"  type="radio" value="2" /></label>_x000D_
<select id="mySelect" size="9"></select>
_x000D_
_x000D_
_x000D_

Convert a list of characters into a string

This works in many popular languages like JavaScript and Ruby, why not in Python?

>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'

Strange enough, in Python the join method is on the str class:

# this is the Python way
"".join(['a','b','c','d'])

Why join is not a method in the list object like in JavaScript or other popular script languages? It is one example of how the Python community thinks. Since join is returning a string, it should be placed in the string class, not on the list class, so the str.join(list) method means: join the list into a new string using str as a separator (in this case str is an empty string).

Somehow I got to love this way of thinking after a while. I can complain about a lot of things in Python design, but not about its coherence.

Is an entity body allowed for an HTTP DELETE request?

Some versions of Tomcat and Jetty seem to ignore a entity body if it is present. Which can be a nuisance if you intended to receive it.

Passing ArrayList from servlet to JSP

public class myActorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String name;
    private String user;
    private String pass;
    private String given_table;
    private String tid;
    private String firstname;
    private String lastname;
    private String action;

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("text/html");

        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        PrintWriter out = response.getWriter();
        name = request.getParameter("screenName");
        user = request.getParameter("username");
        pass = request.getParameter("password");
        tid = request.getParameter("tid");
        firstname = request.getParameter("firstname");
        lastname = request.getParameter("lastname");
        action = request.getParameter("action");
        given_table = request.getParameter("tableName");

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet JDBC</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello, " + name + " </h1>");
        out.println("<h1>Servlet JDBC</h1>");

        /////////////////////////
        // init connection object
        String sqlSelect = "SELECT * FROM `" + given_table + "`";
        String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
        String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
        String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

        //////////////////////////////////////////////////////////
        out.println(
                "<p>Reading Table Data...Pass to JSP File...Okay<p>");

        ArrayList<Actor> list = new ArrayList<Actor>();
        // connecting to database
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sqlSelect);
            // displaying records

            while (rs.next()) {
                Actor actor = new Actor();
                actor.setId(rs.getInt("id"));
                actor.setLastname(rs.getString("lastname"));
                actor.setFirstname(rs.getString("firstname"));
                list.add(actor);
            }
            request.setAttribute("actors", list);
            RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
            view.forward(request, response);

        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
        } catch (ClassNotFoundException e) {
            throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException e) {
            }
        }
        out.println("</body></html>");

        out.close();
    }

}

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

What's the syntax for mod in java

As others have pointed out, the % (remainder) operator is not the same as the mathematical mod modulus operation/function.

mod vs %

The x mod n function maps x to n in the range of [0,n).
Whereas the x % n operator maps x to n in the range of (-n,n).

In order to have a method to use the mathematical modulus operation and not care about the sign in front of x one can use:

((x % n) + n) % n

Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)

enter image description here

How can I undo git reset --hard HEAD~1?

git reflog

  • Find your commit sha in the list then copy and paste it into this command:

git cherry-pick <the sha>

How can I get the current class of a div with jQuery?

Just get the class attribute:

var div1Class = $('#div1').attr('class');

Example

<div id="div1" class="accordion accordion_active">

To check the above div for classes contained in it

var a = ("#div1").attr('class'); 
console.log(a);

console output

accordion accordion_active

@Resource vs @Autowired

@Resource is often used by high-level objects, defined via JNDI. @Autowired or @Inject will be used by more common beans.

As far as I know, it's not a specification, nor even a convention. It's more the logical way standard code will use these annotations.

Partly JSON unmarshal into a map in Go

Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

Example:

func main() {
    jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`

    car := NewCar()

    i := iojson.NewIOJSON()

    if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    }

    // populating data to a live car object.
    if v, err := i.GetObjFromArr(0, car); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    } else {
        fmt.Printf("car (original): %s\n", car.GetName())
        fmt.Printf("car (returned): %s\n", v.(*Car).GetName())

        for k, item := range car.ItemArr {
            fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
        }

        for k, item := range v.(*Car).ItemArr {
            fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
        }
    }
}

Sample output:

car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen

Fitting a histogram with python

I was a bit puzzled that norm.fit apparently only worked with the expanded list of sampled values. I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples. Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...

# histogram is [(val,count)]
from math import sqrt

def normfit(hist):
    n,s,ss = univar(hist)
    mu = s/n
    var = ss/n-mu*mu
    return (mu, sqrt(var))

def univar(hist):
    n = 0
    s = 0
    ss = 0
    for v,c in hist:
        n += c
        s += c*v
        ss += c*v*v
    return n, s, ss

I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead. Feel free to point to the correct way to do it and downvote me :-)

How can I use custom fonts on a website?

Yes, there is a way. Its called custom fonts in CSS.Your CSS needs to be modified, and you need to upload those fonts to your website.

The CSS required for this is:

@font-face {
     font-family: Thonburi-Bold;
     src: url('pathway/Thonburi-Bold.otf'); 
}

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

I had a co-worker with this exact problem last week. He fixed it by installing the x64 version of Eclipse and the x64 JDK.

Edit: he reused his old workspace after installing the necessary plugins, so that should not be much of an issue

Cannot read property 'map' of undefined

in my case it happens when I try add types to Promise.all handler:

Promise.all([1,2]).then(([num1, num2]: [number, number])=> console.log('res', num1));

If remove : [number, number], the error is gone.

How do I replace multiple spaces with a single space in C#?

Consolodating other answers, per Joel, and hopefully improving slightly as I go:

You can do this with Regex.Replace():

string s = Regex.Replace (
    "   1  2    4 5", 
    @"[ ]{2,}", 
    " "
    );

Or with String.Split():

static class StringExtensions
{
    public static string Join(this IList<string> value, string separator)
    {
        return string.Join(separator, value.ToArray());
    }
}

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");

How to create a laravel hashed password

Laravel 5 uses bcrypt. So, you can do this as well.

$hashedpassword = bcrypt('plaintextpassword');

output of which you can save to your database table's password field.

Fn Ref: bcrypt

Finding local IP addresses using Python's stdlib

As an alias called myip, that should work everywhere:

alias myip="python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"
  • Works correctly with Python 2.x, Python 3.x, modern and old Linux distros, OSX/macOS and Windows for finding the current IPv4 address.
  • Will not return the correct result for machines with multiple IP addresses, IPv6, no configured IP address or no internet access.

NOTE: If you intend to use something like this within a Python program, the proper way is to make use of a Python module that has IPv6 support.


Same as above, but only the Python code:

import socket
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
  • This will throw an exception if no IP address is configured.

Version that will also work on LANs without an internet connection:

import socket
print((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0])

(thanks @ccpizza)


Background:

Using socket.gethostbyname(socket.gethostname()) did not work here, because one of the computers I was on had an /etc/hosts with duplicate entries and references to itself. socket.gethostbyname() only returns the last entry in /etc/hosts.

This was my initial attempt, which weeds out all addresses starting with "127.":

import socket
print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])

This works with Python 2 and 3, on Linux and Windows, but does not deal with several network devices or IPv6. However, it stopped working on recent Linux distros, so I tried this alternative technique instead. It tries to connect to the Google DNS server at 8.8.8.8 at port 53:

import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])

Then I combined the two above techniques into a one-liner that should work everywhere, and created the myip alias and Python snippet at the top of this answer.

With the increasing popularity of IPv6, and for servers with multiple network interfaces, using a third-party Python module for finding the IP address is probably both more robust and reliable than any of the methods listed here.

Write / add data in JSON file using Node.js

For synchronous approach

const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));

dynamically add and remove view to viewpager

After figuring out which ViewPager methods are called by ViewPager and which are for other purposes, I came up with a solution. I present it here since I see a lot of people have struggled with this and I didn't see any other relevant answers.

First, here's my adapter; hopefully comments within the code are sufficient:

public class MainPagerAdapter extends PagerAdapter
{
  // This holds all the currently displayable views, in order from left to right.
  private ArrayList<View> views = new ArrayList<View>();

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  "Object" represents the page; tell the ViewPager where the
  // page should be displayed, from left-to-right.  If the page no longer exists,
  // return POSITION_NONE.
  @Override
  public int getItemPosition (Object object)
  {
    int index = views.indexOf (object);
    if (index == -1)
      return POSITION_NONE;
    else
      return index;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager needs a page to display; it is our job
  // to add the page to the container, which is normally the ViewPager itself.  Since
  // all our pages are persistent, we simply retrieve it from our "views" ArrayList.
  @Override
  public Object instantiateItem (ViewGroup container, int position)
  {
    View v = views.get (position);
    container.addView (v);
    return v;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager no longer needs a page to display; it
  // is our job to remove the page from the container, which is normally the
  // ViewPager itself.  Since all our pages are persistent, we do nothing to the
  // contents of our "views" ArrayList.
  @Override
  public void destroyItem (ViewGroup container, int position, Object object)
  {
    container.removeView (views.get (position));
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager; can be used by app as well.
  // Returns the total number of pages that the ViewPage can display.  This must
  // never be 0.
  @Override
  public int getCount ()
  {
    return views.size();
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.
  @Override
  public boolean isViewFromObject (View view, Object object)
  {
    return view == object;
  }

  //-----------------------------------------------------------------------------
  // Add "view" to right end of "views".
  // Returns the position of the new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v)
  {
    return addView (v, views.size());
  }

  //-----------------------------------------------------------------------------
  // Add "view" at "position" to "views".
  // Returns position of new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v, int position)
  {
    views.add (position, v);
    return position;
  }

  //-----------------------------------------------------------------------------
  // Removes "view" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, View v)
  {
    return removeView (pager, views.indexOf (v));
  }

  //-----------------------------------------------------------------------------
  // Removes the "view" at "position" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, int position)
  {
    // ViewPager doesn't have a delete method; the closest is to set the adapter
    // again.  When doing so, it deletes all its views.  Then we can delete the view
    // from from the adapter and finally set the adapter to the pager again.  Note
    // that we set the adapter to null before removing the view from "views" - that's
    // because while ViewPager deletes all its views, it will call destroyItem which
    // will in turn cause a null pointer ref.
    pager.setAdapter (null);
    views.remove (position);
    pager.setAdapter (this);

    return position;
  }

  //-----------------------------------------------------------------------------
  // Returns the "view" at "position".
  // The app should call this to retrieve a view; not used by ViewPager.
  public View getView (int position)
  {
    return views.get (position);
  }

  // Other relevant methods:

  // finishUpdate - called by the ViewPager - we don't care about what pages the
  // pager is displaying so we don't use this method.
}

And here's some snips of code showing how to use the adapter.

class MainActivity extends Activity
{
  private ViewPager pager = null;
  private MainPagerAdapter pagerAdapter = null;

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

    ... do other initialization, such as create an ActionBar ...

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.view_pager);
    pager.setAdapter (pagerAdapter);

    // Create an initial view to display; must be a subclass of FrameLayout.
    LayoutInflater inflater = context.getLayoutInflater();
    FrameLayout v0 = (FrameLayout) inflater.inflate (R.layout.one_of_my_page_layouts, null);
    pagerAdapter.addView (v0, 0);
    pagerAdapter.notifyDataSetChanged();
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to add a view to the ViewPager.
  public void addView (View newPage)
  {
    int pageIndex = pagerAdapter.addView (newPage);
    // You might want to make "newPage" the currently displayed page:
    pager.setCurrentItem (pageIndex, true);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to remove a view from the ViewPager.
  public void removeView (View defunctPage)
  {
    int pageIndex = pagerAdapter.removeView (pager, defunctPage);
    // You might want to choose what page to display, if the current page was "defunctPage".
    if (pageIndex == pagerAdapter.getCount())
      pageIndex--;
    pager.setCurrentItem (pageIndex);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to get the currently displayed page.
  public View getCurrentPage ()
  {
    return pagerAdapter.getView (pager.getCurrentItem());
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to set the currently displayed page.  "pageToShow" must
  // currently be in the adapter, or this will crash.
  public void setCurrentPage (View pageToShow)
  {
    pager.setCurrentItem (pagerAdapter.getItemPosition (pageToShow), true);
  }
}

Finally, you can use the following for your activity_main.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</android.support.v4.view.ViewPager>

Possible to perform cross-database queries with PostgreSQL?

Yes, you can by using DBlink (postgresql only) and DBI-Link (allows foreign cross database queriers) and TDS_LInk which allows queries to be run against MS SQL server.

I have used DB-Link and TDS-link before with great success.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx

There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803

SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:

SELECT CAST(N'±' as varbinary(10)) AS Result

This will return 0xB100 which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.

If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.

You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY instead of VARCHAR so the SQL Server transformation is not invalidated by the client before it is presented:

SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName

This will get you 0xF1 or 0xB1 respectively if columnName contains just the character '±'

You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.

Please double check the actual internal representation of your character by casting the query to VARBINARY on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2

SELECT CAST(columnName as varbinary(10)) from tableName

Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.

All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

From the javadoc:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

urlencode vs rawurlencode?

I believe spaces must be encoded as:

  • %20 when used inside URL path component
  • + when used inside URL query string component or form data (see 17.13.4 Form content types)

The following example shows the correct use of rawurlencode and urlencode:

echo "http://example.com"
    . "/category/" . rawurlencode("latest songs")
    . "/search?q=" . urlencode("lady gaga");

Output:

http://example.com/category/latest%20songs/search?q=lady+gaga

What happens if you encode path and query string components the other way round? For the following example:

http://example.com/category/latest+songs/search?q=lady%20gaga
  • The webserver will look for the directory latest+songs instead of latest songs
  • The query string parameter q will contain lady gaga

R - " missing value where TRUE/FALSE needed "

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

How to lock orientation of one view controller to portrait mode only in Swift

Best Solution for lock and change orientation on portrait and landscape:

Watch this video on YouTube:

https://m.youtube.com/watch?v=4vRrHdBowyo

This tutorial is best and simple.

or use below code:

See this picture

// 1- in second viewcontroller we set landscapeleft and in first viewcontroller we set portrat:

// 2- if you use NavigationController, you should add extension

import UIKit

class SecondViewController: UIViewController {


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
    }

    override open var shouldAutorotate: Bool {
        return false
    }

    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscapeLeft
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .landscapeLeft
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
    }

//write The rest of your code in here


}

//if you use NavigationController, you should add this extension

extension UINavigationController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .allButUpsideDown
    
    }
}

How to install SQL Server 2005 Express in Windows 8

I found that on Windows 8.1 with an instance of SQL 2014 already installed, if I ran the SQLEXPR.EXE and then dismissed the Windows 'warning this may be incompatible' dialogs, that the installer completed successfully.

I suspect having 2014 bits already in place probably helped.

How to Multi-thread an Operation Within a Loop in Python

First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.

This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.


Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing and concurrent.futures libraries both wraps up most of the details for you.

The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures, 4 lines with multiprocessing.)

If you're using 2.6-2.7 or 3.0-3.1, futures isn't built in, but you can install it from PyPI (pip install futures).


Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map), so let's do that first:

def try_my_operation(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

Putting it all together:

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)

If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper from the itertools recipes, which you can copy and paste into your code, or get from the more-itertools project on PyPI):

def try_multiple_operations(items):
    for item in items:
        try:
            api.my_operation(item)
        except:
            print('error with item')

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group) 
           for group in grouper(5, items)]
concurrent.futures.wait(futures)

Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.

So, how do you use threads instead of processes? Just change ProcessPoolExecutor to ThreadPoolExecutor.

If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.


Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?

Yes. In fact, there are two different ways to do it.

First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.

Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.

If you don't know which is appropriate for your program, usually it's the first.

qmake: could not find a Qt installation of ''

For others in my situation, the solution was:

qmake -qt=qt5

This was on Ubuntu 14.04 after install qt5-qmake. qmake was a symlink to qtchooser which takes the -qt argument.

Vertically align text next to an image?

Actually, in this case it's quite simple: apply the vertical align to the image. Since it's all in one line, it's really the image you want aligned, not the text.

_x000D_
_x000D_
<!-- moved "vertical-align:middle" style from span to img -->_x000D_
<div>_x000D_
  <img style="vertical-align:middle" src="https://placehold.it/60x60">_x000D_
  <span style="">Works.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tested in FF3.

Now you can use flexbox for this type of layout.

_x000D_
_x000D_
.box {_x000D_
   display: flex;_x000D_
   align-items:center;_x000D_
}
_x000D_
<div class="box">_x000D_
    <img src="https://placehold.it/60x60">_x000D_
    <span style="">Works.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting Java version at runtime

What about getting the version from the package meta infos:

String version = Runtime.class.getPackage().getImplementationVersion();

Prints out something like:

1.7.0_13

Using command line arguments in VBscript

If you need direct access:

WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

How to merge rows in a column into one cell in excel?

Use VBA's already existing Join function. VBA functions aren't exposed in Excel, so I wrap Join in a user-defined function that exposes its functionality. The simplest form is:

Function JoinXL(arr As Variant, Optional delimiter As String = " ")
    'arr must be a one-dimensional array.
    JoinXL = Join(arr, delimiter)
End Function

Example usage:

=JoinXL(TRANSPOSE(A1:A4)," ") 

entered as an array formula (using Ctrl-Shift-Enter).

enter image description here


Now, JoinXL accepts only one-dimensional arrays as input. In Excel, ranges return two-dimensional arrays. In the above example, TRANSPOSE converts the 4×1 two-dimensional array into a 4-element one-dimensional array (this is the documented behaviour of TRANSPOSE when it is fed with a single-column two-dimensional array).

For a horizontal range, you would have to do a double TRANSPOSE:

=JoinXL(TRANSPOSE(TRANSPOSE(A1:D1)))

The inner TRANSPOSE converts the 1×4 two-dimensional array into a 4×1 two-dimensional array, which the outer TRANSPOSE then converts into the expected 4-element one-dimensional array.

enter image description here

This usage of TRANSPOSE is a well-known way of converting 2D arrays into 1D arrays in Excel, but it looks terrible. A more elegant solution would be to hide this away in the JoinXL VBA function.

Convert JSON string to dict using Python

json.loads()

import json

d = json.loads(j)
print d['glossary']['title']

Compare 2 arrays which returns difference

This should work with unsorted arrays, double values and different orders and length, while giving you the filtered values form array1, array2, or both.

function arrayDiff(arr1, arr2) {
    var diff = {};

    diff.arr1 = arr1.filter(function(value) {
        if (arr2.indexOf(value) === -1) {
            return value;
        }
    });

    diff.arr2 = arr2.filter(function(value) {
        if (arr1.indexOf(value) === -1) {
            return value;
        }
    });

    diff.concat = diff.arr1.concat(diff.arr2);

    return diff;
};

var firstArray = [1,2,3,4];
var secondArray = [4,6,1,4];

console.log( arrayDiff(firstArray, secondArray) );
console.log( arrayDiff(firstArray, secondArray).arr1 );
// => [ 2, 3 ]
console.log( arrayDiff(firstArray, secondArray).concat );
// => [ 2, 3, 6 ]

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

C# Return Different Types?

You can have the return type to be a superclass of the three classes (either defined by you or just use object). Then you can return any one of those objects, but you will need to cast it back to the correct type when getting the result. Like:

public object GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return radio; or return computer; or return hello //should be possible?!      
}

Then:

Hello hello = (Hello)getAnything(); 

Vim: faster way to select blocks of text in visual mode

I use this with fold in indent mode :

v open Visual mode anywhere on the block

zaza toogle it twice

"Fatal error: Cannot redeclare <function>"

In my case it was because of function inside another function! once I moved out the function, error was gone , and everything worked as expected.

This answer explains why you shouldn't use function inside function.

This might help somebody.

Detect Android phone via Javascript / jQuery

I think Michal's answer is the best, but we can take it a step further and dynamically load an Android CSS as per the original question:

var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {
    var css = document.createElement("link");
    css.setAttribute("rel", "stylesheet");
    css.setAttribute("type", "text/css");
    css.setAttribute("href", "/css/android.css");
    document.body.appendChild(css);
}

How to test if a double is zero?

Yes; all primitive numeric types default to 0.

However, calculations involving floating-point types (double and float) can be imprecise, so it's usually better to check whether it's close to 0:

if (Math.abs(foo.x) < 2 * Double.MIN_VALUE)

You need to pick a margin of error, which is not simple.

Bootstrap - Removing padding or margin when screen size is smaller

In Bootstrap 4, the 15px margin the initial container has, cascades down to all rows and columns. So, something like this works for me...

@media (max-width: 576px) {
    .container-fluid {
        padding-left: 5px;
        padding-right: 5px;
    }

    .row {
        margin-left: -5px;
        margin-right: -5px;
    }
    .col, .col-1, .col-10, .col-11, .col-12, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-auto, .col-lg, .col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-auto, .col-md, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-auto, .col-sm, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-auto, .col-xl, .col-xl-1, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-auto {
        padding-left: 5px;
        padding-right: 5px;
    }
    .row.no-gutters {
        margin-left: 0;
        margin-right: 0;
    }
}

Internet Access in Ubuntu on VirtualBox

it could be a problem with your specific network adapter. I have a Dell 15R and there are no working drivers for ubuntu or ubuntu server; I even tried compiling wireless drivers myself, but to no avail.

However, in virtualbox, I was able to get wireless working by using the default configuration. It automatically bridged my internal wireless adapter and hence used my native OS's wireless connection for wireless.

If you are trying to get a separate wireless connection from within ubuntu in virtualbox, then it would take more configuring. If so, let me know, if not, I will not bother typing up instructions to something you are not looking to do, as it is quite complicated in some instances.

p.s. you should be using Windows 7 if you have any technical inclination. Do you live under a rock? No offense intended.

Jquery: Find Text and replace

More specific:

$("#id1 p:contains('dog')").text($("#id1 p:contains('dog')").text().replace('dog', 'doll'));

anaconda/conda - install a specific package version

If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used

conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"

conda install -y torchvision">=0.3.0"
conda install  openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"

where option -y, --yes Do not ask for confirmation.

Here is a summary:

Format         Sample Specification     Results
Exact          qtconsole==4.5.1         4.5.1
Fuzzy          qtconsole=4.5            4.5.0, 4.5.1, ..., etc.
>=, >, <, <=  "qtconsole>=4.5"          4.5.0 or higher
               qtconsole"<4.6"          less than 4.6.0

OR            "qtconsole=4.5.1|4.5.2"   4.5.1, 4.5.2
AND           "qtconsole>=4.3.1,<4.6"   4.3.1 or higher but less than 4.6.0

Potion of the above information credit to Conda Cheat Sheet

Tested on conda 4.7.12

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

How would one write object-oriented code in C?

I've seen it done. I wouldn't recommend it. C++ originally started this way as a preprocessor that produced C code as an intermediate step.

Essentially what you end up doing is create a dispatch table for all of your methods where you store your function references. Deriving a class would entail copying this dispatch table and replacing the entries that you wanted to override, with your new "methods" having to call the original method if it wants to invoke the base method. Eventually, you end up rewriting C++.

Input type DateTime - Value format?

This works for setting the value of the INPUT:

strftime('%Y-%m-%dT%H:%M:%S', time())

Threading pool similar to the multiprocessing Pool?

The overhead of creating the new processes is minimal, especially when it's just 4 of them. I doubt this is a performance hot spot of your application. Keep it simple, optimize where you have to and where profiling results point to.

In C#, what's the difference between \n and \r\n?

The Difference

There are a few characters which can indicate a new line. The usual ones are these two:

* '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF).
* '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).

Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:

* DOS and Windows

They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).

* Unix (and hence Linux as well)

Unix uses a single '\n' to indicate a new line.

* Mac

Macs use a single '\r'.

Taken from Here

How to add background-image using ngStyle (angular2)?

I think you could try this:

<div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div>

From reading your ngStyle expression, I guess that you missed some "'"...

How to detect orientation change?

override func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(MyController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
//...
}

@objc
private func rotated() {
    if UIDevice.current.orientation.isLandscape {

    } else if UIDevice.current.orientation.isPortrait {

    }

    //or you can check orientation separately UIDevice.current.orientation
    //portrait, portraitUpsideDown, landscapeLeft, landscapeRight... 

}

GitHub authentication failing over https, returning wrong email address

Same thing happened with me, when i have enabled 2-way authentication for github. Things i did to resolve:

  • Get you personal access token. This you have to check and generate if not available already. Link for this: https://github.com/settings/tokens
  • Go to your local and delete folder and re-clone branch from github.
  • Now try the command you were trying earlier i.e: git pull origin master
  • Enter username and In password paste the token generated and also don't forget to save that token somewhere, so you can re-use if required.

Doing this will solve your issue.

Parse String to Date with Different Format in Java

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}

How do you deploy Angular apps?

Simple answer. Use the Angular CLI and issue the

ng build 

command in the root directory of your project. The site will be created in the dist directory and you can deploy that to any web server.

This will build for test, if you have production settings in your app you should use

ng build --prod

This will build the project in the dist directory and this can be pushed to the server.

Much has happened since I first posted this answer. The CLI is finally at a 1.0.0 so following this guide go upgrade your project should happen before you try to build. https://github.com/angular/angular-cli/wiki/stories-rc-update

Check if input is integer type in C

I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!

#include<stdio.h>

int iFunctErrorCheck(int iLowerBound, int iUpperBound){

int iUserInput=0;
while (iUserInput==0){
    scanf("%i", &iUserInput);
    if (iUserInput==0){
        printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
        getchar();
    }
    if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
        printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
        iUserInput=0;
    }
}
return iUserInput;
}

Convert pandas dataframe to NumPy array

Try this:

a = numpy.asarray(df)

Java - how do I write a file to a specified directory

Use:

File file = new File("Z:\\results\\results.txt");

You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.

For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.

File file = new File("/home/userName/Documents/results.txt");

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.

Example:

myvar1 = userInput['param1']
myvar2 = userInput['param2']

to:

myvar = userInput

Hex-encoded String to Byte Array

try this:

     String str = "9B7D2C34A366BF890C730641E6CECF6F";
     String[] temp = str.split(",");
     bytesArray = new byte[temp.length];
     int index = 0;
     for (String item: temp) {
     bytesArray[index] = Byte.parseByte(item);
     index++;
     }

How to convert text column to datetime in SQL

Use convert with style 101.

select convert(datetime, Remarks, 101)

If your column is really text you need to convert to varchar before converting to datetime

select convert(datetime, convert(varchar(30), Remarks), 101)

Conda activate not working?

After installing conda in Linux if you are trying to create env just type bash and hit Enter later you can create env

How can you sort an array without mutating the original array?

Try the following

function sortCopy(arr) { 
  return arr.slice(0).sort();
}

The slice(0) expression creates a copy of the array starting at element 0.

Call angularjs function using jquery/javascript

Please check this answer

// In angularJS script
$scope.foo = function() {
    console.log('test');
};
$window.angFoo = function() {
    $scope.foo();
    $scope.$apply(); 
};
    
// In jQuery
if (window.angFoo) {
    window.angFoo();
}

tSQL - Conversion from varchar to numeric works for all but integer

Converting a varchar value into an int fails when the value includes a decimal point to prevent loss of data.

If you convert to a decimal or float value first, then convert to int, the conversion works.

Either example below will return 7082:

SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172'));
SELECT CAST(CAST('7082.7758172' as float) as int);

Be aware that converting to a float value may result, in rare circumstances, in a loss of precision. I would tend towards using a decimal value, however you'll need to specify precision and scale values that make sense for the varchar data you're converting.

What exactly does numpy.exp() do?

It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5)) is similar to [math.e**x for x in range(5)].

Smooth GPS data

You can also use a spline. Feed in the values you have and interpolate points between your known points. Linking this with a least-squares fit, moving average or kalman filter (as mentioned in other answers) gives you the ability to calculate the points inbetween your "known" points.

Being able to interpolate the values between your knowns gives you a nice smooth transition and a /reasonable/ approximation of what data would be present if you had a higher-fidelity. http://en.wikipedia.org/wiki/Spline_interpolation

Different splines have different characteristics. The one's I've seen most commonly used are Akima and Cubic splines.

Another algorithm to consider is the Ramer-Douglas-Peucker line simplification algorithm, it is quite commonly used in the simplification of GPS data. (http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)

Best way to structure a tkinter application?

I advocate an object oriented approach. This is the template that I start out with:

# Use Tkinter for python 2, tkinter for python 3
import tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        <create the rest of your GUI here>

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

The important things to notice are:

  • I don't use a wildcard import. I import the package as "tk", which requires that I prefix all commands with tk.. This prevents global namespace pollution, plus it makes the code completely obvious when you are using Tkinter classes, ttk classes, or some of your own.

  • The main application is a class. This gives you a private namespace for all of your callbacks and private functions, and just generally makes it easier to organize your code. In a procedural style you have to code top-down, defining functions before using them, etc. With this method you don't since you don't actually create the main window until the very last step. I prefer inheriting from tk.Frame just because I typically start by creating a frame, but it is by no means necessary.

If your app has additional toplevel windows, I recommend making each of those a separate class, inheriting from tk.Toplevel. This gives you all of the same advantages mentioned above -- the windows are atomic, they have their own namespace, and the code is well organized. Plus, it makes it easy to put each into its own module once the code starts to get large.

Finally, you might want to consider using classes for every major portion of your interface. For example, if you're creating an app with a toolbar, a navigation pane, a statusbar, and a main area, you could make each one of those classes. This makes your main code quite small and easy to understand:

class Navbar(tk.Frame): ...
class Toolbar(tk.Frame): ...
class Statusbar(tk.Frame): ...
class Main(tk.Frame): ...

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.statusbar = Statusbar(self, ...)
        self.toolbar = Toolbar(self, ...)
        self.navbar = Navbar(self, ...)
        self.main = Main(self, ...)

        self.statusbar.pack(side="bottom", fill="x")
        self.toolbar.pack(side="top", fill="x")
        self.navbar.pack(side="left", fill="y")
        self.main.pack(side="right", fill="both", expand=True)

Since all of those instances share a common parent, the parent effectively becomes the "controller" part of a model-view-controller architecture. So, for example, the main window could place something on the statusbar by calling self.parent.statusbar.set("Hello, world"). This allows you to define a simple interface between the components, helping to keep coupling to a minimun.

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

C#: what is the easiest way to subtract time?

This works too:

System.DateTime dTime = DateTime.Now();

// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0); 

System.DateTime result = dTime + tSpan;

To subtract a year:

DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);

Is an anchor tag without the href attribute safe?

It is OK, but at the same time can cause some browsers to become slow.

http://webdesignfan.com/yslow-tutorial-part-2-of-3-reducing-server-calls/

My advice is use <a href="#"></a>

If you're using JQuery remember to also use:

.click(function(event){
    event.preventDefault();
    // Click code here...
});

Manually Set Value for FormBuilder Control

Aangular 2 final has updated APIs. They have added many methods for this.

To update the form control from controller do this:

this.form.controls['dept'].setValue(selected.id);

this.form.controls['dept'].patchValue(selected.id);

No need to reset the errors

References

https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

https://toddmotto.com/angular-2-form-controls-patch-value-set-value

How do I exit a WPF application programmatically?

Here's how I do mine:

// Any control that causes the Window.Closing even to trigger.
private void MenuItemExit_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

// Method to handle the Window.Closing event.
private void Window_Closing(object sender, CancelEventArgs e)
{
    var response = MessageBox.Show("Do you really want to exit?", "Exiting...",
                                   MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
    if (response == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
    else
    {
        Application.Current.Shutdown();
    }
}

I only call for Application.Current.ShutDown() from the main application window, all other windows use this.Close(). In my main window, Window_Closing(...) handles the top right x button. If any of the methods call for window closer, Window_Closing(...) grabs the event for shut down if user confirms.

The reason I do in fact use Application.Current.Shutdown() in my main window is that I've noticed that if a design mistake was made and I haven't declared a parent of one of my windows in an application, if that window is opened without being shown prior to the last active window closing, I'm left with a hidden window running in the background. The application will not shut down. The only way to prevent complete memory leak is for me to go into the Task Manager to shut down the application. Application.Current.Shutdown() protects me from unintended design flaws.

That is from my personal experience. In the end, use what is best for your scenario. This is just another piece of information.

How do I find the time difference between two datetime objects in python?

Just subtract one from the other. You get a timedelta object with the difference.

>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)

You can convert dd.days, dd.seconds and dd.microseconds to minutes.

Best way to convert text files between character sets?

Under Linux you can use the very powerful recode command to try and convert between the different charsets as well as any line ending issues. recode -l will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.

PHP Multiple Checkbox Array

You need to use the square brackets notation to have values sent as an array:

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td>
</tr>
</table>
<input type='submit' class='buttons'>
</form>

Please note though, that only the values of only checked checkboxes will be sent.

Cordova app not displaying correctly on iPhone X (Simulator)

There is 3 steps you have to do

for iOs 11 status bar & iPhone X header problems


1. Viewport fit cover

Add viewport-fit=cover to your viewport's meta in <header>

<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0,viewport-fit=cover">

Demo: https://jsfiddle.net/gq5pt509 (index.html)


  1. Add more splash images to your config.xml inside <platform name="ios">

Dont skip this step, this required for getting screen fit for iPhone X work

<splash src="your_path/Default@2x~ipad~anyany.png" />   <!-- 2732x2732 -->
<splash src="your_path/Default@2x~ipad~comany.png" />   <!-- 1278x2732 -->
<splash src="your_path/Default@2x~iphone~anyany.png" /> <!-- 1334x1334 -->
<splash src="your_path/Default@2x~iphone~comany.png" /> <!-- 750x1334  -->
<splash src="your_path/Default@2x~iphone~comcom.png" /> <!-- 1334x750  -->
<splash src="your_path/Default@3x~iphone~anyany.png" /> <!-- 2208x2208 -->
<splash src="your_path/Default@3x~iphone~anycom.png" /> <!-- 2208x1242 -->
<splash src="your_path/Default@3x~iphone~comany.png" /> <!-- 1242x2208 -->

Demo: https://jsfiddle.net/mmy885q4 (config.xml)


  1. Fix your style on CSS

Use safe-area-inset-left, safe-area-inset-right, safe-area-inset-top, or safe-area-inset-bottom

Example: (Use in your case!)

#header {
   position: fixed;
   top: 1.25rem; // iOs 10 or lower
   top: constant(safe-area-inset-top); // iOs 11
   top: env(safe-area-inset-top); // iOs 11+ (feature)

   // or use calc()
   top: calc(constant(safe-area-inset-top) + 1rem);
   top: env(constant(safe-area-inset-top) + 1rem);
  
   // or SCSS calc()
   $nav-height: 1.25rem;
   top: calc(constant(safe-area-inset-top) + #{$nav-height});
   top: calc(env(safe-area-inset-top) + #{$nav-height});
}

Bonus: You can add body class like is-android or is-ios on deviceready

var platformId = window.cordova.platformId;
if (platformId) {
   document.body.classList.add('is-' + platformId);
}

So you can do something like this on CSS

.is-ios #header {
 // Properties
}

How to get tf.exe (TFS command line client)?

Following on from the earlier answers above but based on a VS 2019 install ;
I needed to run "tf git permission" commands, and copied the following files from:

C:\Program Files (x86)\Microsoft Visual Studio\2019\TeamExplorer\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer

Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.Diff.dll
Microsoft.TeamFoundation.Git.Client.dll
Microsoft.TeamFoundation.Git.Contracts.dll
Microsoft.TeamFoundation.Git.Controls.dll
Microsoft.TeamFoundation.Git.CoreServices.dll
Microsoft.TeamFoundation.Git.dll
Microsoft.TeamFoundation.Git.Graph.dll
Microsoft.TeamFoundation.Git.HostingProvider.AzureDevOps.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.imagemanifest
Microsoft.TeamFoundation.Git.Provider.dll
Microsoft.TeamFoundation.SourceControl.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Common.Integration.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll
TF.exe
TF.exe.config

Difference between parameter and argument

Arguments and parameters are different in that parameters are used to different values in the program and The arguments are passed the same value in the program so they are used in c++. But no difference in c. It is the same for arguments and parameters in c.