Programs & Examples On #Expect

Expect is a Unix/Linux extension for the Tcl scripting language. It was designed as an automation and testing tool, and it makes it trivial to interact with complex programs, such as remote shells and security maintenance. It has a particularly powerful response recognition.

Use Expect in a Bash script to provide a password to an SSH command

After looking for an answer for the question for months, I finally find a really best solution: writing a simple script.

#!/usr/bin/expect

set timeout 20

set cmd [lrange $argv 1 end]
set password [lindex $argv 0]

eval spawn $cmd
expect "assword:"   # matches both 'Password' and 'password'
send "$password\r";
interact

Put it to /usr/bin/exp, then you can use:

  • exp <password> ssh <anything>
  • exp <password> scp <anysrc> <anydst>

Done!

Disable keyboard on EditText

You can also use setShowSoftInputOnFocus(boolean) directly on API 21+ or through reflection on API 14+:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    editText.setShowSoftInputOnFocus(false);
} else {
    try {
        final Method method = EditText.class.getMethod(
                "setShowSoftInputOnFocus"
                , new Class[]{boolean.class});
        method.setAccessible(true);
        method.invoke(editText, false);
    } catch (Exception e) {
        // ignore
    }
}

Rerender view on browser resize with React

This code is using the new React context API:

  import React, { PureComponent, createContext } from 'react';

  const { Provider, Consumer } = createContext({ width: 0, height: 0 });

  class WindowProvider extends PureComponent {
    state = this.getDimensions();

    componentDidMount() {
      window.addEventListener('resize', this.updateDimensions);
    }

    componentWillUnmount() {
      window.removeEventListener('resize', this.updateDimensions);
    }

    getDimensions() {
      const w = window;
      const d = document;
      const documentElement = d.documentElement;
      const body = d.getElementsByTagName('body')[0];
      const width = w.innerWidth || documentElement.clientWidth || body.clientWidth;
      const height = w.innerHeight || documentElement.clientHeight || body.clientHeight;

      return { width, height };
    }

    updateDimensions = () => {
      this.setState(this.getDimensions());
    };

    render() {
      return <Provider value={this.state}>{this.props.children}</Provider>;
    }
  }

Then you can use it wherever you want in your code like this:

<WindowConsumer>
  {({ width, height }) =>  //do what you want}
</WindowConsumer>

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

changing the language of error message in required field in html5 contact form

<input type="text" id="inputName"  placeholder="Enter name"  required  oninvalid="this.setCustomValidity('Please Enter your first name')" >

this can help you even more better, Fast, Convenient & Easiest.

Export DataBase with MySQL Workbench with INSERT statements

Go to Menu Server and Click on Data Export. There you can select the table and select the option Dump Structure and Data' from the drop-down.

Adding Git-Bash to the new Windows Terminal

Because most answers either show a lot of unrelated configuration or don't show the configuration, I created my own answer that tries to be more focused. It is mainly based on the profile settings reference and Archimedes Trajano's answer.

Steps

  1. Open PowerShell and enter [guid]::NewGuid() to generate a new GUID. We will use it at step 3.

    > [guid]::NewGuid()
    
    Guid
    ----
    a3da8d92-2f3f-4e36-9714-98876b6cb480
    
  2. Open the settings of Windows Terminal. (CTRL+,)

  3. Add the following JSON object to profiles.list. Replace guid with the one you generated at step 1.

    {
      "guid": "{a3da8d92-2f3f-4e36-9714-98876b6cb480}",
      "name": "Git Bash",
      "commandline": "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" -i -l",
      "icon": "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico",
      "startingDirectory" : "%USERPROFILE%"
    },
    

Notes

  • There is currently an issue that you cannot use your arrow keys (and some other keys). It seems to work with the latest preview version, though. (issue #6859)

  • Specifying "startingDirectory" : "%USERPROFILE%" shouldn't be necessary according to the reference. However, if I don't specify it, the starting directory was different depending on how I started the terminal initially.

  • Settings that shall apply to all terminals can be specified in profiles.defaults.

  • I recommend to set "antialiasingMode": "cleartype" in profiles.defaults. You have to remove "useAcrylic" (if you have added it as suggested by some other answers) to make it work. It improves the quality of text rendering. However, you cannot have transparent background without useAcrylic. See issue #1298.

  • If you have problems with the cursor, you can try another shape like "cursorShape": "filledBox". See cursor settings for more information.

Maximum request length exceeded.

If you are using IIS for hosting your application, then the default upload file size is 4MB. To increase it, please use this below section in your web.config -

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Note:

  • maxRequestLength is measured in kilobytes
  • maxAllowedContentLength is measured in bytes

which is why the values differ in this config example. (Both are equivalent to 1 GB.)

How to set custom favicon in Express?

No extra middlewares required. Just use:

app.use('/favicon.ico', express.static('images/favicon.ico'));

The Import android.support.v7 cannot be resolved

  1. Go to your project in the navigator, right click on properties.

  2. Go to the Java Build Path tab on the left.

  3. Go to the libraries tab on top.

  4. Click add external jars.

  5. Go to your ADT Bundle folder, go to sdk/extras/android/support/v7/appcompat/libs.

  6. Select the file android-support-v7-appcompat.jar

  7. Go to order and export and check the box next to your new jar.

  8. Click ok.

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

Is there any use for unique_ptr with array?

I can't disagree with the spirit of the accepted answer strongly enough. "A tool of last resort"? Far from it!

The way I see it, one of the strongest features of C++ compared to C and to some other similar languages is the ability to express constraints so that they can be checked at compile time and accidental misuse can be prevented. So when designing a structure, ask yourself what operations it should permit. All the other uses should be forbidden, and it's best if such restrictions can be implemented statically (at compile time) so that misuse results in a compilation failure.

So when one needs an array, the answers to the following questions specify its behavior: 1. Is its size a) dynamic at runtime, or b) static, but only known at runtime, or c) static and known at compile time? 2. Can the array be allocated on the stack or not?

And based on the answers, this is what I see as the best data structure for such an array:

       Dynamic     |   Runtime static   |         Static
Stack std::vector      unique_ptr<T[]>          std::array
Heap  std::vector      unique_ptr<T[]>     unique_ptr<std::array>

Yep, I think unique_ptr<std::array> should also be considered, and neither is a tool of last resort. Just think what fits best with your algorithm.

All of these are compatible with plain C APIs via the raw pointer to data array (vector.data() / array.data() / uniquePtr.get()).

P. S. Apart from the above considerations, there's also one of ownership: std::array and std::vector have value semantics (have native support for copying and passing by value), while unique_ptr<T[]> can only be moved (enforces single ownership). Either can be useful in different scenarios. On the contrary, plain static arrays (int[N]) and plain dynamic arrays (new int[10]) offer neither and thus should be avoided if possible - which should be possible in the vast majority of cases. If that wasn't enough, plain dynamic arrays also offer no way to query their size - extra opportunity for memory corruptions and security holes.

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

The most likely reason why the Java Runtime Environment JRE or Java Development Kit JDK is that it's owned by Oracle not Google and they would need a redistribution agreement which if you know there is some history between the two companies.

Lucky for us that Sun Microsystems before it was bought by Oracle open sourced Java and MySQL a win for us little guys.... Thank you Sun!

Google should probably have a caveat saying you may also need JRE OR JDK

Convert Text to Date?

Solved the issue for me :

    Range(Cells(1, 1), Cells(100, 1)).Select

    For Each xCell In Selection

    xCell.Value = CDate(xCell.Value)

    Next xCell

Sql server - log is full due to ACTIVE_TRANSACTION

Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:

* Issue a CHECKPOINT command to free up log space in the log file.

* Check the available log space with DBCC SQLPERF('logspace'). If only a small 
  percentage of your log file is actually been used, you can try a DBCC SHRINKFILE 
  command. This can however possibly introduce corruption in your database. 

* If you have another drive with space available you can try to add a file there in 
  order to get enough space to attempt to resolve the issue.

Hope this will help you in finding your solution.

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

The NoneType is the type of the value None. In this case, the variable lifetime has a value of None.

A common way to have this happen is to call a function missing a return.

There are an infinite number of other ways to set a variable to None, however.

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

Thanks to Don Branson,I solve my problem.I think next time i should use this code when i build my repo on server:

root@localhost:~#mkdir foldername
root@localhost:~#cd foldername
root@localhost:~#git init --bare
root@localhost:~#cd ../
root@localhost:~#chown -R usergroup:username foldername

And on client,i user this

$ git remote add origin git@servername:/var/git/foldername
$ git push origin master

How to change credentials for SVN repository in Eclipse?

I was able unable to locate the svn.simple file, but was able to change credentials using the following three steps:

Checkout project from SVN

enter image description here

Select the repository you need to change the credentials on (note: you will not perform an checkout, but this will bring you to the screen to enter a username/password combination).

enter image description here

Finally, enter the new username and password credentials:

enter image description here

It's a bit confusing, because you begin the process of initializing a new project, but you're only resetting the repository credentials.

How to create strings containing double quotes in Excel formulas?

Returning an empty or zero-length string (e.g. "") to make a cell appear blank is a common practise in a worksheet formula but recreating that option when inserting the formula through the Range.Formula or Range.FormulaR1C1 property in VBA is unwieldy due to the necessity of having to double-up the double-quote characters within a quoted string.

The worksheet's native TEXT function can produce the same result without using quotes.

'formula to insert into C1 - =IF(A1<>"", B1, "")
range("C1").formula = "=IF(A1<>"""", B1, """")"         '<~quote chars doubled up
range("C1").formula = "=IF(A1<>TEXT(,), B1, TEXT(,))"   '<~with TEXT(,) instead

To my eye, using TEXT(,) in place of "" cleans up even a simple formula like the one above. The benefits become increasingly significant when used in more complicated formulas like the practise of appending an empty string to a VLOOKUP to avoid returning a zero to the cell when a lookup results in a blank or returning an empty string on no-match with IFERROR.

'formula to insert into D1 - =IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&"", "")
range("D1").formula = "=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&"""", """")"
range("D1").formula = "=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&TEXT(,), TEXT(,))"

With TEXT(,) replacing the old "" method of delivering an empty string, you might get to stop using an abacus to determine whether you have the right number of quote characters in a formula string.

Select rows with same id but different value in another column

Join the same table back to itself. Use an inner join so that rows that don't match are discarded. In the joined set, there will be rows that have a matching ARIDNR in another row in the table with a different LIEFNR. Allow those ARIDNR to appear in the final set.

SELECT * FROM YourTable WHERE ARIDNR IN (
    SELECT a.ARIDNR FROM YourTable a
    JOIN YourTable b on b.ARIDNR = a.ARIDNR AND b.LIEFNR <> a.LIEFNR
)

Get counts of all tables in a schema

If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:

select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;

Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.

Python 2,3 Convert Integer to "bytes" Cleanly

from int to byte:

bytes_string = int_v.to_bytes( lenth, endian )

where the lenth is 1/2/3/4...., and endian could be 'big' or 'little'

form bytes to int:

data_list = list( bytes );

Insert multiple rows with one query MySQL

While inserting multiple rows with a single INSERT statement is generally faster, it leads to a more complicated and often unsafe code. Below I present the best practices when it comes to inserting multiple records in one go using PHP.

To insert multiple new rows into the database at the same time, one needs to follow the following 3 steps:

  1. Start transaction (disable autocommit mode)
  2. Prepare INSERT statement
  3. Execute it multiple times

Using database transactions ensures that the data is saved in one piece and significantly improves performance.

How to properly insert multiple rows using PDO

PDO is the most common choice of database extension in PHP and inserting multiple records with PDO is quite simple.

$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

// Start transaction
$pdo->beginTransaction();

// Prepare statement
$stmt = $pdo->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // All seven parameters are passed into the execute() in a form of an array
    $stmt->execute([$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
}

// Commit the data into the database
$pdo->commit();

How to properly insert multiple rows using mysqli

The mysqli extension is a little bit more cumbersome to use but operates on very similar principles. The function names are different and take slightly different parameters.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');
$mysqli->set_charset('utf8mb4');

// Start transaction
$mysqli->begin_transaction();

// Prepare statement
$stmt = $mysqli->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // mysqli doesn't accept bind in execute yet, so we have to bind the data first
    // The first argument is a list of letters denoting types of parameters. It's best to use 's' for all unless you need a specific type
    // bind_param doesn't accept an array so we need to unpack it first using '...'
    $stmt->bind_param('sssssss', ...[$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
    $stmt->execute();
}

// Commit the data into the database
$mysqli->commit();

Performance

Both extensions offer the ability to use transactions. Executing prepared statement with transactions greatly improves performance, but it's still not as good as a single SQL query. However, the difference is so negligible that for the sake of conciseness and clean code it is perfectly acceptable to execute prepared statements multiple times. If you need a faster option to insert many records into the database at once, then chances are that PHP is not the right tool.

Process list on Linux via Python

I would use the subprocess module to execute the command ps with appropriate options. By adding options you can modify which processes you see. Lot's of examples on subprocess on SO. This question answers how to parse the output of ps for example:)

You can, as one of the example answers showed also use the PSI module to access system information (such as the process table in this example).

Make footer stick to bottom of page correctly

Use this one. It will fix it.

#ibox_footer {
    padding-top: 3px; 
    position: absolute;
    height: 20px;
    margin-bottom: 0;
    bottom: 0;
    width: 100%;
}

How to compare two lists in python?

Given the code you provided in comments, I assume you want to do this:

>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false

The split-method of the string returns a list. A list in Python is very different from an array. == in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

Android Closing Activity Programmatically

You Can use just finish(); everywhere after Activity Start for clear that Activity from Stack.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Python multiprocessing PicklingError: Can't pickle <type 'function'>

I'd use pathos.multiprocesssing, instead of multiprocessing. pathos.multiprocessing is a fork of multiprocessing that uses dill. dill can serialize almost anything in python, so you are able to send a lot more around in parallel. The pathos fork also has the ability to work directly with multiple argument functions, as you need for class methods.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> p = Pool(4)
>>> class Test(object):
...   def plus(self, x, y): 
...     return x+y
... 
>>> t = Test()
>>> p.map(t.plus, x, y)
[4, 6, 8, 10]
>>> 
>>> class Foo(object):
...   @staticmethod
...   def work(self, x):
...     return x+1
... 
>>> f = Foo()
>>> p.apipe(f.work, f, 100)
<processing.pool.ApplyResult object at 0x10504f8d0>
>>> res = _
>>> res.get()
101

Get pathos (and if you like, dill) here: https://github.com/uqfoundation

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Installing PDO driver on MySQL Linux server

Basically the answer from Jani Hartikainen is right! I upvoted his answer. What was missing on my system (based on Ubuntu 15.04) was to enable PDO Extension in my php.ini

extension=pdo.so
extension=pdo_mysql.so

restart the webserver (e.g. with "sudo service apache2 restart") -> every fine :-)

To find where your current active php.ini file is located you can use phpinfo() or some other hints from here: https://www.ostraining.com/blog/coding/phpini-file/

What is the color code for transparency in CSS?

how to make transparent elements with css:

CSS for IE:

filter: alpha(opacity = 52);

CSS for other browsers:

opacity:0.52;

Inserting HTML into a div

As alternative you can use insertAdjacentHTML - however I dig into and make some performance tests - (2019.09.13 Friday) MacOs High Sierra 10.13.6 on Chrome 76.0.3809 (64-bit), Safari 12.1.2 (13604.5.6), Firefox 69.0.0 (64-bit) ). The test F is only for reference - it is out of the question scope because we need to insert dynamically html - but in F I do it by 'hand' (in static way) - theoretically (as far I know) this should be the fastest way to insert new html elements.

enter image description here

SUMMARY

  • The A innerHTML = (do not confuse with +=) is fastest (Safari 48k operations per second, Firefox 43k op/sec, Chrome 23k op/sec) The A is ~31% slower than ideal solution F only chrome but on safari and firefox is faster (!)
  • The B innerHTML +=... is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)
  • The D jQuery is second slow on all browsers (Safari 14 op/sec, Firefox 11k op/sec, Chrome 7k op/sec)
  • The reference solution F (theoretically fastest) is not fastest on firefox and safari (!!!) - which is surprising
  • The fastest browser was Safari

More info about why innerHTML = is much faster than innerHTML += is here. You can perform test on your machine/browser HERE

_x000D_
_x000D_
let html = "<div class='box'>Hello <span class='msg'>World</span> !!!</div>"_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML = `<div id="A_oiio">A: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML += `<div id="B_oiio">B: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  container.insertAdjacentHTML('beforeend', `<div id="C_oiio">C: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function D() {    _x000D_
  $('#container').append(`<div id="D_oiio">D: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function E() {_x000D_
  let d = document.createElement("div");_x000D_
  d.innerHTML = `E: ${html}`;_x000D_
  d.id = 'E_oiio';_x000D_
  container.appendChild(d);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  let dm = document.createElement("div");_x000D_
  dm.id = "F_oiio";_x000D_
  dm.appendChild(document.createTextNode("F: "));_x000D_
_x000D_
  let d = document.createElement("div");_x000D_
  d.classList.add('box');_x000D_
  d.appendChild(document.createTextNode("Hello "));_x000D_
  _x000D_
  let s = document.createElement("span");_x000D_
  s.classList.add('msg');_x000D_
  s.appendChild(document.createTextNode("World"));_x000D_
_x000D_
  d.appendChild(s);_x000D_
  d.appendChild(document.createTextNode(" !!!"));_x000D_
  dm.appendChild( d );_x000D_
  _x000D_
  container.appendChild(dm);_x000D_
}_x000D_
_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
.warr { color: red } .msg { color: blue } .box {display: inline}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="warr">This snippet only for show code used in test (in jsperf.com) - it not perform test itself. </div>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Create table using Javascript

I hope you find this helpful.

HTML :

<html>
<head>
    <link rel = "stylesheet" href = "test.css">
<body>

</body>
<script src = "test.js"></script>
</head>
</html>

JAVASCRIPT :

var tableString = "<table>",
    body = document.getElementsByTagName('body')[0],
    div = document.createElement('div');

for (row = 1; row < 101; row += 1) {

    tableString += "<tr>";

    for (col = 1; col < 11; col += 1) {

        tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
    }
    tableString += "</tr>";
}

tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);

How to make layout with View fill the remaining space?

You should avoid nesting 2 relative layout since relative layout always make 2 pass for drawing (against 1 for any other type of layout). It becomes exponential when you nest them. You should use linear layout with width=0 and weight=1 on the element you want to fill the space left. This answer is better for performance and the practices. Remember: use relative layout ONLY when you don't have other choice.

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

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/prev_button"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="&lt;" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ellipsize="end"
            android:singleLine="true"
            android:gravity="center"
            android:text="TextView" />

        <Button
            android:id="@+id/next_button"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="&gt;" />
    </LinearLayout>
</LinearLayout>

How to declare std::unique_ptr and what is the use of it?

Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr

In this case:

unique_ptr<double> uptr2 (pd);

pd will be destroyed when uptr2 goes out of scope. This facilitates memory management by automatic deletion.

The case of unique_ptr<int> uptr (new int(3)); is not different, except that the raw pointer is not assigned to any variable here.

How to convert an NSString into an NSNumber

you can also do like this code 8.3.3 ios 10.3 support

[NSNumber numberWithInt:[@"put your string here" intValue]]

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Another way to wait for maximum of certain amount say 10 seconds of time for the element to be displayed as below:

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.findElement(By.id("<name>")).isDisplayed();

            }
        });

HTML button calling an MVC Controller and Action method

Despite onclick Method you can also use formaction as follows:

<button type="submit" id="button1" name="button1" formaction='@Url.Action("Action", "Controller")'>Save</button>

Visibility of global variables in imported modules

This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don't work for you if you made the same thing I did below.

Namely, I have a module which contains global/shared variables (as suggested above):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

Then I had the main module which imports the shared stuff with:

import sharedstuff as shared

and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:

from globals import *

it worked (the arrays were populated).

Just sayin'

Hive External Table Skip First Row

Just append below property in your query and the first header or line int the record will not load or it will be skipped.

Try this

tblproperties ("skip.header.line.count"="1");

Lock, mutex, semaphore... what's the difference?

It is a general vision. Details are depended on real language realisation

lock - thread synchronization tool. When thread get a lock it becomes a single thread which is able to execute a block of code. All others thread are blocked. Only thread which owns by lock can unlock it

mutex - mutual exclusion lock. It is a kind of lock. On some languages it is inter-process mechanism, on some languages it is a synonym of lock. For example Java uses lock in synchronised and java.util.concurrent.locks.Lock

semaphore - allows a number of threads to access a shared resource. You can find that mutex also can be implemented by semaphore. It is a standalone object which manage an access to shared resource. You can find that any thread can signal and unblock. Also it is used for signalling

[iOS lock, mutex, semaphore]

Default background color of SVG root element

I'm currently working on a file like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="style.css" ?>
<svg
  xmlns="http://www.w3.org/2000/svg"
  version="1.1"
  width="100%"
  height="100%"
  viewBox="0 0 600 600">
...

And I tried to put this into style.css:

svg {
  background: #bf1f1f;
}

It's working on Chromium and Firefox, but I don't think that it's a good practice. EyeOfGnome image viewer doesn't render it, and Inkscape uses a special namespace to store such a background:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
    xmlns="http://www.w3.org/2000/svg"
    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
    version="1.1"
    ...
  <sodipodi:namedview
     pagecolor="#480000" ... >

Well, it seems that SVG root element is not part of paintable elements in SVG recommandations.

So I'd suggest to use the "rect" solution provided by Robert Longson because I guess that it is not a simple "hack". It seems to be the standard way to set a background with SVG.

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

How can I include css files using node, express, and ejs?

The above responses half worked and I'm not why they didn't on my machine but I had to do the following for it work.

  1. Created a directory at the root

    /public/js/

  2. Paste this into your server.js file with name matching the name of directory created above. Note adding /public as the first param

    app.use('/public',express.static('public'));

  3. Finally in the HTML page to which to import the javascript file into,

    <script src="public/js/bundle.js"></script>

Parsing huge logfiles in Node.js - read in line-by-line

You can use the inbuilt readline package, see docs here. I use stream to create a new output stream.

var fs = require('fs'),
    readline = require('readline'),
    stream = require('stream');

var instream = fs.createReadStream('/path/to/file');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;

var rl = readline.createInterface({
    input: instream,
    output: outstream,
    terminal: false
});

rl.on('line', function(line) {
    console.log(line);
    //Do your stuff ...
    //Then write to outstream
    rl.write(cubestuff);
});

Large files will take some time to process. Do tell if it works.

How do I convert NSInteger to NSString datatype?

%zd works for NSIntegers (%tu for NSUInteger) with no casts and no warnings on both 32-bit and 64-bit architectures. I have no idea why this is not the "recommended way".

NSString *string = [NSString stringWithFormat:@"%zd", month];

If you're interested in why this works see this question.

Adding values to an array in java

  • First line : array created.
  • Third line loop started from j = 1 to j = 28123
  • Fourth line you give the variable x value (0) each time the loop is accessed.
  • Fifth line you put the value of j in the index 0.
  • Sixth line you do increment to the value x by 1.(but it will be reset to 0 at line 4)

Local storage in Angular 2

install

npm install --save @ngx-pwa/local-storage

first of all you need to Install "angular-2-local-storage"

import { LocalStorageService } from 'angular-2-local-storage';

Save into LocalStorage:

localStorage.setItem('key', value);

Get From Local Storage:

localStorage.getItem('key');

How to Convert Int to Unsigned Byte and Back

The solution works fine (thanks!), but if you want to avoid casting and leave the low level work to the JDK, you can use a DataOutputStream to write your int's and a DataInputStream to read them back in. They are automatically treated as unsigned bytes then:

For converting int's to binary bytes;

ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
int val = 250;
dos.write(byteVal);
...
dos.flush();

Reading them back in:

// important to use a (non-Unicode!) encoding like US_ASCII or ISO-8859-1,
// i.e., one that uses one byte per character
ByteArrayInputStream bis = new ByteArrayInputStream(
   bos.toString("ISO-8859-1").getBytes("ISO-8859-1"));
DataInputStream dis = new DataInputStream(bis);
int byteVal = dis.readUnsignedByte();

Esp. useful for handling binary data formats (e.g. flat message formats, etc.)

key_load_public: invalid format

If you're using Windows 10 with the built-in SSH, as of August 2020 it only supports ed25519 keys. You'll get the key_load_public: invalid format error if you use e.g. an RSA key.

As per this GitHub issue it should be fixed via Windows Update some time in 2020. So one solution is to just wait for the update to ship.

If you can't wait, a workaround is to generate a new ed25519 key, which is good advice anyway.

> ssh-keygen -o -a 100 -t ed25519

You can use it with e.g. github, but some older systems might not support this newer format.

After generating your key, if you're using either of the below features, don't forget to update them!

  1. ~\.ssh\config might still point to the old key.
  2. Add the new key to ssh-agent via the ssh-add command

Display open transactions in MySQL

By using this query you can see all open transactions.

List All:

SHOW FULL PROCESSLIST  

if you want to kill a hang transaction copy transaction id and kill transaction by using this command:

KILL <id>    // e.g KILL 16543

List of standard lengths for database fields

UK Government Data Standards Catalogue details the UK standards for this kind of thing. It suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name, and 255 characters for an email address. Amongst other things..

How to find my php-fpm.sock?

I faced this same issue on CentOS 7 years later

Posting hoping that it may help others...

Steps:

FIRST, configure the php-fpm settings:

-> systemctl stop php-fpm.service

-> cd /etc/php-fpm.d

-> ls -hal (should see a www.conf file)

-> cp www.conf www.conf.backup (back file up just in case)

-> vi www.conf

-> :/listen = (to get to the line we need to change)

-> i (to enter VI's text insertion mode)

-> change from listen = 127.0.0.1:9000 TO listen = /var/run/php-fpm/php-fpm.sock

-> Esc then :/listen.owner (to find it) then i (to change)

-> UNCOMMENT the listen.owner = nobody AND listen.group = nobody lines

-> Hit Esc then type :/user = then i

-> change user = apache TO user = nginx

-> AND change group = apache TO group = nginx

-> Hit Esc then :wq (to save and quit)

-> systemctl start php-fpm.service (now you will have a php-fpm.sock file)

SECOND, you configure your server {} block in your /etc/nginx/nginx.conf file. Then run:systemctl restart nginx.service

FINALLY, create a new .php file in your /usr/share/nginx/html directory for your Nginx server to serve up via the internet browser as a test.

-> vi /usr/share/nginx/html/mytest.php

-> type o

-> <?php echo date("Y/m/d-l"); ?> (PHP page will print date and day in browser)

-> Hit Esc

-> type :wq (to save and quite VI editor)

-> open up a browser and go to: http://yourDomainOrIPAddress/mytest.php (you should see the date and day printed)

How to go back (ctrl+z) in vi/vim

You can use the u button to undo the last modification. (And Ctrl+R to redo it).

Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

I think the solution is to combine techniques from video encoding, namely the discrete cosine transformation. In digital video, rather recording the changing the brightness or colour of video as regular values such as 110 112 115 116, each is subtracted from the last (similar to run length encoding). 110 112 115 116 becomes 110 2 3 1. The values, 2 3 1 require less bits than the originals.

So lets say we create a list of the input values as they arrive on the socket. We are storing in each element, not the value, but the offset of the one before it. We sort as we go, so the offsets are only going to be positive. But the offset could be 8 decimal digits wide which this fits in 3 bytes. Each element can't be 3 bytes, so we need to pack these. We could use the top bit of each byte as a "continue bit", indicating that the next byte is part of the number and the lower 7 bits of each byte need to be combined. zero is valid for duplicates.

As the list fills up, the numbers should be get closer together, meaning on average only 1 byte is used to determine the distance to the next value. 7 bits of value and 1 bit of offset if convenient, but there may be a sweet spot that requires less than 8 bits for a "continue" value.

Anyway, I did some experiment. I use a random number generator and I can fit a million sorted 8 digit decimal numbers into about 1279000 bytes. The average space between each number is consistently 99...

public class Test {
    public static void main(String[] args) throws IOException {
        // 1 million values
        int[] values = new int[1000000];

        // create random values up to 8 digits lrong
        Random random = new Random();
        for (int x=0;x<values.length;x++) {
            values[x] = random.nextInt(100000000);
        }
        Arrays.sort(values);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int av = 0;    
        writeCompact(baos, values[0]);     // first value
        for (int x=1;x<values.length;x++) {
            int v = values[x] - values[x-1];  // difference
            av += v;
            System.out.println(values[x] + " diff " + v);
            writeCompact(baos, v);
        }

        System.out.println("Average offset " + (av/values.length));
        System.out.println("Fits in " + baos.toByteArray().length);
    }

    public static void writeCompact(OutputStream os, long value) throws IOException {
        do {
            int b = (int) value & 0x7f;
            value = (value & 0x7fffffffffffffffl) >> 7;
            os.write(value == 0 ? b : (b | 0x80));
        } while (value != 0);
    }
}

swift 3.0 Data to String?

To extend on the answer of weijia.wang:

extension Data {
    func hexString() -> String {
        let nsdataStr = NSData.init(data: self)
        return nsdataStr.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
    }
}

use it with deviceToken.hexString()

specifying goal in pom.xml

Add the goal like -

 <build>
        <defaultGoal>install</defaultGoal>
        <!-- Source directory configuration -->
        <sourceDirectory>src</sourceDirectory>
</build>

This will solve the issue

How do I properly escape quotes inside HTML attributes?

If you are using Javascript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.

See here: https://lodash.com/docs/#escape

Android DialogFragment vs Dialog

Yes, use DialogFragment and in onCreateDialog you can simply use an AlertDialog builder anyway to create a simple AlertDialog with Yes/No confirmation buttons. Not very much code at all.

With regards handling events in your fragment there would be various ways of doing it but I simply define a message Handler in my Fragment, pass it into the DialogFragment via its constructor and then pass messages back to my fragment's handler as approprirate on the various click events. Again various ways of doing that but the following works for me.

In the dialog hold a message and instantiate it in the constructor:

private Message okMessage;
...
okMessage = handler.obtainMessage(MY_MSG_WHAT, MY_MSG_OK);

Implement the onClickListener in your dialog and then call the handler as appropriate:

public void onClick(.....
    if (which == DialogInterface.BUTTON_POSITIVE) {
        final Message toSend = Message.obtain(okMessage);
        toSend.sendToTarget();
    }
 }

Edit

And as Message is parcelable you can save it out in onSaveInstanceState and restore it

outState.putParcelable("okMessage", okMessage);

Then in onCreate

if (savedInstanceState != null) {
    okMessage = savedInstanceState.getParcelable("okMessage");
}

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

What is the difference between gravity and layout_gravity in Android?

Inside - Outside

  • gravity arranges the content inside the view.
  • layout_gravity arranges the view's position outside of itself.

Sometimes it helps to see a picture, too. The green and blue are TextViews and the other two background colors are LinearLayouts.

enter image description here

Notes

  • The layout_gravity does not work for views in a RelativeLayout. Use it for views in a LinearLayout or FrameLayout. See my supplemental answer for more details.
  • The view's width (or height) has to be greater than its content. Otherwise gravity won't have any effect. Thus, wrap_content and gravity are meaningless together.
  • The view's width (or height) has to be less than the parent. Otherwise layout_gravity won't have any effect. Thus, match_parent and layout_gravity are meaningless together.
  • The layout_gravity=center looks the same as layout_gravity=center_horizontal here because they are in a vertical linear layout. You can't center vertically in this case, so layout_gravity=center only centers horizontally.
  • This answer only dealt with setting gravity and layout_gravity on the views within a layout. To see what happens when you set the gravity of the of the parent layout itself, check out the supplemental answer that I referred to above. (Summary: gravity doesn't work well on a RelativeLayout but can be useful with a LinearLayout.)

So remember, layout_gravity arranges a view in its layout. Gravity arranges the content inside the view.

xml

Here is the xml for the above image for your reference:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#e3e2ad"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="24sp"
            android:text="gravity=" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#bcf5b1"
            android:gravity="left"
            android:text="left" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#aacaff"
            android:gravity="center_horizontal"
            android:text="center_horizontal" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#bcf5b1"
            android:gravity="right"
            android:text="right" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#aacaff"
            android:gravity="center"
            android:text="center" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#d6c6cd"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="24sp"
            android:text="layout_gravity=" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="left"
            android:background="#bcf5b1"
            android:text="left" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal"
            android:background="#aacaff"
            android:text="center_horizontal" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="right"
            android:background="#bcf5b1"
            android:text="right" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:background="#aacaff"
            android:text="center" />

    </LinearLayout>

</LinearLayout>

Related

What is the best way to programmatically detect porn images?

This was written in 2000, not sure if the state of the art in porn detection has advanced at all, but I doubt it.

http://www.dansdata.com/pornsweeper.htm

PORNsweeper seems to have some ability to distinguish pictures of people from pictures of things that aren't people, as long as the pictures are in colour. It is less successful at distinguishing dirty pictures of people from clean ones.

With the default, medium sensitivity, if Human Resources sends around a picture of the new chap in Accounts, you've got about a 50% chance of getting it. If your sister sends you a picture of her six-month-old, it's similarly likely to be detained.

It's only fair to point out amusing errors, like calling the Mona Lisa porn, if they're representative of the behaviour of the software. If the makers admit that their algorithmic image recogniser will drop the ball 15% of the time, then making fun of it when it does exactly that is silly.

But PORNsweeper only seems to live up to its stated specifications in one department - detection of actual porn. It's half-way decent at detecting porn, but it's bad at detecting clean pictures. And I wouldn't be surprised if no major leaps were made in this area in the near future.

Is it possible to use 'else' in a list comprehension?

The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

So for your example,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))

How do I "break" out of an if statement?

The || and && operators are short circuit, so if the left side of || evaluates to true or the left side of && evaluates to false, the right side will not be evaluated. That's equivalent to a break.

If else on WHERE clause

Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE `email` LIKE  '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE  '%[email protected]%')

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox, then compile and run.

class myclass
{
     public static void Main(string[] args)
     {
         unsafe
         {
             int iData = 10;
             int* pData = &iData;
             Console.WriteLine("Data is " + iData);
             Console.WriteLine("Address is " + (int)pData);
         }
     }
}

Output:

Data is 10
Address is 1831848

How to compile and run C/C++ in a Unix console/Mac terminal?

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

echo $PATH

On Mac OS X (by default) this will display the following colon separated search path:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

So any executable in the listed directories can by run just by typing in their name. For example:

cat mytextfile.txt

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

/Users/oliver/MyProgram

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

MyProject/MyProgram

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

../MyProject/MyProgram

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

./MyProgram

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

What is the default Precision and Scale for a Number in Oracle?

I expand on spectra‘s answer so people don’t have to try it for themselves.

This was done on Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production.

CREATE TABLE CUSTOMERS
(
  CUSTOMER_ID NUMBER NOT NULL,
  FOO FLOAT NOT NULL,
  JOIN_DATE DATE NOT NULL,
  CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
  CUSTOMER_NAME VARCHAR2(20) NOT NULL,
  CREDITRATING VARCHAR2(10)
);

select column_name, data_type, nullable, data_length, data_precision, data_scale
from user_tab_columns where table_name ='CUSTOMERS'; 

Which yields

COLUMN_NAME      DATA_TYPE  NULLABLE DATA_LENGTH DATA_PRECISION DATA_SCALE
CUSTOMER_ID      NUMBER     N        22        
FOO              FLOAT      N        22          126    
JOIN_DATE        DATE       N        7        
CUSTOMER_STATUS  VARCHAR2   N        8        
CUSTOMER_NAME    VARCHAR2   N        20        
CREDITRATING     VARCHAR2   Y        10    

How to print a list with integers without the brackets, commas and no quotes?

If you're using Python 3, or appropriate Python 2.x version with from __future__ import print_function then:

data = [7, 7, 7, 7]
print(*data, sep='')

Otherwise, you'll need to convert to string and print:

print ''.join(map(str, data))

I get exception when using Thread.sleep(x) or wait()

public static void main(String[] args) throws InterruptedException {
  //type code


  short z=1000;
  Thread.sleep(z);/*will provide 1 second delay. alter data type of z or value of z for longer delays required */

  //type code
}

eg:-

class TypeCasting {

  public static void main(String[] args) throws InterruptedException {
    short f = 1;
    int a = 123687889;
    short b = 2;
    long c = 4567;
    long d=45;
    short z=1000;
    System.out.println("Value of a,b and c are\n" + a + "\n" + b + "\n" + c + "respectively");
    c = a;
    b = (short) c;
    System.out.println("Typecasting...........");
    Thread.sleep(z);
    System.out.println("Value of B after Typecasting" + b);
    System.out.println("Value of A is" + a);


  }
}

SQL Sum Multiple rows into one

I tried this, but the query won't run telling me my field is invalid in the select statement because it is not contained in either an aggregate function or the GROUP BY clause. It's forcing me to keep it there. Is there a way around this?

You need to do a self-join. You can't both aggregate and preserve non-aggregated data in the same subquery. E.g.

select q2.AccountNumber, q2.Bill, q2.BillDate, q1.BillSum
from
(
SELECT AccountNumber, SUM(Bill) as BillSum
FROM Table1
GROUP BY AccountNumber
) q1,
(
select AccountNumber, Bill, BillDate
from table1
) q2
where q1.AccountNumber = q2.AccountNumber

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Is there a way to return a list of all the image file names from a folder using only Javascript?

This will list all jpg files in the folder you define under url: and append them to a div as a paragraph. Can do it with ul li as well.

$.ajax({
  url: "YOUR FOLDER",
  success: function(data){
     $(data).find("a:contains(.jpg)").each(function(){
        // will loop through 
        var images = $(this).attr("href");

        $('<p></p>').html(images).appendTo('a div of your choice')

     });
  }
});

From io.Reader to string in Go

I like the bytes.Buffer struct. I see it has ReadFrom and String methods. I've used it with a []byte but not an io.Reader.

javascript date to string

You will need to pad with "0" if its a single digit & note getMonth returns 0..11 not 1..12

function printDate() {
    var temp = new Date();
    var dateStr = padStr(temp.getFullYear()) +
                  padStr(1 + temp.getMonth()) +
                  padStr(temp.getDate()) +
                  padStr(temp.getHours()) +
                  padStr(temp.getMinutes()) +
                  padStr(temp.getSeconds());
    debug (dateStr );
}

function padStr(i) {
    return (i < 10) ? "0" + i : "" + i;
}

How to find tag with particular text with Beautiful Soup?

With bs4 4.7.1+ you can use :contains pseudo class to specify the td containing your search string

from bs4 import BeautifulSoup
html = '''
<tr>
  <td class="pos">\n
      "Some text:"\n
      <br>\n
      <strong>some value</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Fixed text:"\n
      <br>\n
      <strong>text I am looking for</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Some other text:"\n
      <br>\n
      <strong>some other value</strong>\n
  </td>
</tr>'''
soup = bs(html, 'lxml')
print(soup.select_one('td:contains("Fixed text:")'))

Reverse of JSON.stringify?

How about this

var parsed = new Function('return ' + stringifiedJSON )();

This is a safer alternative for eval.

_x000D_
_x000D_
var stringifiedJSON = '{"hello":"world"}';_x000D_
var parsed = new Function('return ' + stringifiedJSON)();_x000D_
alert(parsed.hello);
_x000D_
_x000D_
_x000D_

How to read a local text file?

_x000D_
_x000D_
var input = document.getElementById("myFile");_x000D_
var output = document.getElementById("output");_x000D_
_x000D_
_x000D_
input.addEventListener("change", function () {_x000D_
  if (this.files && this.files[0]) {_x000D_
    var myFile = this.files[0];_x000D_
    var reader = new FileReader();_x000D_
    _x000D_
    reader.addEventListener('load', function (e) {_x000D_
      output.textContent = e.target.result;_x000D_
    });_x000D_
    _x000D_
    reader.readAsBinaryString(myFile);_x000D_
  }   _x000D_
});
_x000D_
<input type="file" id="myFile">_x000D_
<hr>_x000D_
<textarea style="width:500px;height: 400px" id="output"></textarea>
_x000D_
_x000D_
_x000D_

Trigger standard HTML5 validation (form) without using submit button?

form.submit() doesn't work cause the HTML5 validation is performed before the form submition. When you click on a submit button, the HTML5 validation is trigerred and then the form is submited if validation was successfull.

How do I set up access control in SVN?

In your svn\repos\YourRepo\conf folder you will find two files, authz and passwd. These are the two you need to adjust.

In the passwd file you need to add some usernames and passwords. I assume you have already done this since you have people using it:

[users]
User1=password1
User2=password2

Then you want to assign permissions accordingly with the authz file:

Create the conceptual groups you want, and add people to it:

[groups]
allaccess = user1
someaccess = user2

Then choose what access they have from both the permissions and project level.

So let's give our "all access" guys all access from the root:

[/]
@allaccess = rw

But only give our "some access" guys read-only access to some lower level project:

[/someproject]
@someaccess = r

You will also find some simple documentation in the authz and passwd files.

Open youtube video in Fancybox jquery

If you wanna add autoplay function to it. Simply replace

this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), 

with

this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',

also you can do the same with vimeo

this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),

with

this.href = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1') + '&autoplay=1',

How to use cURL to send Cookies?

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line

127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

ORA-01438: value larger than specified precision allows for this column

Further to previous answers, you should note that a column defined as VARCHARS(10) will store 10 bytes, not 10 characters unless you define it as VARCHAR2(10 CHAR)

[The OP's question seems to be number related... this is just in case anyone else has a similar issue]

Add custom message to thrown exception while maintaining stack trace in Java

Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:

throw new TransactionProblemException(transNbr, originalException);

The stack trace will look like

TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...

How do I assert equality on two classes without an equals method?

Can you put the comparision code you posted into some static utility method?

public static String findDifference(Type obj1, Type obj2) {
    String difference = "";
    if (obj1.getFieldA() == null && obj2.getFieldA() != null
            || !obj1.getFieldA().equals(obj2.getFieldA())) {
        difference += "Difference at field A:" + "obj1 - "
                + obj1.getFieldA() + ", obj2 - " + obj2.getFieldA();
    }
    if (obj1.getFieldB() == null && obj2.getFieldB() != null
            || !obj1.getFieldB().equals(obj2.getFieldB())) {
        difference += "Difference at field B:" + "obj1 - "
                + obj1.getFieldB() + ", obj2 - " + obj2.getFieldB();
        // (...)
    }
    return difference;
}

Than you can use this method in JUnit like this:

assertEquals("Objects aren't equal", "", findDifferences(obj1, obj));

which isn't clunky and gives you full information about differences, if they exist (through not exactly in normal form of assertEqual but you get all the info so it should be good).

How to convert a String to JsonObject using gson library

String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

I do this, and it worked.

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

concat scope variables into string in angular directive expression

You can just concat the values using +

<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>

Simple example on jsfiddle

I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

What is the default access modifier in Java?

No, you can't call the default access level to the other package. But you have the access within the package. Follow this link for more details.

Convert decimal to binary in python

Without the 0b in front:

"{0:b}".format(int)

Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:

f"{int:b}"

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

Adding an arbitrary line to a matplotlib plot in ipython notebook

It's not too late for the newcomers.

plt.axvline(x, color='r')

It takes the range of y as well, using ymin and ymax.

How can I show/hide component with JSF?

Use the "rendered" attribute available on most if not all tags in the h-namespace.

<h:outputText value="Hi George" rendered="#{Person.name == 'George'}" />

Switch statement for greater-than/less-than

When I looked at the solutions in the other answers I saw some things that I know are bad for performance. I was going to put them in a comment but I thought it was better to benchmark it and share the results. You can test it yourself. Below are my results (ymmv) normalized after the fastest operation in each browser (multiply the 1.0 time with the normalized value to get the absolute time in ms).

                    Chrome  Firefox Opera   MSIE    Safari  Node
-------------------------------------------------------------------
1.0 time               37ms    73ms    68ms   184ms    73ms    21ms
if-immediate            1.0     1.0     1.0     2.6     1.0     1.0
if-indirect             1.2     1.8     3.3     3.8     2.6     1.0
switch-immediate        2.0     1.1     2.0     1.0     2.8     1.3
switch-range           38.1    10.6     2.6     7.3    20.9    10.4
switch-range2          31.9     8.3     2.0     4.5     9.5     6.9
switch-indirect-array  35.2     9.6     4.2     5.5    10.7     8.6
array-linear-switch     3.6     4.1     4.5    10.0     4.7     2.7
array-binary-switch     7.8     6.7     9.5    16.0    15.0     4.9

Test where performed on Windows 7 32bit with the folowing versions: Chrome 21.0.1180.89m, Firefox 15.0, Opera 12.02, MSIE 9.0.8112, Safari 5.1.7. Node was run on a Linux 64bit box because the timer resolution on Node.js for Windows was 10ms instead of 1ms.

if-immediate

This is the fastest in all tested environments, except in ... drumroll MSIE! (surprise, surprise). This is the recommended way to implement it.

if (val < 1000) { /*do something */ } else
if (val < 2000) { /*do something */ } else
...
if (val < 30000) { /*do something */ } else

if-indirect

This is a variant of switch-indirect-array but with if-statements instead and performs much faster than switch-indirect-array in almost all tested environments.

values=[
   1000,  2000, ... 30000
];
if (val < values[0]) { /* do something */ } else
if (val < values[1]) { /* do something */ } else
...
if (val < values[29]) { /* do something */ } else

switch-immediate

This is pretty fast in all tested environments, and actually the fastest in MSIE. It works when you can do a calculation to get an index.

switch (Math.floor(val/1000)) {
  case 0: /* do something */ break;
  case 1: /* do something */ break;
  ...
  case 29: /* do something */ break;
}

switch-range

This is about 6 to 40 times slower than the fastest in all tested environments except for Opera where it takes about one and a half times as long. It is slow because the engine has to compare the value twice for each case. Surprisingly it takes Chrome almost 40 times longer to complete this compared to the fastest operation in Chrome, while MSIE only takes 6 times as long. But the actual time difference was only 74ms in favor to MSIE at 1337ms(!).

switch (true) {
  case (0 <= val &&  val < 1000): /* do something */ break;
  case (1000 <= val &&  val < 2000): /* do something */ break;
  ...
  case (29000 <= val &&  val < 30000): /* do something */ break;
}

switch-range2

This is a variant of switch-range but with only one compare per case and therefore faster, but still very slow except in Opera. The order of the case statement is important since the engine will test each case in source code order ECMAScript262:5 12.11

switch (true) {
  case (val < 1000): /* do something */ break;
  case (val < 2000): /* do something */ break;
  ...
  case (val < 30000): /* do something */ break;
}

switch-indirect-array

In this variant the ranges is stored in an array. This is slow in all tested environments and very slow in Chrome.

values=[1000,  2000 ... 29000, 30000];

switch(true) {
  case (val < values[0]): /* do something */ break;
  case (val < values[1]): /* do something */ break;
  ...
  case (val < values[29]): /* do something */ break;
}

array-linear-search

This is a combination of a linear search of values in an array, and the switch statement with fixed values. The reason one might want to use this is when the values isn't known until runtime. It is slow in every tested environment, and takes almost 10 times as long in MSIE.

values=[1000,  2000 ... 29000, 30000];

for (sidx=0, slen=values.length; sidx < slen; ++sidx) {
  if (val < values[sidx]) break;
}

switch (sidx) {
  case 0: /* do something */ break;
  case 1: /* do something */ break;
  ...
  case 29: /* do something */ break;
}

array-binary-switch

This is a variant of array-linear-switch but with a binary search. Unfortunately it is slower than the linear search. I don't know if it is my implementation or if the linear search is more optimized. It could also be that the keyspace is to small.

values=[0, 1000,  2000 ... 29000, 30000];

while(range) {
  range = Math.floor( (smax - smin) / 2 );
  sidx = smin + range;
  if ( val < values[sidx] ) { smax = sidx; } else { smin = sidx; }
}

switch (sidx) {
  case 0: /* do something */ break;
  ...
  case 29: /* do something */ break;
}

Conclusion

If performance is important, use if-statements or switch with immediate values.

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

Ternary operator ?: vs if...else

It is not faster. There is one difference when you can initialize a constant variable depending on some expression:

const int x = (a<b) ? b : a;

You can't do the same with if-else.

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

Deserializing JSON array into strongly typed .NET object

This worked for me for deserializing JSON into an array of objects:

List<TheUser> friends = JsonConvert.DeserializeObject<List<TheUser>>(response);

ArrayList of String Arrays

Following works in Java 8..

List<String[]> addresses = new ArrayList<>();

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Try writing the file path as "C:\\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener" i.e with double backslash after the drive as opposed to "C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener"

How can I remove the top and right axis in matplotlib?

Alternatively, this

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).

How to append elements into a dictionary in Swift?

As of Swift 5, the following code collection works.

 // main dict to start with
 var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]

 // dict(s) to be added to main dict
 let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
 let myDictUpdated : Dictionary = [ 5 : "lmn"]
 let myDictToBeMapped : Dictionary = [ 6 : "opq"]

 myDict[3]="fgh"
 myDict.updateValue("ijk", forKey: 4)

 myDict.merge(myDictToMergeWith){(current, _) in current}
 print(myDict)

 myDict.merge(myDictUpdated){(_, new) in new}
 print(myDict)

 myDictToBeMapped.map {
     myDict[$0.0] = $0.1
 }
 print(myDict)

Convert a python UTC datetime to a local datetime using only python standard library?

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

Getting all names in an enum as a String[]

Here's one-liner for any enum class:

public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}

Pre Java 8 is still a one-liner, albeit less elegant:

public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");
}

That you would call like this:

String[] names = getNames(State.class); // any other enum class will work

If you just want something simple for a hard-coded enum class:

public static String[] names() {
    return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", ");
}

CSS3 :unchecked pseudo-class

:unchecked is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.

In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked), it's safe to assume that there is no corresponding :unchecked pseudo. Browser support for :not() and :checked is identical, so that shouldn't be a problem.

This may seem inconsistent with the :enabled and :disabled states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.

(:indeterminate does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)

Adding a slide effect to bootstrap dropdown

For Bootstrap 3, this variation on the answers above makes the mobile slideUp() animation smoother; the answers above have choppy animation because Bootstrap removes the .open class from the toggle's parent immediately, so this code restores the class until the slideUp() animation is finished.

// Add animations to topnav dropdowns
// based on https://stackoverflow.com/a/19339162
// and https://stackoverflow.com/a/52231970

$('.dropdown')
  .on('show.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
  })
  .on('hide.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, false).slideUp(300, function() {
      $(this).parent().removeClass('open');
    });
  })
  .on('hidden.bs.dropdown', function() {
    $(this).addClass('open');
  });

Key differences:

  • In the hide.bs.dropdown event handler I'm using .stop()'s default value (false) for its second argument (jumpToEnd)
  • The hidden.bs.dropdown event handler restores the .open class to the dropdown toggle's parent, and it does this pretty much immediately after the class has been first removed. Meanwhile the slideUp() animation is still running, and just like in the answers above, its "the-animation-is-completed" callback is responsible for finally removing the .open class from its parent.
  • Methods are chained together because the selector for each event handler is the same

What is %timeit in python?

This is known as a line magic in iPython. They are unique in that their arguments only extend to the end of the current line, and magics themselves are really structured for command line development. timeit is used to time the execution of code.

If you wanted to see all of the magics you can use, you could simply type:

%lsmagic

to get a list of both line magics and cell magics.

Some further magic information from documentation here:

IPython has a system of commands we call magics that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.

Depending on whether you are in line or cell mode, there are two different ways to use %timeit. Your question illustrates the first way:

In [1]: %timeit range(100)

vs.

In [1]: %%timeit 
      : x = range(100)
      :

Store mysql query output into a shell variable

Another example when the table name or database contains unsupported characters such as a space, or '-'

db='data-base'

db_d=''
db_d+='`'
db_d+=$db
db_d+='`'

myvariable=`mysql --user=$user --password=$password -e "SELECT A, B, C FROM $db_d.table_a;"`

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

You are doing it right with ServerCertificateValidationCallback. This is not the problem you are facing. The problem you are facing is most likely the version of SSL/TLS protocol.

For example, if your server offers only SSLv3 and TLSv10 and your client needs TLSv12 then you will receive this error message. What you need to do is to make sure that both client and server have a common protocol version supported.

When I need a client that is able to connect to as many servers as possible (rather than to be as secure as possible) I use this (together with setting the validation callback):

  ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Bootstrap 4 - Glyphicons migration?

You can use both Font Awesome and Github Octicons as a free alternative for Glyphicons.

Bootstrap 4 also switched from Less to Sass, so you might integerate the font's Sass (SCSS) into you build process, to create a single CSS file for your projects.

Also see https://getbootstrap.com/docs/4.1/getting-started/build-tools/ to find out how to set up your tooling:

  1. Download and install Node, which we use to manage our dependencies.
  2. Navigate to the root /bootstrap directory and run npm install to install our local dependencies listed in package.json.
  3. Install Ruby, install Bundler with gem install bundler, and finally run bundle install. This will install all Ruby dependencies, such as Jekyll and plugins.

Font Awesome

  1. Download the files at https://github.com/FortAwesome/Font-Awesome/tree/fa-4
  2. Copy the font-awesome/scss folder into your /bootstrap folder
  3. Open your SCSS /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:

    $fa-font-path: "../fonts"; @import "../font-awesome/scss/font-awesome.scss";

  4. Notice that you also have to copy the font file from font-awesome/fonts to dist/fonts or any other public folder set by $fa-font-path in the previous step

  5. Run: npm run dist to recompile your code with Font-Awesome

Github Octicons

  1. Download the files at https://github.com/github/octicons/
  2. Copy the octicons folder into your /bootstrap folder
  3. Open your SCSS /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:

    $fa-font-path: "../fonts"; @import "../octicons/octicons/octicons.scss";

  4. Notice that you also have to copy the font file from font-awesome/fonts to dist/fonts or any other public folder set by $fa-font-path in the previous step

  5. Run: npm run dist to recompile your code with Octicons

Glyphicons

On the Bootstrap website you can read:

Includes over 250 glyphs in font format from the Glyphicon Halflings set. Glyphicons Halflings are normally not available for free, but their creator has made them available for Bootstrap free of cost. As a thank you, we only ask that you include a link back to Glyphicons whenever possible.

As I understand you can use these 250 glyphs free of cost restricted for Bootstrap but not limited to version 3 exclusive. So you can use them for Bootstrap 4 too.

  1. Copy the fonts files from: https://github.com/twbs/bootstrap-sass/tree/master/assets/fonts/bootstrap
  2. Copy the https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_glyphicons.scss file into your bootstrap/scss folder
  3. Open your scss /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:
$bootstrap-sass-asset-helper: false;
$icon-font-name: 'glyphicons-halflings-regular';
$icon-font-svg-id: 'glyphicons_halflingsregular';
$icon-font-path: '../fonts/';
@import "glyphicons";
  1. Run: npm run dist to recompile your code with Glyphicons

Notice that Bootstrap 4 requires the post CSS Autoprefixer for compiling. When you are using a static Sass compiler to compile your CSS you should have to run the Autoprefixer afterwards.

You can find out more about mixing with the Bootstrap 4 SCSS in here.

You can also use Bower to install the fonts above. Using Bower Font Awesome installs your files in bower_components/components-font-awesome/ also notice that Github Octicons sets the octicons/octicons/octicons-.scss as the main file whilst you should use octicons/octicons/sprockets-octicons.scss.

All the above will compile all your CSS code including into a single file, which requires only one HTTP request. Alternatively you can also load the Font-Awesome font from CDN, which can be fast too in many situations. Both fonts on CDN also include the font files (using data-uri's, possible not supported for older browsers). So consider which solution best fits your situation depending on among others browsers to support.

For Font Awesome paste the following code into the <head> section of your site's HTML:

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Also try Yeoman generator to scaffold out a front-end Bootstrap 4 Web app to test Bootstrap 4 with Font Awesome or Github Octicons.

In Visual Studio C++, what are the memory allocation representations?

Regarding 0xCC and 0xCD in particular, these are relics from the Intel 8088/8086 processor instruction set back in the 1980s. 0xCC is a special case of the software interrupt opcode INT 0xCD. The special single-byte version 0xCC allows a program to generate interrupt 3.

Although software interrupt numbers are, in principle, arbitrary, INT 3 was traditionally used for the debugger break or breakpoint function, a convention which remains to this day. Whenever a debugger is launched, it installs an interrupt handler for INT 3 such that when that opcode is executed the debugger will be triggered. Typically it will pause the currently running programming and show an interactive prompt.

Normally, the x86 INT opcode is two bytes: 0xCD followed by the desired interrupt number from 0-255. Now although you could issue 0xCD 0x03 for INT 3, Intel decided to add a special version--0xCC with no additional byte--because an opcode must be only one byte in order to function as a reliable 'fill byte' for unused memory.

The point here is to allow for graceful recovery if the processor mistakenly jumps into memory that does not contain any intended instructions. Multi-byte instructions aren't suited this purpose since an erroneous jump could land at any possible byte offset where it would have to continue with a properly formed instruction stream.

Obviously, one-byte opcodes work trivially for this, but there can also be quirky exceptions: for example, considering the fill sequence 0xCDCDCDCD (also mentioned on this page), we can see that it's fairly reliable since no matter where the instruction pointer lands (except perhaps the last filled byte), the CPU can resume executing a valid two-byte x86 instruction CD CD, in this case for generating software interrupt 205 (0xCD).

Weirder still, whereas CD CC CD CC is 100% interpretable--giving either INT 3 or INT 204--the sequence CC CD CC CD is less reliable, only 75% as shown, but generally 99.99% when repeated as an int-sized memory filler.

page from contemporaneous 8088/8086 instruction set manual showing INT instruction
Macro Assembler Reference, 1987

Dismissing a Presented View Controller

If you are using modal use view dismiss.

[self dismissViewControllerAnimated:NO completion:nil];

ASP.NET postback with JavaScript

You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

How to replace (or strip) an extension from a filename in Python?

As @jethro said, splitext is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension must be the part of the filename coming after the final period:

filename = '/home/user/somefile.txt'
print( filename.rsplit( ".", 1 )[ 0 ] )
# '/home/user/somefile'

The rsplit tells Python to perform the string splits starting from the right of the string, and the 1 says to perform at most one split (so that e.g. 'foo.bar.baz' -> [ 'foo.bar', 'baz' ]). Since rsplit will always return a non-empty array, we may safely index 0 into it to get the filename minus the extension.

Java and HTTPS url connection without downloading certificate

Java and HTTPS url connection without downloading certificate

If you really want to avoid downloading the server's certificate, then use an anonymous protocol like Anonymous Diffie-Hellman (ADH). The server's certificate is not sent with ADH and friends.

You select an anonymous protocol with setEnabledCipherSuites. You can see the list of cipher suites available with getEnabledCipherSuites.

Related: that's why you have to call SSL_get_peer_certificate in OpenSSL. You'll get a X509_V_OK with an anonymous protocol, and that's how you check to see if a certificate was used in the exchange.

But as Bruno and Stephed C stated, its a bad idea to avoid the checks or use an anonymous protocol.


Another option is to use TLS-PSK or TLS-SRP. They don't require server certificates either. (But I don't think you can use them).

The rub is, you need to be pre-provisioned in the system because TLS-PSK is Pres-shared Secret and TLS-SRP is Secure Remote Password. The authentication is mutual rather than server only.

In this case, the mutual authentication is provided by a property that both parties know the shared secret and arrive at the same premaster secret; or one (or both) does not and channel setup fails. Each party proves knowledge of the secret is the "mutual" part.

Finally, TLS-PSK or TLS-SRP don't do dumb things, like cough up the user's password like in a web app using HTTP (or over HTTPS). That's why I said each party proves knowledge of the secret...

Vertical line using XML drawable

its very simple... to add a vertical line in android xml...

<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:rotation="90"
android:background="@android:color/darker_gray"/>

How to get the index with the key in Python dictionary?

Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1

For those using Python 3

>>> list(x.keys()).index("c")
1

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How do I send a file as an email attachment using Linux command line?

If the file is text, you can send it easiest in the body as:

sendmail [email protected] < message.txt

How to convert Set<String> to String[]?

I was facing the same situation.

I begin by declaring the structures I need:

Set<String> myKeysInSet = null; String[] myArrayOfString = null;

In my case, I have a JSON object and I need all the keys in this JSON to be stored in an array of strings. Using the GSON library, I use JSON.keySet() to get the keys and move to my Set :

myKeysInSet = json_any.keySet();

With this, I have a Set structure with all the keys, as I needed it. So I just need to the values to my Array of Strings. See the code below:

myArrayOfString = myKeysInSet.toArray(new String[myKeysInSet.size()]);

This was my first answer in StackOverflow. Sorry for any error :D

How do I get a PHP class constructor to call its parent's parent's constructor?

Ok, Yet another ugly solution:

Create a function in Papa like:

protected function call2Granpa() {
     return parent::__construct();
}

Then in Kiddo you use:

parent::call2Granpa(); //instead of calling constructor in Papa.

I think it could work... I haven't test it, so I'm not sure if the objects are created correctly.

I used this approach but with non-constructor functions.

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

Can Android Studio be used to run standard Java projects?

Easy way to run a java program in Android Studio would be,

  1. Create a java Class says "Test.java" in Android Studio.

  2. Write your code eg, a Hello World program to test.

  3. Right-click on the Java class and:

  • select the option Run 'Test.main()'

or

  • press CTRL + SHIFT + F10 (on windows) or control + R (on Mac)

There you have your Java code running below.

Found a swap file by the name

.MERGE_MSG.swp is open in your git, you just need to delete this .swp file. In my case I used following command and it worked fine.

rm .MERGE_MSG.swp

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

More specifically to what is being asked. Pass in a String and a position to check. Very close to Josh's except that this one will compare a larger string. Would have added as a comment but I don't have that ability yet.

function isUpperCase(myString, pos) { 
    return (myString.charAt(pos) == myString.charAt(pos).toUpperCase()); 
}   

function isLowerCase(myString, pos) {
    return (myString.charAt(pos) == myString.charAt(pos).toLowerCase()); 
}

Where to place JavaScript in an HTML file?

Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).

I you really need to squeeze out every last ms then you probably should do what Yahoo says.

A project with an Output Type of Class Library cannot be started directly

I had a similar issue when trying to use the Experimental Instance of Visual Studio 2013. This was for a vsix project (Creating Snippets).

Solution was:

Right Click Project in Solution Explorer > Properties > Debug

Setting the Start Action to "Start external program" and using the following path:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe

This option was set to "Start project" which won't work for the application output type Class Library, which caused that same error.

Note: Yours may differ depending on how you installed VS.

Using number as "index" (JSON)

Probably you need an array?

var Game = {

    status: [
        ["val", "val","val"],
        ["val", "val", "val"]
    ]
}

alert(Game.status[0][0]);

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

To generate a certificate on the Apple provisioning profile website, firstly you have to generate keys on your mac, then upload the public key. Apple will generate your certificates with this key. When you download your certificates, tu be able to use them you need to have the private key.

The error "XCode could not find a valid private-key/certificate pair for this profile in your keychain." means you don't have the private key.

Maybe because your Mac was reinstalled, maybe because this key was generated on another Mac. So to be able to use your certificates, you need to find this key and install it on the keychain.

If you can not find it you can generate new keys restart this process on the provisioning profile website and get new certificates you will able to use.

Retrieve the maximum length of a VARCHAR column in SQL Server

Use the built-in functions for length and max on the description column:

SELECT MAX(LEN(DESC)) FROM table_name;

Note that if your table is very large, there can be performance issues.

jQuery: How to get the event object in an event handler function without passing it as an argument?

Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?

No, not reliably. IE and some other browsers make it available as window.event (not $(window.event)), but that's non-standard and not supported by all browsers (famously, Firefox does not).

You're better off passing the event object into the function:

<a href="#" onclick="myFunc(event, 1,2,3)">click</a>

That works even on non-IE browsers because they execute the code in a context that has an event variable (and works on IE because event resolves to window.event). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4

But your best bet is to use modern event handling:

HTML:

<a href="#">click</a>

JavaScript using jQuery (since you're using jQuery):

$("selector_for_the_anchor").click(function(event) {
    // Call `myFunc`
    myFunc(1, 2, 3);

    // Use `event` here at the event handler level, for instance
    event.stopPropagation();
});

...or if you really want to pass event into myFunc:

$("selector_for_the_anchor").click(function(event) {
    myFunc(event, 1, 2, 3);
});

The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id or class to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.

How do I capture the output of a script if it is being ran by the task scheduler?

You can have a debug.cmd that calls yourscript.cmd

yourscript.cmd > logall.txt

you schedule debug.cmd instead of yourscript.cmd

Access IP Camera in Python OpenCV

I answer my own question reporting what therefore seems to be the most comprehensive overall procedure to Access IP Camera in Python OpenCV.

Given an IP camera:

  • Find your camera IP address
  • Find the port where the IP address is accessed
  • Find the protocol (HTTP/RTSP etc.) specified by the camera provider

Then, if your camera is protected go ahead and find out:

  • your username
  • your password

Then use your data to run the following script:

"""Access IP Camera in Python OpenCV"""

import cv2

stream = cv2.VideoCapture('protocol://IP:port/1')

# Use the next line if your camera has a username and password
# stream = cv2.VideoCapture('protocol://username:password@IP:port/1')  

while True:

    r, f = stream.read()
    cv2.imshow('IP Camera stream',f)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

NOTE: In my original question I specify to being working with Teledyne Dalsa Genie Nano XL Camera. Unfortunately for this kind of cameras this normal way of accessing the IP Camera video stream does not work and the Sapera SDK must be employed in order to grab frames from the device.

Entity Framework 5 Updating a Record

You are looking for:

db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();

How do I convert a Python 3 byte-string variable into a regular string?

UPDATED:

TO NOT HAVE ANY b and quotes at first and end

How to convert bytes as seen to strings, even in weird situations.

As your code may have unrecognizable characters to 'utf-8' encoding, it's better to use just str without any additional parameters:

some_bad_bytes = b'\x02-\xdfI#)'
text = str( some_bad_bytes )[2:-1]

print(text)
Output: \x02-\xdfI

if you add 'utf-8' parameter, to these specific bytes, you should receive error.

As PYTHON 3 standard says, text would be in utf-8 now with no concern.

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.

public static Stream ToStream(this bytes[] bytes) 
{
    return new MemoryStream(bytes) 
    {
        Position = 0
    };
}

Setting background-image using jQuery CSS property

You'll want to include double quotes (") before and after the imageUrl like this:

$('myOjbect').css('background-image', 'url("' + imageUrl + '")');

This way, if the image has spaces it will still be set as a property.

Open new popup window without address bars in firefox & IE

Workaround - Open a modal popup window and embed the external URL as an iframe.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

To do this easily, the use of Stack is better. Create a Stack Then inside Stack add Align or Positioned and set position according to your needed, You can add multiple Container.

Container
  child: Stack(
    children: <Widget>[
      Align(
         alignment: FractionalOffset.center,
         child: Text(
            "? 1000",
         )
      ),
      Positioned(
        bottom: 0,
        child: Container(
           width: double.infinity,
           height: 30,
           child: Text(
             "Balance", ,
           )
         ),
       )
    ],
  )
)

enter image description here

Stack a widget that positions its children relative to the edges of its box.

Stack class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.

PackagesNotFoundError: The following packages are not available from current channels:

If your base conda environment is active...

  • in which case "(base)" will most probably show at the start or your terminal command prompt.

... and pip is installed in your base environment ...

  • which it is: $ conda list | grep pip

... then install the not-found package simply by $ pip install <packagename>

Implementing autocomplete

I think you can use typeahead.js. There are typescript definitions for it. so it'll be easy to use it i guess if you are using typescript for development.

How to create a drop shadow only on one side of an element?

I think this is what you're after?

_x000D_
_x000D_
.shadow {_x000D_
  -webkit-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  -moz-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
}
_x000D_
<div class="shadow">wefwefwef</div>
_x000D_
_x000D_
_x000D_

Create file path from variables

You want the path.join() function from os.path.

>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
    os.makedirs (final_path)

Display Two <div>s Side-by-Side

Try this : (http://jsfiddle.net/TpqVx/)

.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}??

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'>&nbsp;</div>

Hints :

  • Just use float:left in your left-most div only.
  • No real reason to use height, but anyway...
  • Good practice to use <div 'clear:both'>&nbsp;</div> after your last div.

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

Angular 4 - Observable catch error

You should be using below

return Observable.throw(error || 'Internal Server error');

Import the throw operator using the below line

import 'rxjs/add/observable/throw';

What is the difference between the | and || or operators?

The single pipe, |, is one of the bitwise operators.

From Wikipedia:

In the C programming language family, the bitwise OR operator is "|" (pipe). Again, this operator must not be confused with its Boolean "logical or" counterpart, which treats its operands as Boolean values, and is written "||" (two pipes).

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Replace substring with another substring C++

using std::string;

string string_replace( string src, string const& target, string const& repl)
{
    // handle error situations/trivial cases

    if (target.length() == 0) {
        // searching for a match to the empty string will result in 
        //  an infinite loop
        //  it might make sense to throw an exception for this case
        return src;
    }

    if (src.length() == 0) {
        return src;  // nothing to match against
    }

    size_t idx = 0;

    for (;;) {
        idx = src.find( target, idx);
        if (idx == string::npos)  break;

        src.replace( idx, target.length(), repl);
        idx += repl.length();
    }

    return src;
}

Since it's not a member of the string class, it doesn't allow quite as nice a syntax as in your example, but the following will do the equivalent:

test = string_replace( string_replace( test, "abc", "hij"), "def", "klm")

How to compare DateTime without time via LINQ?

The Date property is not supported by LINQ to Entities -- you'll get an error if you try to use it on a DateTime field in a LINQ to Entities query. You can, however, trim dates using the DbFunctions.TruncateTime method.

var today = DateTime.Today;
var q = db.Games.Where(t => DbFunctions.TruncateTime(t.StartDate) >= today);

xpath find if node exists

Patrick is correct, both in the use of the xsl:if, and in the syntax for checking for the existence of a node. However, as Patrick's response implies, there is no xsl equivalent to if-then-else, so if you are looking for something more like an if-then-else, you're normally better off using xsl:choose and xsl:otherwise. So, Patrick's example syntax will work, but this is an alternative:

<xsl:choose>
 <xsl:when test="/html/body">body node exists</xsl:when>
 <xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>

Today's Date in Perl in MM/DD/YYYY format

Perl Code for Unix systems:

# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;

# Remove newline character
$current_date = substr($current_date,0,-1);

print $current_date, "\n";

How to determine the version of android SDK installed in computer?

I develope cross-plateform mobile applications Using Xamarin integrated in Visual Studio 2017.

I prefer to install and check all details of Android SDK from within the Visual Studio 2017. This can be found under the menu TOOLS -> Android -> Android SDK Manager.

Bellow is the Visual representation of the Adroid SDK Manager.enter image description here

Get the time of a datetime using T-SQL?

CAST(CONVERT(CHAR(8),GETUTCDATE(),114) AS DATETIME)

IN SQL Server 2008+

CAST(GETUTCDATE() AS TIME)

Add ripple effect to my button with button background color?

In addition to Jigar Patel's solution, add this to the ripple.xml to avoid transparent background of buttons.

<item
    android:id="@android:id/background"
    android:drawable="@color/your-color" />

Complete xml :

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="@color/your-color"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/your-color" />
        </shape>
    </item>
    <item
        android:id="@android:id/background"
        android:drawable="@color/your-color" />
</ripple>

Use this ripple.xml as background in your button :

android:background="@drawable/ripple"

How to populate a sub-document in mongoose after creating it?

This might have changed since the original answer was written, but it looks like you can now use the Models populate function to do this without having to execute an extra findOne. See: http://mongoosejs.com/docs/api.html#model_Model.populate. You'd want to use this inside the save handler just like the findOne is.

Can jQuery read/write cookies to a browser?

A new jQuery plugin for cookie retrieval and manipulation with binding for forms, etc: http://plugins.jquery.com/project/cookies

What is the best way to convert an array to a hash in Ruby

Summary & TL;DR:

This answer hopes to be a comprehensive wrap-up of information from other answers.

The very short version, given the data from the question plus a couple extras:

flat_array   = [  apple, 1,   banana, 2  ] # count=4
nested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays
incomplete_f = [  apple, 1,   banana     ] # count=3 - missing last value
incomplete_n = [ [apple, 1], [banana   ] ] # count=2 of either k or k,v arrays


# there's one option for flat_array:
h1  = Hash[*flat_array]                     # => {apple=>1, banana=>2}

# two options for nested_array:
h2a = nested_array.to_h # since ruby 2.1.0    => {apple=>1, banana=>2}
h2b = Hash[nested_array]                    # => {apple=>1, banana=>2}

# ok if *only* the last value is missing:
h3  = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}
# always ok for k without v in nested array:
h4  = Hash[incomplete_n] # or .to_h           => {apple=>1, banana=>nil}

# as one might expect:
h1 == h2a # => true
h1 == h2b # => true
h1 == h3  # => false
h3 == h4  # => true

Discussion and details follow.


Setup: variables

In order to show the data we'll be using up front, I'll create some variables to represent various possibilities for the data. They fit into the following categories:

Based on what was directly in the question, as a1 and a2:

(Note: I presume that apple and banana were meant to represent variables. As others have done, I'll be using strings from here on so that input and results can match.)

a1 = [  'apple', 1 ,  'banana', 2  ] # flat input
a2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input

Multi-value keys and/or values, as a3:

In some other answers, another possibility was presented (which I expand on here) – keys and/or values may be arrays on their own:

a3 = [ [ 'apple',                   1   ],
       [ 'banana',                  2   ],
       [ ['orange','seedless'],     3   ],
       [ 'pear',                 [4, 5] ],
     ]

Unbalanced array, as a4:

For good measure, I thought I'd add one for a case where we might have an incomplete input:

a4 = [ [ 'apple',                   1],
       [ 'banana',                  2],
       [ ['orange','seedless'],     3],
       [ 'durian'                    ], # a spiky fruit pricks us: no value!
     ]

Now, to work:

Starting with an initially-flat array, a1:

Some have suggested using #to_h (which showed up in Ruby 2.1.0, and can be backported to earlier versions). For an initially-flat array, this doesn't work:

a1.to_h   # => TypeError: wrong element type String at 0 (expected array)

Using Hash::[] combined with the splat operator does:

Hash[*a1] # => {"apple"=>1, "banana"=>2}

So that's the solution for the simple case represented by a1.

With an array of key/value pair arrays, a2:

With an array of [key,value] type arrays, there are two ways to go.

First, Hash::[] still works (as it did with *a1):

Hash[a2] # => {"apple"=>1, "banana"=>2}

And then also #to_h works now:

a2.to_h  # => {"apple"=>1, "banana"=>2}

So, two easy answers for the simple nested array case.

This remains true even with sub-arrays as keys or values, as with a3:

Hash[a3] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]} 
a3.to_h  # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}

But durians have spikes (anomalous structures give problems):

If we've gotten input data that's not balanced, we'll run into problems with #to_h:

a4.to_h  # => ArgumentError: wrong array length at 3 (expected 2, was 1)

But Hash::[] still works, just setting nil as the value for durian (and any other array element in a4 that's just a 1-value array):

Hash[a4] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}

Flattening - using new variables a5 and a6

A few other answers mentioned flatten, with or without a 1 argument, so let's create some new variables:

a5 = a4.flatten
# => ["apple", 1, "banana", 2,  "orange", "seedless" , 3, "durian"] 
a6 = a4.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian"] 

I chose to use a4 as the base data because of the balance problem we had, which showed up with a4.to_h. I figure calling flatten might be one approach someone might use to try to solve that, which might look like the following.

flatten without arguments (a5):

Hash[*a5]       # => {"apple"=>1, "banana"=>2, "orange"=>"seedless", 3=>"durian"}
# (This is the same as calling `Hash[*a4.flatten]`.)

At a naïve glance, this appears to work – but it got us off on the wrong foot with the seedless oranges, thus also making 3 a key and durian a value.

And this, as with a1, just doesn't work:

a5.to_h # => TypeError: wrong element type String at 0 (expected array)

So a4.flatten isn't useful to us, we'd just want to use Hash[a4]

The flatten(1) case (a6):

But what about only partially flattening? It's worth noting that calling Hash::[] using splat on the partially-flattened array (a6) is not the same as calling Hash[a4]:

Hash[*a6] # => ArgumentError: odd number of arguments for Hash

Pre-flattened array, still nested (alternate way of getting a6):

But what if this was how we'd gotten the array in the first place? (That is, comparably to a1, it was our input data - just this time some of the data can be arrays or other objects.) We've seen that Hash[*a6] doesn't work, but what if we still wanted to get the behavior where the last element (important! see below) acted as a key for a nil value?

In such a situation, there's still a way to do this, using Enumerable#each_slice to get ourselves back to key/value pairs as elements in the outer array:

a7 = a6.each_slice(2).to_a
# => [["apple", 1], ["banana", 2], [["orange", "seedless"], 3], ["durian"]] 

Note that this ends up getting us a new array that isn't "identical" to a4, but does have the same values:

a4.equal?(a7) # => false
a4 == a7      # => true

And thus we can again use Hash::[]:

Hash[a7] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
# or Hash[a6.each_slice(2).to_a]

But there's a problem!

It's important to note that the each_slice(2) solution only gets things back to sanity if the last key was the one missing a value. If we later added an extra key/value pair:

a4_plus = a4.dup # just to have a new-but-related variable name
a4_plus.push(['lychee', 4])
# => [["apple",                1],
#     ["banana",               2],
#     [["orange", "seedless"], 3], # multi-value key
#     ["durian"],              # missing value
#     ["lychee", 4]]           # new well-formed item

a6_plus = a4_plus.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian", "lychee", 4]

a7_plus = a6_plus.each_slice(2).to_a
# => [["apple",                1],
#     ["banana",               2],
#     [["orange", "seedless"], 3], # so far so good
#     ["durian",               "lychee"], # oops! key became value!
#     [4]]                     # and we still have a key without a value

a4_plus == a7_plus # => false, unlike a4 == a7

And the two hashes we'd get from this are different in important ways:

ap Hash[a4_plus] # prints:
{
                     "apple" => 1,
                    "banana" => 2,
    [ "orange", "seedless" ] => 3,
                    "durian" => nil, # correct
                    "lychee" => 4    # correct
}

ap Hash[a7_plus] # prints:
{
                     "apple" => 1,
                    "banana" => 2,
    [ "orange", "seedless" ] => 3,
                    "durian" => "lychee", # incorrect
                           4 => nil       # incorrect
}

(Note: I'm using awesome_print's ap just to make it easier to show the structure here; there's no conceptual requirement for this.)

So the each_slice solution to an unbalanced flat input only works if the unbalanced bit is at the very end.


Take-aways:

  1. Whenever possible, set up input to these things as [key, value] pairs (a sub-array for each item in the outer array).
  2. When you can indeed do that, either #to_h or Hash::[] will both work.
  3. If you're unable to, Hash::[] combined with the splat (*) will work, so long as inputs are balanced.
  4. With an unbalanced and flat array as input, the only way this will work at all reasonably is if the last value item is the only one that's missing.

Side-note: I'm posting this answer because I feel there's value to be added – some of the existing answers have incorrect information, and none (that I read) gave as complete an answer as I'm endeavoring to do here. I hope that it's helpful. I nevertheless give thanks to those who came before me, several of whom provided inspiration for portions of this answer.

What's the difference between echo, print, and print_r in PHP?

print_r() can print out value but also if second flag parameter is passed and is TRUE - it will return printed result as string and nothing send to standard output. About var_dump. If XDebug debugger is installed so output results will be formatted in much more readable and understandable way.

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

Hans Passant was correct, I added a handler for AppDomain.CurrentDomain.UnhandledException as described here http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx I was able to find the exception that was occurring and corrected it.

Disable/Enable button in Excel/VBA

... I don't know if you're using an activex button or not, but when I insert an activex button into sheet1 in Excel called CommandButton1, the following code works fine:

Sub test()

   Sheets(1).CommandButton1.Enabled = False

End Sub

Hope this helps...

Error when deploying an artifact in Nexus

Cause of problem for me was -source.jars was getting uploaded twice (with maven-source-plugin) as mentioned as one of the cause in accepted answer. Redirecting to answer that I referred: Maven release plugin fails : source artifacts getting deployed twice

How to increase heap size of an android application?

From what I remember you could use VMRuntime class in early Android versions but now you just can't anymore.

I don't think letting the developer choose the heap size in a mobile environment can be considered so safe though. I think it's easier that you can find a way to modify the heap size in a specific device (not on the programming side) that by trying to modify it from the application itself.

Copy existing project with a new name in Android Studio

In Android Studio 4.0 you need only these few steps:

  • in File Manager copy the project directory and rename the new one
  • enter in it and change applicationId inside app/build.gradle
  • open the existing new project in Android Studio
  • open one class file and highlight the package name part to change (e.g. from com.domain.appname to com.domain.newappname highlight appname)
  • right click on it -> "refactor" -> "rename"
  • choose "rename package"
  • in the dialog choose "Scope: all places" and click "preview" or "refactor"

How should I print types like off_t and size_t?

To print off_t:

printf("%jd\n", (intmax_t)x);

To print size_t:

printf("%zu\n", x);

To print ssize_t:

printf("%zd\n", x);

See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:

http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html

If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.

For example if your compiler has long long and your standard library supports %lld, you can confidently expect that will serve in place of intmax_t. But if it doesn't, you'll have to fall back to long, which would fail on some other implementations because it's too small.

NSDictionary - Need to check whether dictionary contains key-value pair or not

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

What does <> mean?

Yes, it's "not equal".

GET URL parameter in PHP

Whomever gets nothing back, I think he just has to enclose the result in html tags,

Like this:

<html>
<head></head>
<body>
<?php
echo $_GET['link'];
?>
<body>
</html>

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

SJF are two type - i) non preemptive SJF ii)pre-emptive SJF

I have re-arranged the processes according to Arrival time. here is the non preemptive SJF

A.T= Arrival Time

B.T= Burst Time

C.T= Completion Time

T.T = Turn around Time = C.T - A.T

W.T = Waiting Time = T.T - B.T

enter image description here

Here is the preemptive SJF Note: each process will preempt at time a new process arrives.Then it will compare the burst times and will allocate the process which have shortest burst time. But if two process have same burst time then the process which came first that will be allocated first just like FCFS.

enter image description here

jQuery: Setting select list 'selected' based on text, failing strangely

In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript

document.getElementById("The id of the element").value = "The value"

And that would set the value and make the current value selected in the combo box. Tested in firefox.

it was easier than keep googling a solution for jQuery

How do I resize a Google Map with JavaScript after it has loaded?

First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

google.maps.event.trigger({$id}, \"resize\");

And need the include below code in JavaScript

google.maps.event.addListenerOnce({$id}, 'idle', function(){
   setCenterMap(new google.maps.LatLng({$this->defaultLatitude}, 
   {$this->defaultLongitude}));
});

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

.map() a Javascript ES6 Map?

You can use myMap.forEach, and in each loop, using map.set to change value.

_x000D_
_x000D_
myMap = new Map([_x000D_
  ["a", 1],_x000D_
  ["b", 2],_x000D_
  ["c", 3]_x000D_
]);_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
  console.log(key + ' = ' + value);_x000D_
}_x000D_
_x000D_
_x000D_
myMap.forEach((value, key, map) => {_x000D_
  map.set(key, value+1)_x000D_
})_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
  console.log(key + ' = ' + value);_x000D_
}
_x000D_
_x000D_
_x000D_

SELECT from nothing?

There is another possibility - standalone VALUES():

VALUES ('Hello World');

Output:

column1
Hello World

It is useful when you need to specify multiple values in compact way:

VALUES (1, 'a'), (2, 'b'), (3, 'c');

Output:

column1     column2
      1     a
      2     b
      3     c

DBFiddle Demo

This syntax is supported by SQLite/PostgreSQL/DB LUW/MariaDB 10.3.

Subversion stuck due to "previous operation has not finished"?

I had tried the most voted answers here and a few others to no avail. My WORK_QUEUE table was empty and I wasn't able to try a clean up at a higher folder. What did work was the following (this is via Tortoise SVN);

  • Right click on folder
  • Go to TortoiseSVN -> Clean Up...
  • Make sure the option to Break Locks is ticked and click OK

The Clean Up operation now completes successfully and I can continue. No downloading of sqlite3 or other convoluted solutions required.

jQuery select all except first

$("div.test:not(:first)").hide();

or:

$("div.test:not(:eq(0))").hide();

or:

$("div.test").not(":eq(0)").hide();

or:

$("div.test:gt(0)").hide();

or: (as per @Jordan Lev's comment):

$("div.test").slice(1).hide();

and so on.

See:

Viewing my IIS hosted site on other machines on my network

You have to do following steps.

Go to IIS ->
Sites->
Click on Your Web site ->
In Action Click on Edit Permissions ->
Security ->
Click on ADD ->
Advanced ->
Find Now ->
Add all the users in it ->
and grant all permissions to other users ->
click on Ok.

If you do above things properly you can access your web site by using your domain.
Suggestion - Do not add host name to your site it creates problem sometime. So please host your web site using your machines ip address.

making matplotlib scatter plots from dataframes in Python's pandas

Try passing columns of the DataFrame directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100

In [5]: df
Out[5]: 
       col1      col2  col3
0 -1.000075 -0.759910   100
1  0.510382  0.972615   200
2  1.872067 -0.731010   500
3  0.131612  1.075142  1000
4  1.497820  0.237024  1700

Vary scatter point size based on another column

plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)

enter image description here

Vary scatter point color based on another column

colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)

enter image description here

Scatter plot with legend

However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter once for each point type.

cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300') 
plt.legend()

enter image description here

Update

From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull method: df[df.col3.isnull()]

To split a list of points into many types, take a look at numpy select, which is a vectorized if-then-else implementation and accepts an optional default value. For example:

df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
                         [0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
    subset = df[df.subset == label]
    plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()

enter image description here

Is there a way to get version from package.json in nodejs code?

Why don't use the require resolve...

const packageJson = path.dirname(require.resolve('package-name')) + '/package.json';
const { version } = require(packageJson);
console.log('version', version)

With this approach work for all sub paths :)

Change label text using JavaScript

Here is another way to change the text of a label using jQuery:

<script>
  $("#lbltipAddedComment").text("your tip has been submitted!");
</script>

Check the JsFiddle example

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

SQL (MySQL) vs NoSQL (CouchDB)

Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.

Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.

Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...

You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding

Hope that helped.

bash "if [ false ];" returns true instead of false -- why?

Using true/false removes some bracket clutter...

#! /bin/bash    
#  true_or_false.bash

[ "$(basename $0)" == "bash" ] && sourced=true || sourced=false

$sourced && echo "SOURCED"
$sourced || echo "CALLED"

# Just an alternate way:
! $sourced  &&  echo "CALLED " ||  echo "SOURCED"

$sourced && return || exit

add an element to int [] array in java

import java.util.Arrays;

public class NumberArray {     

    public static void main(String []args){
        int[] series = {4,2};
        int[] newSeries = putNumberInSeries(1,series);
        System.out.println(series==newSeries);//return false. you won't get the same int[] object. But functionality achieved.
    }
    private static int[] putNumberInSeries(int i, int[] series) {
        int[] localSeries = Arrays.copyOf(series, series.length+1);
        localSeries[series.length] = i;
        System.out.println(localSeries);
        return localSeries;
    }
}

Is multiplication and division using shift operators in C actually faster?

Short answer: Not likely.

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

What is the best way to remove accents (normalize) in a Python unicode string?

How about this:

import unicodedata
def strip_accents(s):
   return ''.join(c for c in unicodedata.normalize('NFD', s)
                  if unicodedata.category(c) != 'Mn')

This works on greek letters, too:

>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>> 

The character category "Mn" stands for Nonspacing_Mark, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).

And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".

Convert textbox text to integer

Suggest do this in your code-behind before sending down to SQL Server.

 int userVal = int.Parse(txtboxname.Text);

Perhaps try to parse and optionally let the user know.

int? userVal;
if (int.TryParse(txtboxname.Text, out userVal) 
{
  DoSomething(userVal.Value);
}
else
{ MessageBox.Show("Hey, we need an int over here.");   }

The exception you note means that you're not including the value in the call to the stored proc. Try setting a debugger breakpoint in your code at the time you call down into the code that builds the call to SQL Server.

Ensure you're actually attaching the parameter to the SqlCommand.

using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add("@ParamName", SqlDbType.Int);
    cmd.Parameters["@ParamName"].Value = newName;        
    conn.Open();
    string someReturn = (string)cmd.ExecuteScalar();        
}

Perhaps fire up SQL Profiler on your database to inspect the SQL statement being sent/executed.

How to dismiss keyboard for UITextView with return key?

Swift Code

Implement UITextViewDelegate in your class / View like so:

class MyClass: UITextViewDelegate  { ...

set the textView delegate to self

myTextView.delegate = self

And then implement the following:

  func textViewDidChange(_ textView: UITextView) {
    if textView.text.characters.count >= 1 {

        if let lastChar = textView.text.characters.last {

            if(lastChar == "\n"){

              textView.text = textView.text.substring(to: textView.text.index(before: textView.text.endIndex))
              textView.resignFirstResponder()
            }
        }
    }
}

EDIT I updated the code because it is never a good idea to change the user input in a textfield to for a workarround and not resetting the state after the hack code completed.

How to get database structure in MySQL via query

I think that what you're after is DESCRIBE

DESCRIBE table;

You can also use SHOW TABLES

SHOW TABLES;

to get a list of the tables in your database.

Property 'catch' does not exist on type 'Observable<any>'

Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below

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

Yes, you need to import the operator:

import 'rxjs/add/operator/catch';

Or import Observable this way:

import {Observable} from 'rxjs/Rx';

But in this case, you import all operators.

See this question for more details:

Installation error: INSTALL_FAILED_OLDER_SDK

Make sure to check your build.gradle and that it doesn't use a newer SDK version than what is installed on your AVD. That's only if you use Android Studio though.

Root password inside a Docker container

When you start the container, you will be root but you won't know what root's pw is. To set it to something you know simply use "passwd root". Snapshot/commit the container to save your actions.