Programs & Examples On #Pgf

How to control font sizes in pgf/tikz graphics in latex?

I found the better control would be using scalefnt package:

\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}

How do I see what character set a MySQL database / table / column is?

As many wrote earlier, SHOW FULL COLUMNS should be the preferred method to get column information. What's missing is a way to get charset after that without reaching metadata tables directly:

SHOW FULL COLUMNS FROM my_table WHERE Field = 'my_field'
SHOW COLLATION WHERE Collation = 'collation_you_got'

How to write a foreach in SQL Server?

Your select count and select max should be from your table variable instead of the actual table

DECLARE @i int
DECLARE @PractitionerId int
DECLARE @numrows int
DECLARE @Practitioner TABLE (
    idx smallint Primary Key IDENTITY(1,1)
    , PractitionerId int
)

INSERT @Practitioner
SELECT distinct PractitionerId FROM Practitioner

SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM @Practitioner)
IF @numrows > 0
    WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))
    BEGIN

        SET @PractitionerId = (SELECT PractitionerId FROM @Practitioner WHERE idx = @i)

        --Do something with Id here
        PRINT @PractitionerId

        SET @i = @i + 1
    END

Reinitialize Slick js after successful ajax call

Try this code, it helped me!

$('.slider-selector').not('.slick-initialized').slick({
  dots: true,
  arrows: false,
  setPosition: true
});

What's the complete range for Chinese characters in Unicode?

To summarize, it sounds like these are them:

var blocks = [
  [0x3400, 0x4DB5],
  [0x4E00, 0x62FF],
  [0x6300, 0x77FF],
  [0x7800, 0x8CFF],
  [0x8D00, 0x9FCC],
  [0x2e80, 0x2fd5],
  [0x3190, 0x319f],
  [0x3400, 0x4DBF],
  [0x4E00, 0x9FCC],
  [0xF900, 0xFAAD],
  [0x20000, 0x215FF],
  [0x21600, 0x230FF],
  [0x23100, 0x245FF],
  [0x24600, 0x260FF],
  [0x26100, 0x275FF],
  [0x27600, 0x290FF],
  [0x29100, 0x2A6DF],
  [0x2A700, 0x2B734],
  [0x2B740, 0x2B81D]
]

How to export JSON from MongoDB using Robomongo

Don't run this command on shell, enter this script at a command prompt with your database name, collection name, and file name, all replacing the placeholders..

mongoexport --db (Database name) --collection (Collection Name) --out (File name).json

It works for me.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

How to print an unsigned char in C?

There are two bugs in this code. First, in most C implementations with signed char, there is a problem in char ch = 212 because 212 does not fit in an 8-bit signed char, and the C standard does not fully define the behavior (it requires the implementation to define the behavior). It should instead be:

unsigned char ch = 212;

Second, in printf("%u",ch), ch will be promoted to an int in normal C implementations. However, the %u specifier expects an unsigned int, and the C standard does not define behavior when the wrong type is passed. It should instead be:

printf("%u", (unsigned) ch);

Playing Sound In Hidden Tag

I hope people would allow them to turn things such as music off, as for button clicks, Sometimes, those are pretty cool. Use the

<audio controls autoplay hidden="hidden"> <source src="*file here*" type="*file extension (.mp3 .ogg etc.)*"> <!--This displays an error to users that don't have it supported--> Your browser does not support the audio element. </audio>

As you can see, I don't like to repeat myself much, But I decided with the hidden tag.

Hope this helps.

C/C++ NaN constant (literal)?

This can be done using the numeric_limits in C++:

http://www.cplusplus.com/reference/limits/numeric_limits/

These are the methods you probably want to look at:

infinity()  T   Representation of positive infinity, if available.
quiet_NaN() T   Representation of quiet (non-signaling) "Not-a-Number", if available.
signaling_NaN() T   Representation of signaling "Not-a-Number", if available.

Get class name of object as string in Swift

In my case String(describing: self) returned something like:

< My_project.ExampleViewController: 0x10b2bb2b0>

But I'd like to have something like getSimpleName on Android.

So I've created a little extension:

extension UIViewController {

    func getSimpleClassName() -> String {
        let describing = String(describing: self)
        if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") {
            let afterDotIndex = describing.index(after: dotIndex)
            if(afterDotIndex < commaIndex) {
                return String(describing[afterDotIndex ..< commaIndex])
            }
        }
        return describing
    }

}

And now it returns:

ExampleViewController

Extending NSObject instead of UIViewController should also work. Function above is also fail-safe :)

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

<table>
     <ng-container *ngFor="let group of groups">
         <tr><td><h2>{{group.name}}</h2></td></tr>
         <tr *ngFor="let item of group.items"><td>{{item}}</td></tr>
     </ng-container>
</table>

Find a string between 2 known values

A Regex approach using lazy match and back-reference:

foreach (Match match in Regex.Matches(
        "morenonxmldata<tag1>0002</tag1>morenonxmldata<tag2>abc</tag2>asd",
        @"<([^>]+)>(.*?)</\1>"))
{
    Console.WriteLine("{0}={1}",
        match.Groups[1].Value,
        match.Groups[2].Value);
}

How to call a .NET Webservice from Android using KSOAP2?

Typecast the envelope to SoapPrimitive:

SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();

and it will work.

Android Studio 3.0 Flavor Dimension Issue

Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
    production {
        dimension 'yourAppName' //you just need to add this line
        //here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.

    }

    staging {
        dimension 'yourAppName' //added here also
        applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
        //or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
        //versionNameSuffix "-staging"

    }

    develop {
        dimension 'yourAppName' //add here too
        applicationIdSuffix ".develop"
        //versionNameSuffix "-develop"

    }

How to add hamburger menu in bootstrap

All you have to do is read the code on getbootstrap.com:

Codepen

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
  <div class="container">_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
      <ul class="nav navbar-nav">_x000D_
        <li><a href="index.php">Home</a></li>_x000D_
        <li><a href="about.php">About</a></li>_x000D_
        <li><a href="#portfolio">Portfolio</a></li>_x000D_
        <li><a href="#">Blog</a></li>_x000D_
        <li><a href="contact.php">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Python: convert string from UTF-8 to Latin-1

If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.

In my case, I was using json.load on data incorrectly read from file by not using the encoding="utf-8". Trying to de-/encode the resulting string to latin-1 just does not help...

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

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

Measure string size in Bytes in php

You have to figure out if the string is ascii encoded or encoded with a multi-byte format.

In the former case, you can just use strlen.

In the latter case you need to find the number of bytes per character.

the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274

Adding a background image to a <div> element

You mean this?

<style type="text/css">
.bgimg {
    background-image: url('../images/divbg.png');
}
</style>

...

<div class="bgimg">
    div with background
</div>

How do I check if there are duplicates in a flat list?

If you are fond of functional programming style, here is a useful function, self-documented and tested code using doctest.

def decompose(a_list):
    """Turns a list into a set of all elements and a set of duplicated elements.

    Returns a pair of sets. The first one contains elements
    that are found at least once in the list. The second one
    contains elements that appear more than once.

    >>> decompose([1,2,3,5,3,2,6])
    (set([1, 2, 3, 5, 6]), set([2, 3]))
    """
    return reduce(
        lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
        a_list,
        (set(), set()))

if __name__ == "__main__":
    import doctest
    doctest.testmod()

From there you can test unicity by checking whether the second element of the returned pair is empty:

def is_set(l):
    """Test if there is no duplicate element in l.

    >>> is_set([1,2,3])
    True
    >>> is_set([1,2,1])
    False
    >>> is_set([])
    True
    """
    return not decompose(l)[1]

Note that this is not efficient since you are explicitly constructing the decomposition. But along the line of using reduce, you can come up to something equivalent (but slightly less efficient) to answer 5:

def is_set(l):
    try:
        def func(s, o):
            if o in s:
                raise Exception
            return s.union([o])
        reduce(func, l, set())
        return True
    except:
        return False

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

MySQL "Group By" and "Order By"

A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:

SELECT * FROM ( 
    SELECT `timestamp`, `fromEmail`, `subject`
    FROM `incomingEmails` 
    ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)

This is similar to using the join but looks much nicer.

Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.

IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)

As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above

See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

How to find children of nodes using BeautifulSoup

try this:

li = soup.find("li", { "class" : "test" })
children = li.find_all("a") # returns a list of all <a> children of li

other reminders:

The find method only gets the first occurring child element. The find_all method gets all descendant elements and are stored in a list.

How to use multiple LEFT JOINs in SQL?

Yes it is possible. You need one ON for each join table.

LEFT JOIN ab
  ON ab.sht = cd.sht
LEFT JOIN aa
  ON aa.sht = cd.sht

Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.

How to keep environment variables when using sudo

A simple wrapper function (or in-line for loop)

I came up with a unique solution because:

  • sudo -E "$@" was leaking variables that was causing problems for my command
  • sudo VAR1="$VAR1" ... VAR42="$VAR42" "$@" was long and ugly in my case

demo.sh

#!/bin/bash

function sudo_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}

# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh

export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."

export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"

# clean function style
sudo_exports ./sudo_test.sh

# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh

Result

$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.

How?

This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0

How to get the file-path of the currently executing javascript code

I just made this little trick :

window.getRunningScript = () => {
    return () => {      
        return new Error().stack.match(/([^ \n])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0]
    }
}
console.log('%c Currently running script:', 'color: blue', getRunningScript()())

screenshot

? Works on: Chrome, Firefox, Edge, Opera

Enjoy !

What does "pending" mean for request in Chrome Developer Window?

In my case, I found (after much hair-pulling) that the "pending" status was caused by the AdBlock extension. The image that I couldn't get to load had the word "ad" in the URL, so AdBlock kept it from loading.

Disabling AdBlock fixes this issue.

Renaming the file so that it doesn't contain "ad" in the URL also fixes it, and is obviously a better solution. Unless it's an advertisement, in which case you should leave it like that. :)

How to remove \xa0 from string in Python?

Try using .strip() at the end of your line line.strip() worked well for me

How can I group by date time column without taking time into consideration

In pre Sql 2008 By taking out the date part:

GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)

HTML button onclick event

This example will help you:

<form>
    <input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>

You can open next page on same page by:

<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">

Quick unix command to display specific lines in the middle of a file?

No there isn't, files are not line-addressable.

There is no constant-time way to find the start of line n in a text file. You must stream through the file and count newlines.

Use the simplest/fastest tool you have to do the job. To me, using head makes much more sense than grep, since the latter is way more complicated. I'm not saying "grep is slow", it really isn't, but I would be surprised if it's faster than head for this case. That'd be a bug in head, basically.

Recover unsaved SQL query scripts

A bit late to the party, but none of the previously mentioned locations worked for me - for some reason the back up/autorecovery files were saved under VS15 folder on my PC (this is for SQL Server 2016 Management Studio)

C:\Users\YOURUSERNAME\Documents\Visual Studio 2015\Backup Files\Solution1

You might want to check your Tools-Options-Environment-Import and Export Settings, the location of the settings files could point you to your back up folder - I would never have looked under the VS15 folder for this.

Hide scroll bar, but while still being able to scroll

Use:

<div style='overflow:hidden; width:500px;'>
   <div style='overflow:scroll; width:508px'>
      My scroll-able area
   </div>
</div>

This is a trick to somewhat overlap the scrollbar with an overlapping div which doesn't have any scroll bars:

::-webkit-scrollbar {
    display: none;
}

This is only for WebKit browsers... Or you could use browser-specific CSS content (if there is any in future). Every browser could have a different and specific property for their respective bars.

For Microsoft Edge use: -ms-overflow-style: -ms-autohiding-scrollbar; or -ms-overflow-style: none; as per MSDN.

There is no equivalent for Firefox. Although there is a jQuery plugin to achieve this, http://manos.malihu.gr/tuts/jquery_custom_scrollbar.html

How to switch between python 2.7 to python 3 from command line?

You can try to rename the python executable in the python3 folder to python3, that is if it was named python formally... it worked for me

How to find the size of a table in SQL?

SQL Server:-

sp_spaceused 'TableName'

Or in management studio: Right Click on table -> Properties -> Storage

MySQL:-

SELECT table_schema, table_name, data_length, index_length FROM information_schema.tables

Sybase:-

sp_spaceused 'TableName'

Oracle:- how-do-i-calculate-tables-size-in-oracle

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

Here are some examples for insert ... on conflict ... (pg 9.5+) :

  • Insert, on conflict - do nothing.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict do nothing;`  
    
  • Insert, on conflict - do update, specify conflict target via column.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict(id)
    do update set name = 'new_name', size = 3;  
    
  • Insert, on conflict - do update, specify conflict target via constraint name.
    insert into dummy(id, name, size) values(1, 'new_name', 3)
    on conflict on constraint dummy_pkey
    do update set name = 'new_name', size = 4;
    

Remove special symbols and extra spaces and replace with underscore using the replace method

If you have a text as

var sampleText ="ä_öü_ßÄ_ TESTED Ö_Ü!@#$%^&())(&&++===.XYZ"

To replace all special character (!@#$%^&())(&&++= ==.) without replacing the characters(including umlaut)

Use below regex

sampleText = sampleText.replace(/[`~!@#$%^&*()|+-=?;:'",.<>{}[]\/\s]/gi,'');

OUTPUT : sampleText = "ä_öü_ßÄ____TESTED_Ö_Ü_____________________XYZ"

This would replace all with an underscore which is provided as second argument to the replace function.You can add whatever you want as per your requirement

Display MessageBox in ASP

<% response.write("<script language=""javascript"">alert('Hello!');</script>") %>

How to clear/remove observable bindings in Knockout.js?

I think it might be better to keep the binding the entire time, and simply update the data associated with it. I ran into this issue, and found that just calling using the .resetAll() method on the array in which I was keeping my data was the most effective way to do this.

Basically you can start with some global var which contains data to be rendered via the ViewModel:

var myLiveData = ko.observableArray();

It took me a while to realize I couldn't just make myLiveData a normal array -- the ko.oberservableArray part was important.

Then you can go ahead and do whatever you want to myLiveData. For instance, make a $.getJSON call:

$.getJSON("http://foo.bar/data.json?callback=?", function(data) {
    myLiveData.removeAll();
    /* parse the JSON data however you want, get it into myLiveData, as below */
    myLiveData.push(data[0].foo);
    myLiveData.push(data[4].bar);
});

Once you've done this, you can go ahead and apply bindings using your ViewModel as usual:

function MyViewModel() {
    var self = this;
    self.myData = myLiveData;
};
ko.applyBindings(new MyViewModel());

Then in the HTML just use myData as you normally would.

This way, you can just muck with myLiveData from whichever function. For instance, if you want to update every few seconds, just wrap that $.getJSON line in a function and call setInterval on it. You'll never need to remove the binding as long as you remember to keep the myLiveData.removeAll(); line in.

Unless your data is really huge, user's won't even be able to notice the time in between resetting the array and then adding the most-current data back in.

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

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

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

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

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

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

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

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

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

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

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

.includes() not working in Internet Explorer

I had the same problem when working in Angular 5. In order to make it work directly without writing a polyfill yourself, just add the following line to polyfills.ts file:

import "core-js/es7/array"

Also, tsconfig.json lib section might be relevant:

"lib": [
  "es2017",
  "dom"
],

What's the most efficient way to erase duplicates and sort a vector?

I'm not sure what you are using this for, so I can't say this with 100% certainty, but normally when I think "sorted, unique" container, I think of a std::set. It might be a better fit for your usecase:

std::set<Foo> foos(vec.begin(), vec.end()); // both sorted & unique already

Otherwise, sorting prior to calling unique (as the other answers pointed out) is the way to go.

ERROR 1064 (42000) in MySQL

Faced the same issue. Indeed it was wrong SQL at the beginning of the file because when dumping I did:

mysqldump -u username --password=password db_name > dump.sql

Which wrote at the beginning of the file something that was in stdout which was:

mysqldump: [Warning] Using a password on the command line interface can be insecure.

Resulting in the restore raising that error.

So deleting the first line of the SQL dump enables a proper restore.

Looking at the way the restore was done in the original question, there is a high chance the dump was done similarly as mine, causing a stdout warning printing in the SQL file (if ever mysqldump was printing it back then).

Find an element by class name, from a known parent element

var element = $("#parentDiv .myClassNameOfInterest")

JavaScript equivalent to printf/String.Format

For use with jQuery.ajax() success functions. Pass only a single argument and string replace with the properties of that object as {propertyName}:

String.prototype.format = function () {
    var formatted = this;
    for (var prop in arguments[0]) {
        var regexp = new RegExp('\\{' + prop + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[0][prop]);
    }
    return formatted;
};

Example:

var userInfo = ("Email: {Email} - Phone: {Phone}").format({ Email: "[email protected]", Phone: "123-123-1234" });

HTTP response code for POST when resource already exists

It's all about context, and also who is responsible for handling duplicates in requests (server or client or both)


If server just point the duplicate, look at 4xx:

  • 400 Bad Request - when the server will not process a request because it's obvious client fault
  • 409 Conflict - if the server will not process a request, but the reason for that is not the client's fault
  • ...

For implicit handling of duplicates, look at 2XX:

  • 200 OK
  • 201 Created
  • ...

if the server is expected to return something, look at 3XX:

  • 302 Found
  • 303 See Other
  • ...

when the server is able to point the existing resource, it implies a redirection.


If the above is not enough, it's always a good practice to prepare some error message in the body of the response.

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

How to set up a Web API controller for multipart/form-data

I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:

[HttpPost]
public string UploadFile()
{
    var file = HttpContext.Current.Request.Files.Count > 0 ?
        HttpContext.Current.Request.Files[0] : null;

    if (file != null && file.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.FileName);

        var path = Path.Combine(
            HttpContext.Current.Server.MapPath("~/uploads"),
            fileName
        );

        file.SaveAs(path);
    }

    return file != null ? "/uploads/" + file.FileName : null;
}

M_PI works with math.h but not with cmath in Visual Studio

This works for me:

#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>

using namespace std;

int main()
{
    cout << M_PI << endl;

    return 0;
}

Compiles and prints pi like is should: cl /O2 main.cpp /link /out:test.exe.

There must be a mismatch in the code you have posted and the one you're trying to compile.

Be sure there are no precompiled headers being pulled in before your #define.

In log4j, does checking isDebugEnabled before logging improve performance?

For a single line, I use a ternary inside of logging message, In this way I don't do the concatenation:

ej:

logger.debug(str1 + str2 + str3 + str4);

I do:

logger.debug(logger.isDebugEnable()?str1 + str2 + str3 + str4:null);

But for multiple lines of code

ej.

for(Message mess:list) {
    logger.debug("mess:" + mess.getText());
}

I do:

if(logger.isDebugEnable()) {
    for(Message mess:list) {
         logger.debug("mess:" + mess.getText());
    }
}

The remote host closed the connection. The error code is 0x800704CD

As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).

There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:

http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm

The following stack-overflow post might also be of interest:

"The remote host closed the connection" in Response.OutputStream.Write

How do I UPDATE from a SELECT in SQL Server?

The below solution works for a MySQL database:

UPDATE table1 a , table2 b 
SET a.columname = 'some value' 
WHERE b.columnname IS NULL ;

What does the red exclamation point icon in Eclipse mean?

I found another scenario in which the red exclamation mark might appear. I copied a directory from one project to another. This directory included a hidden .svn directory (the original project had been committed to version control). When I checked my new project into SVN, the copied directory still contained the old SVN information, incorrectly identifying itself as an element in its original project.

I discovered the problem by looking at the Properties for the directory, selecting SVN Info, and reviewing the Resource URL. I fixed the problem by deleting the hidden .svn directory for my copied directory and refreshing my project. The red exclamation mark disappeared, and I was able to check in the directory and its contents correctly.

keypress, ctrl+c (or some combo like that)

I couldn't get it to work with .keypress(), but it worked with the .keydown() function like this:

$(document).keydown(function(e) {
    if(e.key == "c" && e.ctrlKey) {
        console.log('ctrl+c was pressed');
    }
});

How do I return JSON without using a template in Django?

For rendering my models in JSON in django 1.9 I had to do the following in my views.py:

from django.core import serializers
from django.http import HttpResponse
from .models import Mymodel

def index(request):
    objs = Mymodel.objects.all()
    jsondata = serializers.serialize('json', objs)
    return HttpResponse(jsondata, content_type='application/json')

jQuery Remove string from string

Pretty sure nobody answer your question to your exact terms, you want it for dynamic text

var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );

It takes a substring from the first comma, to the end

jQuery Datepicker close datepicker after selected date

There is another code that's works for me (jQuery).

_x000D_
_x000D_
$(".datepicker").datepicker({_x000D_
    format: "dd/mm/yyyy",_x000D_
    autoHide: true_x000D_
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />_x000D_
Date: <input type="text" readonly="true" class="datepicker">
_x000D_
_x000D_
_x000D_

jQuery find and replace string

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

How to get the android Path string to a file on Assets folder?

Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:

@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
    val cacheFile = File(context.cacheDir, "splash_video")
    try {
        val inputStream = context.assets.open("splash_video")
        val outputStream = FileOutputStream(cacheFile)
        try {
            inputStream.copyTo(outputStream)
        } finally {
            inputStream.close()
            outputStream.close()
        }
    } catch (e: IOException) {
        throw IOException("Could not open splash_video", e)
    }
    return cacheFile
}

maven compilation failure

Inside in yours classses on which is complain maven is some dependecy which belongs to some jar's try right these jars re-build with maven command, i use this command mvn clean install -DskipTests=true should be work in this case when some symbols from classes is missing

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'} when you define your update, which means

return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
  query: {method:'GET', params:{entryId:''}, isArray:true},
  post: {method:'POST'},
  update: {method:'PUT', params: {entryId: '@entryId'}},
  remove: {method:'DELETE'}
});

Fix: Was missing a closing curly brace on the update line.

Ring Buffer in Java

If you need

  • O(1) insertion and removal
  • O(1) indexing to interior elements
  • access from a single thread only
  • generic element type

then you can use this CircularArrayList for Java in this way (for example):

CircularArrayList<String> buf = new CircularArrayList<String>(4);

buf.add("A");
buf.add("B");
buf.add("C");
buf.add("D"); // ABCD

String pop = buf.remove(0); // A <- BCD
buf.add("E"); // BCDE

String interiorElement = buf.get(i);

All these methods run in O(1).

Moving from position A to position B slowly with animation

Use jquery animate and give it a long duration say 2000

$("#Friends").animate({ 
        top: "-=30px",
      }, duration );

The -= means that the animation will be relative to the current top position.

Note that the Friends element must have position set to relative in the css:

#Friends{position:relative;}

Calling one method from another within same class in Python

To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.

class YourClass():

    def your_function(self, *args):

        self.callable_function(param) # if you need to pass any parameter

    def callable_function(self, *params): 
        print('Your param:', param)

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

Using JQuery to check if no radio button in a group has been checked

I think this is a simple example, how to check if a radio in a group of radios was checked.

if($('input[name=html_elements]:checked').length){
    //a radio button was checked
}else{
    //there was no radio button checked
} 

Oracle - how to remove white spaces?

If I understand correctly, this is what you want

select (trim(a) || trim(b))as combinedStrings from yourTable

Java - JPA - @Version annotation

Although @Pascal answer is perfectly valid, from my experience I find the code below helpful to accomplish optimistic locking:

@Entity
public class MyEntity implements Serializable {    
    // ...

    @Version
    @Column(name = "optlock", columnDefinition = "integer DEFAULT 0", nullable = false)
    private long version = 0L;

    // ...
}

Why? Because:

  1. Optimistic locking won't work if field annotated with @Version is accidentally set to null.
  2. As this special field isn't necessarily a business version of the object, to avoid a misleading, I prefer to name such field to something like optlock rather than version.

First point doesn't matter if application uses only JPA for inserting data into the database, as JPA vendor will enforce 0 for @version field at creation time. But almost always plain SQL statements are also in use (at least during unit and integration testing).

Get top 1 row of each group

I believe this can be done just like this. This might need some tweaking but you can just select the max from the group.

These answers are overkill..

SELECT
  d.DocumentID,
  MAX(d.Status),
  MAX(d1.DateCreated)
FROM DocumentStatusLogs d, DocumentStatusLogs d1
USING(DocumentID)
GROUP BY d.DocumentID
ORDER BY DateCreated DESC

how to access downloads folder in android?

For your first question try

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 

(available since API 8)

To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.

How can I get the last day of the month in C#?

Something like:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

How to convert a huge list-of-vector to a matrix more efficiently?

This should be equivalent to your current code, only a lot faster:

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

It's a bit late, But easy and effective. Click on About Android Studio, Check the current version, Open build.graddle of Project and put it in front of the class path. e.g Your studio version is 3.5.2, then your classpath should be like that.

classpath 'com.android.tools.build:gradle:3.5.2'

bootstrap 3 wrap text content within div for horizontal alignment

Your code is working fine using bootatrap v3.3.7, but you can use word-break: break-word if it's not working at your end.

which would then look like this -

snap

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"_x000D_
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <div class="row" style="box-shadow: 0 0 30px black;">_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2005 Volkswagen Jetta 2.5 Sedan (worcester http://www.massmotorcars.com)_x000D_
                $6900</h3>_x000D_
            <p>_x000D_
                <small>2005 volkswagen jetta 2.5 for sale has 110,000 miles powere doors,power windows,has ,car drives_x000D_
                    excellent ,comes with warranty if you&#39;re ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1355/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1355">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2006 Honda Civic EX Sedan (Worcester www.massmotorcars.com) $7950</h3>_x000D_
            <p>_x000D_
                <small>2006 honda civic ex has 110,176 miles, has power doors ,power windows,sun roof,alloy wheels,runs_x000D_
                    great, cd player, 4 cylinder engen, ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1356/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1356">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2004 Honda Civic LX Sedan (worcester www.massmotorcars.com) $5900</h3>_x000D_
            <p>_x000D_
                <small>2004 honda civic lx sedan has 134,000 miles, great looking car, interior and exterior looks_x000D_
                    nice,has_x000D_
                    cd player, power windows ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1357/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1357">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

PHP Regex to check date is in YYYY-MM-DD format

It all depends on how strict you want this function to be. For instance, if you don't want to allow months above 12 and days above 31 (not depending on the month, that would require writing date-logic), it could become pretty complicated:

function checkDate($date)
{
  $regex = '/^' . 
    '(' .

    // Allows years 0000-9999
    '(?:[0-9]{4})' .
    '\-' .

    // Allows 01-12
    '(?:' .
    '(?:01)|(?:02)|(?:03)|(?:04)|(?:05)|(?:06)|(?:07)|(?:08)|(?:09)|(?:10)|' .
    '(?:11)|(?:12)' .
    ')' .
    '\-' .

    // Allows 01-31
    '(?:' .
    '(?:01)|(?:02)|(?:03)|(?:04)|(?:05)|(?:06)|(?:07)|(?:08)|(?:09)|(?:10)|' .
    '(?:11)|(?:12)|(?:13)|(?:14)|(?:15)|(?:16)|(?:17)|(?:18)|(?:19)|(?:20)|' .
    '(?:21)|(?:22)|(?:23)|(?:24)|(?:25)|(?:26)|(?:27)|(?:28)|(?:29)|(?:30)|' .
    '(?:31)' .
    ')' .

    '$/';

  if ( preg_match($regex, $date) ) {
    return true;
  }

  return false;
}

$result = checkDate('2012-09-12');

Personally I'd just go for: /^([0-9]{4}\-([0-9]{2}\-[0-9]{2})$/

How to create a checkbox with a clickable label?

This should help you: W3Schools - Labels

<form>
  <label for="male">Male</label>
  <input type="radio" name="sex" id="male" />
  <br />
  <label for="female">Female</label>
  <input type="radio" name="sex" id="female" />
</form>

Chrome:The website uses HSTS. Network errors...this page will probably work later

Encountered similar error. resetting chrome://net-internals/#hsts did not work for me. The issue was that my vm's clock was skewed by days. resetting the time did work out to resolve this issue. https://support.google.com/chrome/answer/4454607?hl=en

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

This is a simple solution that worked for me with the same problem (I think): mv /var/lib/mongodb /var/lib/mongodb_backup mkdir /var/lib/mongodb chmod 700 /var/lib/mongodb chown mongodb:daemon /var/lib/mongodb systemctl restart mongodb or service mongod restart

What are Makefile.am and Makefile.in?

Makefile.am is a programmer-defined file and is used by automake to generate the Makefile.in file (the .am stands for automake). The configure script typically seen in source tarballs will use the Makefile.in to generate a Makefile.

The configure script itself is generated from a programmer-defined file named either configure.ac or configure.in (deprecated). I prefer .ac (for autoconf) since it differentiates it from the generated Makefile.in files and that way I can have rules such as make dist-clean which runs rm -f *.in. Since it is a generated file, it is not typically stored in a revision system such as Git, SVN, Mercurial or CVS, rather the .ac file would be.

Read more on GNU Autotools. Read about make and Makefile first, then learn about automake, autoconf, libtool, etc.

Find the division remainder of a number

you are looking for the modulo operator:

a % b

for example:

26 % 7

Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either.

Docker Networking - nginx: [emerg] host not found in upstream

(new to nginx) In my case it was wrong folder name

For config

upstream serv {
    server ex2_app_1:3000;
}

make sure the app folder is in ex2 folder:

ex2/app/...

The openssl extension is required for SSL/TLS protection

according to the composer reference there are two relevant options: disable-tls and secure-http.

nano ~/.composer/config.json (If the file does not exist or is empty, then just create it with the following content)

{
    "config": {
        "disable-tls": true,
        "secure-http": false
    }
}

then it complains much:

You are running Composer with SSL/TLS protection disabled.
Warning: Accessing getcomposer.org over http which is an insecure protocol.

but it performs the composer selfupdate (or whatever).

while one cannot simply "enable SSL in the php.ini" on Linux; PHP needs to be compiled with openSSL configured as shared library - in order to be able to access it from the PHP CLI SAPI.

Get number days in a specified month using JavaScript?

The following takes any valid datetime value and returns the number of days in the associated month... it eliminates the ambiguity of both other answers...

 // pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getFullYear(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

'uint32_t' identifier not found error

This type is defined in the C header <stdint.h> which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.

In the meantime, you could probably fake up your own version of the header by adding typedefs that map Microsoft's custom integer types to the types expected by C. For example:

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */

Hope this helps!

How do you run a Python script as a service in Windows?

The simplest way to achieve this is to use native command sc.exe:

sc create PythonApp binPath= "C:\Python34\Python.exe --C:\tmp\pythonscript.py"

References:

  1. https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
  2. When creating a service with sc.exe how to pass in context parameters?

Nested Recycler view height doesn't wrap its content

I have tried all solutions, they are very useful but this only works fine for me

public class  LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

    public LinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);
        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {


            if (getOrientation() == HORIZONTAL) {

                measureScrapChild(recycler, i,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                        heightSpec,
                        mMeasuredDimension);

                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                measureScrapChild(recycler, i,
                        widthSpec,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                        mMeasuredDimension);
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }

        if (height < heightSize || width < widthSize) {

            switch (widthMode) {
                case View.MeasureSpec.EXACTLY:
                    width = widthSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }

            switch (heightMode) {
                case View.MeasureSpec.EXACTLY:
                    height = heightSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }

            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
        }
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        recycler.bindViewToPosition(view, position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

How can I initialize a MySQL database with schema in a Docker container?

For the ones not wanting to create an entrypoint script like me, you actually can start mysqld at build-time and then execute the mysql commands in your Dockerfile like so:

RUN mysqld_safe & until mysqladmin ping; do sleep 1; done && \
    mysql -uroot -e "CREATE DATABASE somedb;" && \
    mysql -uroot -e "CREATE USER 'someuser'@'localhost' IDENTIFIED BY 'somepassword';" && \
    mysql -uroot -e "GRANT ALL PRIVILEGES ON somedb.* TO 'someuser'@'localhost';"

The key here is to send mysqld_safe to background with the single & sign.

Get Android Device Name

 static String getDeviceName() {
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method getMethod = systemPropertiesClass.getMethod("get", String.class);
            Object object = new Object();
            Object obj = getMethod.invoke(object, "ro.product.device");
            return (obj == null ? "" : (String) obj);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

enter image description here

you can get 'idol3' by this way.

How do I get the parent directory in Python?

import os

def parent_filedir(n):
    return parent_filedir_iter(n, os.path.dirname(__file__))

def parent_filedir_iter(n, path):
    n = int(n)
    if n <= 1:
        return path
    return parent_filedir_iter(n - 1, os.path.dirname(path))

test_dir = os.path.abspath(parent_filedir(2))

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

I'm using a similar code as those that use the while loop but I call the entry count in every loop... so I suppose it's somewhat slower

FragmentManager manager = getFragmentManager();
while (manager.getBackStackEntryCount() > 0){
        manager.popBackStackImmediate();
    }

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Actually, vim does allow what you're looking for. Enter vim, and type the following commands:

:args **/*.java
:argdo set ff=unix | update | next

The first of these commands sets the argument list to every file matching **/*.java, which is all Java files, recursively. The second of these commands does the following to each file in the argument list, in turn:

  • Sets the line-endings to Unix style (you already know this)
  • Writes the file out iff it's been changed
  • Proceeds to the next file

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

It's perfectly safe as long as you always access the values through the struct via the . (dot) or -> notation.

What's not safe is taking the pointer of unaligned data and then accessing it without taking that into account.

Also, even though each item in the struct is known to be unaligned, it's known to be unaligned in a particular way, so the struct as a whole must be aligned as the compiler expects or there'll be trouble (on some platforms, or in future if a new way is invented to optimise unaligned accesses).

How to center an element horizontally and vertically

CSS Grid: place-items

Finally, we have place-items: center for CSS Grid to make it easier.

HTML

<div class="parent">
  <div class="to-center"></div>
</div>

CSS

.parent {
  display: grid;
  place-items: center;
}

Output:

_x000D_
_x000D_
html,
body {
  height: 100%;
}

.container {
  display: grid;
  place-items: center;
  height: 100%;
}

.center {
  background: #5F85DB;
  color: #fff;
  font-weight: bold;
  font-family: Tahoma;
  padding: 10px;
}
_x000D_
<div class="container">
  <div class="center" contenteditable>I am always super centered within my parent</div>
</div>
_x000D_
_x000D_
_x000D_

HTML input fields does not get focus when clicked

I had this issue caused by a sort of overlap of a div element with a bootstrap class ="row" over a "brother" div element with the class="col", the first hid the focus of the second div element.

I solved taking outer the div row element from that level of the divs' tree and so rebalancing bootstrap logical hierarchy based on the row and col classes.

set font size in jquery

Try:

$("#"+styleTarget).css({ 'font-size': $(this).val() });

By putting the value in quotes, it becomes a string, and "+$(this).val()+"px is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:

Using a map:

$("#elem").css({
    fontSize: 20
});

Using key and value parameters:

All of these are valid.

$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");

You can replace "fontSize" with "font-size" but it will have to be quoted then.

Cannot open backup device. Operating System error 5

In my case, I forgot to name the backup file and it kept giving me the same permission error :/

TO DISK N'{path}\WRITE_YOUR_BACKUP_FILENAME_HERE.bak'

Spark read file from S3 using sc.textFile ("s3n://...)

Ran into the same problem in Spark 2.0.2. Resolved it by feeding it the jars. Here's what I ran:

$ spark-shell --jars aws-java-sdk-1.7.4.jar,hadoop-aws-2.7.3.jar,jackson-annotations-2.7.0.jar,jackson-core-2.7.0.jar,jackson-databind-2.7.0.jar,joda-time-2.9.6.jar

scala> val hadoopConf = sc.hadoopConfiguration
scala> hadoopConf.set("fs.s3.impl","org.apache.hadoop.fs.s3native.NativeS3FileSystem")
scala> hadoopConf.set("fs.s3.awsAccessKeyId",awsAccessKeyId)
scala> hadoopConf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey)
scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)
scala> sqlContext.read.parquet("s3://your-s3-bucket/")

obviously, you need to have the jars in the path where you're running spark-shell from

Cassandra port usage - how are the ports used?

Ports 57311 and 57312 are randomly assigned ports used for RMI communication. These ports change each time Cassandra starts up, but need to be open in the firewall, along with 8080/7199 (depending on version), to allow for remote JMX access. Something that doesn't appear to be particularly well documented, but has tripped me up in the past.

Extension mysqli is missing, phpmyadmin doesn't work

For the record, my system is Ubuntu Server 20.04 and none of the solutions here worked. For me, I installed PHP 7.4 and I had to edit enter code here/etc/php/7.4/apache2/php.ini`.

Within this, search for ;extension=mysqli, uncomment and change mysqli to mysqlnd so it should look like this extension=mysqlnd. I tried using mysqli but I faced the same error as if I didn't enable it but mysqlnd worked for me.

Use a.any() or a.all()

This should also work and is a closer answer to what is asked in the question:

for i in range(len(x)):
    if valeur.item(i) <= 0.6:
        print ("this works")
    else:   
        print ("valeur is too high")

How to put a text beside the image?

Use floats to float the image, the text should wrap beside

http://www.w3schools.com/css/css_float.asp

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

How to connect to a docker container from outside the host (same network) [Windows]

TL;DR Check the network mode of your VirtualBox host - it should be bridged if you want the virtual machine (and the Docker container it's hosting) accessible on your local network.


It sounds like your confusion lies in which host to connect to in order to access your application via HTTP. You haven't really spelled out what your configuration is - I'm going to make some guesses, based on the fact that you've got "Windows" and "VirtualBox" in your tags.

I'm guessing that you have Docker running on some flavour of Linux running in VirtualBox on a Windows host. I'm going to label the IP addresses as follows:

D = the IP address of the Docker container

L = the IP address of the Linux host running in VirtualBox

W = the IP address of the Windows host

When you run your Go application on your Windows host, you can connect to it with http://W:8080/ from anywhere on your local network. This works because the Go application binds the port 8080 on the Windows machine and anybody who tries to access port 8080 at the IP address W will get connected.

And here's where it becomes more complicated:

VirtualBox, when it sets up a virtual machine (VM), can configure the network in one of several different modes. I don't remember what all the different options are, but the one you want is bridged. In this mode, VirtualBox connects the virtual machine to your local network as if it were a stand-alone machine on the network, just like any other machine that was plugged in to your network. In bridged mode, the virtual machine appears on your network like any other machine. Other modes set things up differently and the machine will not be visible on your network.

So, assuming you set up networking correctly for the Linux host (bridged), the Linux host will have an IP address on your local network (something like 192.168.0.x) and you will be able to access your Docker container at http://L:8080/.

If the Linux host is set to some mode other than bridged, you might be able to access from the Windows host, but this is going to depend on exactly what mode it's in.

EDIT - based on the comments below, it sounds very much like the situation I've described above is correct.

Let's back up a little: here's how Docker works on my computer (Ubuntu Linux).

Imagine I run the same command you have: docker run -p 8080:8080 dockertest. What this does is start a new container based on the dockertest image and forward (connect) port 8080 on the Linux host (my PC) to port 8080 on the container. Docker sets up it's own internal networking (with its own set of IP addresses) to allow the Docker daemon to communicate and to allow containers to communicate with one another. So basically what you're doing with that -p 8080:8080 is connecting Docker's internal networking with the "external" network - ie. the host's network adapter - on a particular port.

With me so far? OK, now let's take a step back and look at your system. Your machine is running Windows - Docker does not (currently) run on Windows, so the tool you're using has set up a Linux host in a VirtualBox virtual machine. When you do the docker run in your environment, exactly the same thing is happening - port 8080 on the Linux host is connected to port 8080 on the container. The big difference here is that your Windows host is not the Linux host on which the container is running, so there's another layer here and it's communication across this layer where you are running into problems.

What you need is one of two things:

  1. to connect port 8080 on the VirtualBox VM to port 8080 on the Windows host, just like you connect the Docker container to the host port.

  2. to connect the VirtualBox VM directly to your local network with the bridged network mode I described above.

If you go for the first option, you will be able to access the container at http://W:8080 where W is the IP address or hostname of the Windows host. If you opt for the second, you will be able to access the container at http://L:8080 where L is the IP address or hostname of the Linux VM.

So that's all the higher-level explanation - now you need to figure out how to change the configuration of the VirtualBox VM. And here's where I can't really help you - I don't know what tool you're using to do all this on your Windows machine and I'm not at all familiar with using Docker on Windows.

If you can get to the VirtualBox configuration window, you can make the changes described below. There is also a command line client that will modify VMs, but I'm not familiar with that.

For bridged mode (and this really is the simplest choice), shut down your VM, click the "Settings" button at the top, and change the network mode to bridged, then restart the VM and you're good to go. The VM should pick up an IP address on your local network via DHCP and should be visible to other computers on the network at that IP address.

How to define a relative path in java

 File f1 = new File("..\\..\\..\\config.properties");  

this path trying to access file is in Project directory then just access file like this.

File f=new File("filename.txt");

if your file is in OtherSources/Resources

this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

Solving in underscore

data = [];
_.times( highEnd, function( n ){ data.push( lowEnd ++ ) } );

Break or return from Java 8 stream forEach?

I would suggest using anyMatch. Example:-

return someObjects.stream().anyMatch(obj -> 
    some_condition_met;
);

You can refer this post for understanding anyMatch:- https://beginnersbook.com/2017/11/java-8-stream-anymatch-example/

Error when creating a new text file with python?

import sys

def write():
    print('Creating new text file') 

    name = raw_input('Enter name of text file: ')+'.txt'  # Name of text file coerced with +.txt

    try:
        file = open(name,'a')   # Trying to create a new file or open one
        file.close()

    except:
        print('Something went wrong! Can\'t tell what?')
        sys.exit(0) # quit Python

write()

this will work promise :)

Copying files from server to local computer using SSH

that scp command must be issued on the local command-line, for putty the command is pscp.

C:\something> pscp [email protected]:/dir/of/file.txt \local\dir\

fopen deprecated warning

If you code is intended for a different OS (like Mac OS X, Linux) you may use following:

#ifdef _WIN32
#define _CRT_SECURE_NO_DEPRECATE
#endif

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

Versioning of assemblies in .NET can be a confusing prospect given that there are currently at least three ways to specify a version for your assembly.

Here are the three main version-related assembly attributes:

// Assembly mscorlib, Version 2.0.0.0
[assembly: AssemblyFileVersion("2.0.50727.3521")]
[assembly: AssemblyInformationalVersion("2.0.50727.3521")]
[assembly: AssemblyVersion("2.0.0.0")]

By convention, the four parts of the version are referred to as the Major Version, Minor Version, Build, and Revision.

The AssemblyFileVersion is intended to uniquely identify a build of the individual assembly

Typically you’ll manually set the Major and Minor AssemblyFileVersion to reflect the version of the assembly, then increment the Build and/or Revision every time your build system compiles the assembly. The AssemblyFileVersion should allow you to uniquely identify a build of the assembly, so that you can use it as a starting point for debugging any problems.

On my current project we have the build server encode the changelist number from our source control repository into the Build and Revision parts of the AssemblyFileVersion. This allows us to map directly from an assembly to its source code, for any assembly generated by the build server (without having to use labels or branches in source control, or manually keeping any records of released versions).

This version number is stored in the Win32 version resource and can be seen when viewing the Windows Explorer property pages for the assembly.

The CLR does not care about nor examine the AssemblyFileVersion.

The AssemblyInformationalVersion is intended to represent the version of your entire product

The AssemblyInformationalVersion is intended to allow coherent versioning of the entire product, which may consist of many assemblies that are independently versioned, perhaps with differing versioning policies, and potentially developed by disparate teams.

“For example, version 2.0 of a product might contain several assemblies; one of these assemblies is marked as version 1.0 since it’s a new assembly that didn’t ship in version 1.0 of the same product. Typically, you set the major and minor parts of this version number to represent the public version of your product. Then you increment the build and revision parts each time you package a complete product with all its assemblies.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 57

The CLR does not care about nor examine the AssemblyInformationalVersion.

The AssemblyVersion is the only version the CLR cares about (but it cares about the entire AssemblyVersion)

The AssemblyVersion is used by the CLR to bind to strongly named assemblies. It is stored in the AssemblyDef manifest metadata table of the built assembly, and in the AssemblyRef table of any assembly that references it.

This is very important, because it means that when you reference a strongly named assembly, you are tightly bound to a specific AssemblyVersion of that assembly. The entire AssemblyVersion must be an exact match for the binding to succeed. For example, if you reference version 1.0.0.0 of a strongly named assembly at build-time, but only version 1.0.0.1 of that assembly is available at runtime, binding will fail! (You will then have to work around this using Assembly Binding Redirection.)

Confusion over whether the entire AssemblyVersion has to match. (Yes, it does.)

There is a little confusion around whether the entire AssemblyVersion has to be an exact match in order for an assembly to be loaded. Some people are under the false belief that only the Major and Minor parts of the AssemblyVersion have to match in order for binding to succeed. This is a sensible assumption, however it is ultimately incorrect (as of .NET 3.5), and it’s trivial to verify this for your version of the CLR. Just execute this sample code.

On my machine the second assembly load fails, and the last two lines of the fusion log make it perfectly clear why:

.NET Framework Version: 2.0.50727.3521
---
Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f
Successfully loaded assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f
---
Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
Assembly binding for  failed:
System.IO.FileLoadException: Could not load file or assembly 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, 
PublicKeyToken=0b3305902db7183f' or one of its dependencies. The located assembly's manifest definition 
does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f'

=== Pre-bind state information ===
LOG: User = Phoenix\Dani
LOG: DisplayName = Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
 (Fully-specified)
LOG: Appbase = [...]
LOG: Initial PrivatePath = NULL
Calling assembly : AssemblyBinding, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Post-policy reference: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f
LOG: Attempting download of new URL [...].
WRN: Comparing the assembly name resulted in the mismatch: Revision Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

I think the source of this confusion is probably because Microsoft originally intended to be a little more lenient on this strict matching of the full AssemblyVersion, by matching only on the Major and Minor version parts:

“When loading an assembly, the CLR will automatically find the latest installed servicing version that matches the major/minor version of the assembly being requested.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 56

This was the behaviour in Beta 1 of the 1.0 CLR, however this feature was removed before the 1.0 release, and hasn’t managed to re-surface in .NET 2.0:

“Note: I have just described how you should think of version numbers. Unfortunately, the CLR doesn’t treat version numbers this way. [In .NET 2.0], the CLR treats a version number as an opaque value, and if an assembly depends on version 1.2.3.4 of another assembly, the CLR tries to load version 1.2.3.4 only (unless a binding redirection is in place). However, Microsoft has plans to change the CLR’s loader in a future version so that it loads the latest build/revision for a given major/minor version of an assembly. For example, on a future version of the CLR, if the loader is trying to find version 1.2.3.4 of an assembly and version 1.2.5.0 exists, the loader with automatically pick up the latest servicing version. This will be a very welcome change to the CLR’s loader — I for one can’t wait.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 164 (Emphasis mine)

As this change still hasn’t been implemented, I think it’s safe to assume that Microsoft had back-tracked on this intent, and it is perhaps too late to change this now. I tried to search around the web to find out what happened with these plans, but I couldn’t find any answers. I still wanted to get to the bottom of it.

So I emailed Jeff Richter and asked him directly — I figured if anyone knew what happened, it would be him.

He replied within 12 hours, on a Saturday morning no less, and clarified that the .NET 1.0 Beta 1 loader did implement this ‘automatic roll-forward’ mechanism of picking up the latest available Build and Revision of an assembly, but this behaviour was reverted before .NET 1.0 shipped. It was later intended to revive this but it didn’t make it in before the CLR 2.0 shipped. Then came Silverlight, which took priority for the CLR team, so this functionality got delayed further. In the meantime, most of the people who were around in the days of CLR 1.0 Beta 1 have since moved on, so it’s unlikely that this will see the light of day, despite all the hard work that had already been put into it.

The current behaviour, it seems, is here to stay.

It is also worth noting from my discussion with Jeff that AssemblyFileVersion was only added after the removal of the ‘automatic roll-forward’ mechanism — because after 1.0 Beta 1, any change to the AssemblyVersion was a breaking change for your customers, there was then nowhere to safely store your build number. AssemblyFileVersion is that safe haven, since it’s never automatically examined by the CLR. Maybe it’s clearer that way, having two separate version numbers, with separate meanings, rather than trying to make that separation between the Major/Minor (breaking) and the Build/Revision (non-breaking) parts of the AssemblyVersion.

The bottom line: Think carefully about when you change your AssemblyVersion

The moral is that if you’re shipping assemblies that other developers are going to be referencing, you need to be extremely careful about when you do (and don’t) change the AssemblyVersion of those assemblies. Any changes to the AssemblyVersion will mean that application developers will either have to re-compile against the new version (to update those AssemblyRef entries) or use assembly binding redirects to manually override the binding.

  • Do not change the AssemblyVersion for a servicing release which is intended to be backwards compatible.
  • Do change the AssemblyVersion for a release that you know has breaking changes.

Just take another look at the version attributes on mscorlib:

// Assembly mscorlib, Version 2.0.0.0
[assembly: AssemblyFileVersion("2.0.50727.3521")]
[assembly: AssemblyInformationalVersion("2.0.50727.3521")]
[assembly: AssemblyVersion("2.0.0.0")]

Note that it’s the AssemblyFileVersion that contains all the interesting servicing information (it’s the Revision part of this version that tells you what Service Pack you’re on), meanwhile the AssemblyVersion is fixed at a boring old 2.0.0.0. Any change to the AssemblyVersion would force every .NET application referencing mscorlib.dll to re-compile against the new version!

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Handling very large numbers in Python

You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.

  • Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.

  • Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.

  • The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.

Drop rows containing empty cells from a pandas DataFrame

You can use this variation:

import pandas as pd
vals = {
    'name' : ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
    'gender' : ['m', 'f', 'f', 'f',  'f', 'c', 'c'],
    'age' : [39, 12, 27, 13, 36, 29, 10],
    'education' : ['ma', None, 'school', None, 'ba', None, None]
}
df_vals = pd.DataFrame(vals) #converting dict to dataframe

This will output(** - highlighting only desired rows):

   age education gender name
0   39        ma      m   n1 **
1   12      None      f   n2    
2   27    school      f   n3 **
3   13      None      f   n4
4   36        ba      f   n5 **
5   29      None      c   n6
6   10      None      c   n7

So to drop everything that does not have an 'education' value, use the code below:

df_vals = df_vals[~df_vals['education'].isnull()] 

('~' indicating NOT)

Result:

   age education gender name
0   39        ma      m   n1
2   27    school      f   n3
4   36        ba      f   n5

How to loop backwards in python?

To reverse a string without using reversed or [::-1], try something like:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

jQuery find element by data attribute value

I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)

var numb = "3";
$(`#myid[data-tab-id=${numb}]`);

What is the volatile keyword useful for?

No one has mentioned the treatment of read and write operation for long and double variable type. Reads and writes are atomic operations for reference variables and for most primitive variables, except for long and double variable types, which must use the volatile keyword to be atomic operations. @link

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());

This works for me.

I forgot the password I entered during postgres installation

If you are in windows you can just run

net user postgres postgres

and login in postgres with postgres/postgres as user/password

Include php files when they are in different folders

Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

SQL query: Delete all records from the table except latest N?

This should work as well:

DELETE FROM [table] 
INNER JOIN (
    SELECT [id] 
    FROM (
        SELECT [id] 
        FROM [table] 
        ORDER BY [id] DESC
        LIMIT N
    ) AS Temp
) AS Temp2 ON [table].[id] = [Temp2].[id]

How to get PHP $_GET array?

Put all the ids into a variable called $ids and separate them with a ",":

$ids = "1,2,3,4,5,6";

Pass them like so:

$url = "?ids={$ids}";

Process them:

$ids = explode(",", $_GET['ids']);

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

How do I change the font size and color in an Excel Drop Down List?

Try making the whole sheet font size smaller. Then zoom and save. Make a practice sheet first because it really screws everything up.

How can I join multiple SQL tables using the IDs?

You want something more like this:

SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
    JOIN TableB
        ON TableB.aID = TableA.aID
    JOIN TableC
        ON TableC.cID = TableB.cID
    JOIN TableD
        ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now()) 

In your example, you are not actually including TableD. All you have to do is perform another join just like you have done before.

A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.

How to return part of string before a certain character?

You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:

str.substring(0, str.indexOf(":"));

Where 'str' represents the variable with your string inside.

Click here for JSFiddle Example

Javascript

var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');

var left_text = input_string.substring(0, input_string.indexOf(":"));

output_element.innerText = left_text;

Html

<p>
  <h5>Input:</h5>
  <strong id="my-input">Left Text:Right Text</strong>
  <h5>Output:</h5>
  <strong id="my-output">XXX</strong>
</p>

CSS

body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
  width:90%;
  padding: 0.5em 1em;
  background-color: cyan;
}
#my-output { background-color: gold; }

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Difference between pre-increment and post-increment in a loop?

Pre-increment ++i increments the value of i and evaluates to the new incremented value.

int i = 3;
int preIncrementResult = ++i;
Assert( preIncrementResult == 4 );
Assert( i == 4 );

Post-increment i++ increments the value of i and evaluates to the original non-incremented value.

int i = 3;
int postIncrementResult = i++;
Assert( postIncrementtResult == 3 );
Assert( i == 4 );

In C++, the pre-increment is usually preferred where you can use either.

This is because if you use post-increment, it can require the compiler to have to generate code that creates an extra temporary variable. This is because both the previous and new values of the variable being incremented need to be held somewhere because they may be needed elsewhere in the expression being evaluated.

So, in C++ at least, there can be a performance difference which guides your choice of which to use.

This is mainly only a problem when the variable being incremented is a user defined type with an overridden ++ operator. For primitive types (int, etc) there's no performance difference. But, it's worth sticking to the pre-increment operator as a guideline unless the post-increment operator is definitely what's required.

There's some more discussion here.

In C++ if you're using STL, then you may be using for loops with iterators. These mainly have overridden ++ operators, so sticking to pre-increment is a good idea. Compilers get smarter all the time though, and newer ones may be able to perform optimizations that mean there's no performance difference - especially if the type being incremented is defined inline in header file (as STL implementations often are) so that the compiler can see how the method is implemented and can then know what optimizations are safe to perform. Even so, it's probably still worth sticking to pre-increment because loops get executed lots of times and this means a small performance penalty could soon get amplified.


In other languages such as C# where the ++ operator can't be overloaded there is no performance difference. Used in a loop to advance the loop variable, the pre and post increment operators are equivalent.

Correction: overloading ++ in C# is allowed. It seems though, that compared to C++, in C# you cannot overload the pre and post versions independently. So, I would assume that if the result of calling ++ in C# is not assigned to a variable or used as part of a complex expression, then the compiler would reduce the pre and post versions of ++ down to code that performs equivalently.

Setting max width for body using Bootstrap

Edit

A better way to do this is:

  1. Create your own less file as a main less file ( like bootstrap.less ).

  2. Import all bootstrap less files you need. (in this case, you just need to Import all responsive less files but responsive-1200px-min.less)

  3. If you need to modify anything in original bootstrap less file, you just need to write your own less to overwrite bootstrap's less code. (Just remember to put your less code/file after @import { /* bootstrap's less file */ };).

Original

I have the same problem. This is how I fixed it.

Find the media query:

@media (max-width:1200px) ...

Remove it. (I mean the whole thing , not just @media (max-width:1200px))

Since the default width of Bootstrap is 940px, you don't need to do anything.

If you want to have your own max-width, just modify the css rule in the media query that matches your desired width.

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

From the documentation of SimpleDateFormat:

Letter     Date or Time Component     Presentation     Examples  
S          Millisecond                Number           978 

So it is milliseconds, or 1/1000th of a second. You just format it with on 6 digits, so you add 3 extra leading zeroes...

You can check it this way:

    Date d =new Date();
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(d));

Output:

2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.0132
2013-10-07 12:13:27.00132
2013-10-07 12:13:27.000132

(Ideone fiddle)

What does %s and %d mean in printf in the C language?

% notation is called a format specifier. For example, %d tells printf() to print an integer. %s to print a string (char *) etc. You should really look it up here: http://google.com/search?q=printf+format+specifiers

No, commas are not used for string concatenation. Commas are for separating arguments passed to a function.

Installing TensorFlow on Windows (Python 3.6.x)

I was having Python 3.6 and was facing the issue as "No module named tensorflow" on "pip install tensorflow". Turned out as my machine was of 64 bit while the Python 3.6 version installed was for 32 bit. Uninstalled it, reinstalled the Python 3.6 x64 version, pip installed tensorflow, problem solved.

How to sort an array of objects in Java?

Update for Java 8 constructs

Assuming a Book class with a name field getter, you can use Arrays.sort method by passing an additional Comparator specified using Java 8 constructs - Comparator default method & method references.

Arrays.sort(bookArray, Comparator.comparing(Book::getName));

Also, it's possible to compare on multiple fields using thenComparing methods.

Arrays.sort(bookArray, Comparator.comparing(Book::getName)
      .thenComparing(Book::getAuthor))
      .thenComparingInt(Book::getId));

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Class 'ViewController' has no initializers in swift

Sometimes this error also appears when you have a var or a let that hasn't been intialized.

For example

class ViewController: UIViewController {
    var x: Double
    // or
    var y: String
    // or
    let z: Int
}

Depending on what your variable is supposed to do you might either set that var type as an optional or initialize it with a value like the following

class ViewController: UIViewCOntroller {
    // Set an initial value for the variable
    var x: Double = 0
    // or an optional String
    var y: String?
    // or
    let z: Int = 2
}

HTML table with fixed headers?

Most of the solutions posted here require jQuery. If you are looking for a framework independent solution try Grid: http://www.matts411.com/post/grid/

It's hosted on Github here: https://github.com/mmurph211/Grid

Not only does it support fixed headers, it also supports fixed left columns and footers, among other things.

Why do I need to do `--set-upstream` all the time?

You can also explicitly tell git pull what remote branch to pull (as it mentions in the error message):

git pull <remote-name> <remote-branch>

Be careful with this, however: if you are on a different branch and do an explicit pull, the refspec you pull will be merged into the branch you're on!

SQL Query - how do filter by null or not null

How about statusid = statusid. Null is never equal to null.

vuetify center items into v-flex

v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.

So, you should override it with display: flex in your HTML or CSS to make it work with justify-content.

How to catch all exceptions in c# using try and catch?

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw; and not throw ex;.

How do I get first element rather than using [0] in jQuery?

$("#grid_GridHeader:first") works as well.

CSS smooth bounce animation

Here is code not using the percentage in the keyframes. Because you used percentages the animation does nothing a long time.

  • 0% translate 0px
  • 20% translate 0px
  • etc.

How does this example work:

  1. We set an animation. This is a short hand for animation properties.
  2. We immediately start the animation since we use from and to in the keyframes. from is = 0% and to is = 100%
  3. We can now control how fast it will bounce by setting the animation time: animation: bounce 1s infinite alternate; the 1s is how long the animation will last.

_x000D_
_x000D_
.ball {_x000D_
  margin-top: 50px;_x000D_
  border-radius: 50%;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  background-color: cornflowerblue;_x000D_
  border: 2px solid #999;_x000D_
  animation: bounce 1s infinite alternate;_x000D_
  -webkit-animation: bounce 1s infinite alternate;_x000D_
}_x000D_
@keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}
_x000D_
<div class="ball"></div>
_x000D_
_x000D_
_x000D_

var functionName = function() {} vs function functionName() {}

Another difference between both function is functionOne can be used as a variable that can hold multiple functions within and functionTwo holds some block of code that gets executed all when called. Please check below :

   var functionOne = (function() {
      return {

         sayHello: function(){
                console.log('say hello')

         },
         redirectPage:function(_url){
                window.location.href = _url;
         }

      }
})();

You have a choice which function to be called. e.g functionOne.sayHello or functionOne. redirectPage. And if you call functionTwo then whole block of code will get executed.

Is there a TRY CATCH command in Bash

Below is an complete copy of the simplified script used in my other answer. Beyond additional error checking, there is an alias which allows the user to change the name of an existing alias. The syntax is given below. If the new_alias parameter is omitted, then the alias is removed.

ChangeAlias old_alias [new_alias]

The complete script is given below.

common.GetAlias() {
    local "oldname=${1:-0}"
    if [[ $oldname =~ ^[0-9]+$ && oldname+1 -lt ${#FUNCNAME[@]} ]]; then
        oldname="${FUNCNAME[oldname + 1]}"
    fi
    name="common_${oldname#common.}"
    echo "${!name:-$oldname}"
}

common.Alias() {
    if [[ $# -ne 2 || -z $1 || -z $2 ]]; then
        echo "$(common.GetAlias): The must be only two parameters of nonzero length" >&2
        return 1;
    fi
    eval "alias $1='$2'"
    local "f=${2##*common.}"
    f="${f%%;*}"
    local "v=common_$f"
    f="common.$f"
    if [[ -n ${!v:-} ]]; then
        echo "$(common.GetAlias): $1: Function \`$f' already paired with name \`${!v}'" >&2
        return 1;
    fi
    shopt -s expand_aliases
    eval "$v=\"$1\""
}

common.ChangeAlias() {
    if [[ $# -lt 1 || $# -gt 2 ]]; then
        echo "usage: $(common.GetAlias) old_name [new_name]" >&2
        return "1"
    elif ! alias "$1" &>"/dev/null"; then
        echo "$(common.GetAlias): $1: Name not found" >&2
        return 1;
    fi
    local "s=$(alias "$1")" 
    s="${s#alias $1=\'}"
    s="${s%\'}"
    local "f=${s##*common.}"
    f="${f%%;*}"
    local "v=common_$f"
    f="common.$f"
    if [[ ${!v:-} != "$1" ]]; then
        echo "$(common.GetAlias): $1: Name not paired with a function \`$f'" >&2
        return 1;
    elif [[ $# -gt 1 ]]; then
        eval "alias $2='$s'"
        eval "$v=\"$2\""
    else
        unset "$v"
    fi
    unalias "$1"
}

common.Alias exception             'common.Exception'
common.Alias throw                 'common.Throw'
common.Alias try                   '{ if common.Try; then'
common.Alias yrt                   'common.EchoExitStatus; fi; common.yrT; }'
common.Alias catch                 '{ while common.Catch'
common.Alias hctac                 'common.hctaC -r; done; common.hctaC; }'
common.Alias finally               '{ if common.Finally; then'
common.Alias yllanif               'fi; common.yllaniF; }'
common.Alias caught                'common.Caught'
common.Alias EchoExitStatus        'common.EchoExitStatus'
common.Alias EnableThrowOnError    'common.EnableThrowOnError'
common.Alias DisableThrowOnError   'common.DisableThrowOnError'
common.Alias GetStatus             'common.GetStatus'
common.Alias SetStatus             'common.SetStatus'
common.Alias GetMessage            'common.GetMessage'
common.Alias MessageCount          'common.MessageCount'
common.Alias CopyMessages          'common.CopyMessages'
common.Alias TryCatchFinally       'common.TryCatchFinally'
common.Alias DefaultErrHandler     'common.DefaultErrHandler'
common.Alias DefaultUnhandled      'common.DefaultUnhandled'
common.Alias CallStack             'common.CallStack'
common.Alias ChangeAlias           'common.ChangeAlias'
common.Alias TryCatchFinallyAlias  'common.Alias'

common.CallStack() {
    local -i "i" "j" "k" "subshell=${2:-0}" "wi" "wl" "wn"
    local "format= %*s  %*s  %-*s  %s\n" "name"
    eval local "lineno=('' ${BASH_LINENO[@]})"
    for (( i=${1:-0},j=wi=wl=wn=0; i<${#FUNCNAME[@]}; ++i,++j )); do  
        name="$(common.GetAlias "$i")"
        let "wi = ${#j} > wi ? wi = ${#j} : wi"
        let "wl = ${#lineno[i]} > wl ? wl = ${#lineno[i]} : wl"
        let "wn = ${#name} > wn ? wn = ${#name} : wn"
    done
    for (( i=${1:-0},j=0; i<${#FUNCNAME[@]}; ++i,++j )); do
        ! let "k = ${#FUNCNAME[@]} - i - 1"
        name="$(common.GetAlias "$i")"
        printf "$format" "$wi" "$j" "$wl" "${lineno[i]}" "$wn" "$name" "${BASH_SOURCE[i]}"
    done
}

common.Echo() {
    [[ $common_options != *d* ]] || echo "$@" >"$common_file"
}

common.DefaultErrHandler() {
    echo "Orginal Status: $common_status"
    echo "Exception Type: ERR"
}

common.Exception() {
    common.TryCatchFinallyVerify || return
    if [[ $# -eq 0 ]]; then
        echo "$(common.GetAlias): At least one parameter is required" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    let "common_status = 10#$1"
    shift
    common_messages=()
    for message in "$@"; do
        common_messages+=("$message")
    done
    if [[ $common_options == *c* ]]; then
        echo "Call Stack:" >"$common_fifo"
        common.CallStack "2" >"$common_fifo"
    fi
}

common.Throw() {
    common.TryCatchFinallyVerify || return
    local "message"
    if ! common.TryCatchFinallyExists; then
        echo "$(common.GetAlias): No Try-Catch-Finally exists" >&2
        return "1"        
    elif [[ $# -eq 0 && common_status -eq 0 ]]; then
        echo "$(common.GetAlias): No previous unhandled exception" >&2 
        return "1"
    elif [[ $# -gt 0 && ( ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ) ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    common.Echo -n "In Throw ?=$common_status "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL #=$#"
    if [[ $common_options == *k* ]]; then
        common.CallStack "2" >"$common_file"
    fi
    if [[ $# -gt 0 ]]; then
        let "common_status = 10#$1"
        shift
        for message in "$@"; do
            echo "$message" >"$common_fifo"
        done
        if [[ $common_options == *c* ]]; then
            echo "Call Stack:" >"$common_fifo"
            common.CallStack "2" >"$common_fifo"
        fi
    elif [[ ${#common_messages[@]} -gt 0 ]]; then
        for message in "${common_messages[@]}"; do
            echo "$message" >"$common_fifo"
        done
    fi
    chmod "0400" "$common_fifo"
    common.Echo "Still in Throw $=$common_status subshell=$BASH_SUBSHELL #=$# -=$-"
    exit "$common_status"
}

common.ErrHandler() {
    common_status=$?
    trap ERR
    common.Echo -n "In ErrHandler ?=$common_status debug=$common_options "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL order=$common_order"
    if [[ -w "$common_fifo" ]]; then
        if [[ $common_options != *e* ]]; then
            common.Echo "ErrHandler is ignoring"
            common_status="0"
            return "$common_status" # value is ignored
        fi
        if [[ $common_options == *k* ]]; then
            common.CallStack "2" >"$common_file"
        fi
        common.Echo "Calling ${common_errHandler:-}"
        eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
        if [[ $common_options == *c* ]]; then
            echo "Call Stack:" >"$common_fifo"
            common.CallStack "2" >"$common_fifo"
        fi
        chmod "0400" "$common_fifo"
    fi
    common.Echo "Still in ErrHandler $=$common_status subshell=$BASH_SUBSHELL -=$-"
    if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
        return "$common_status" # value is ignored   
    else
        exit "$common_status"
    fi
}

common.Token() {
    local "name"
    case $1 in
    b) name="before";;
    t) name="$common_Try";;
    y) name="$common_yrT";;
    c) name="$common_Catch";;
    h) name="$common_hctaC";;
    f) name="$common_yllaniF";;
    l) name="$common_Finally";;
    *) name="unknown";;
    esac
    echo "$name"
}

common.TryCatchFinallyNext() {
    common.ShellInit
    local "previous=$common_order" "errmsg"
    common_order="$2"
    if [[ $previous != $1 ]]; then
        errmsg="${BASH_SOURCE[2]}: line ${BASH_LINENO[1]}: syntax error_near unexpected token \`$(common.Token "$2")'"
        echo "$errmsg" >&2
        [[ /dev/fd/2 -ef $common_file ]] || echo "$errmsg" >"$common_file"
        kill -s INT 0
        return "1"        
    fi
}

common.ShellInit() {
    if [[ common_initSubshell -ne BASH_SUBSHELL ]]; then
        common_initSubshell="$BASH_SUBSHELL"
        common_order="b"
    fi
}

common.Try() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[byhl]" "t" || return 
    common_status="0"
    common_subshell="$common_trySubshell"
    common_trySubshell="$BASH_SUBSHELL"
    common_messages=()
    common.Echo "-------------> Setting try=$common_trySubshell at subshell=$BASH_SUBSHELL"
}

common.yrT() {
    local "status=$?"
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[t]" "y" || return 
    common.Echo -n "Entered yrT ?=$status status=$common_status "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL"
    if [[ common_status -ne 0 ]]; then    

        common.Echo "Build message array. ?=$common_status, subshell=$BASH_SUBSHELL"
        local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
        chmod "0600" "$common_fifo"
        echo "$eof" >"$common_fifo"
        common_messages=()
        while read "message"; do

            common.Echo "----> $message"

            [[ $message != *$eof ]] || break
            common_messages+=("$message")
        done <"$common_fifo"
    fi

    common.Echo "In ytT status=$common_status"
    common_trySubshell="$common_subshell"
}

common.Catch() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[yh]" "c" || return 
    [[ common_status -ne 0 ]] || return "1"
    local "parameter" "pattern" "value"
    local "toggle=true" "compare=p" "options=$-"
    local -i "i=-1" "status=0"
    set -f
    for parameter in "$@"; do
        if "$toggle"; then
            toggle="false"
            if [[ $parameter =~ ^-[notepr]$ ]]; then
                compare="${parameter#-}"
                continue 
            fi
        fi
        toggle="true"
        while "true"; do
            eval local "patterns=($parameter)"
            if [[ ${#patterns[@]} -gt 0 ]]; then
                for pattern in "${patterns[@]}"; do
                    [[ i -lt ${#common_messages[@]} ]] || break
                    if [[ i -lt 0 ]]; then
                        value="$common_status"
                    else
                        value="${common_messages[i]}"
                    fi
                    case $compare in
                    [ne]) [[ ! $value == "$pattern" ]] || break 2;;
                    [op]) [[ ! $value == $pattern ]] || break 2;;
                    [tr]) [[ ! $value =~ $pattern ]] || break 2;;
                    esac
                done
            fi
            if [[ $compare == [not] ]]; then
                let "++i,1"
                continue 2
            else
                status="1"
                break 2
            fi
        done
        if [[ $compare == [not] ]]; then
            status="1"
            break
        else
            let "++i,1"
        fi
    done
    [[ $options == *f* ]] || set +f
    return "$status"
} 

common.hctaC() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[c]" "h" || return 
    [[ $# -ne 1 || $1 != -r ]] || common_status="0"
}

common.Finally() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[ych]" "f" || return 
}

common.yllaniF() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[f]" "l" || return 
    [[ common_status -eq 0 ]] || common.Throw
}

common.Caught() {
    common.TryCatchFinallyVerify || return
    [[ common_status -eq 0 ]] || return 1
}

common.EchoExitStatus() {
    return "${1:-$?}"
}

common.EnableThrowOnError() {
    common.TryCatchFinallyVerify || return
    [[ $common_options == *e* ]] || common_options+="e"
}

common.DisableThrowOnError() {
    common.TryCatchFinallyVerify || return
    common_options="${common_options/e}"
}

common.GetStatus() {
    common.TryCatchFinallyVerify || return
    echo "$common_status"
}

common.SetStatus() {
    common.TryCatchFinallyVerify || return
    if [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    let "common_status = 10#$1"
}

common.GetMessage() {
    common.TryCatchFinallyVerify || return
    local "upper=${#common_messages[@]}"
    if [[ upper -eq 0 ]]; then
        echo "$(common.GetAlias): $1: There are no messages" >&2
        return "1"
    elif [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -ge upper ]]; then
        echo "$(common.GetAlias): $1: First parameter was an invalid index" >&2
        return "1"
    fi
    echo "${common_messages[$1]}"
}

common.MessageCount() {
    common.TryCatchFinallyVerify || return
    echo "${#common_messages[@]}"
}

common.CopyMessages() {
    common.TryCatchFinallyVerify || return
    if [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#common_messages} -gt 0 ]]; then
        eval "$1=(\"\${common_messages[@]}\")"
    else
        eval "$1=()"
    fi
}

common.TryCatchFinallyExists() {
    [[ ${common_fifo:-u} != u ]]
}

common.TryCatchFinallyVerify() {
    local "name"
    if ! common.TryCatchFinallyExists; then
        echo "$(common.GetAlias "1"): No Try-Catch-Finally exists" >&2
        return "2"        
    fi
}

common.GetOptions() {
    local "opt"
    local "name=$(common.GetAlias "1")"
    if common.TryCatchFinallyExists; then
        echo "$name: A Try-Catch-Finally already exists" >&2
        return "1"        
    fi
    let "OPTIND = 1"
    let "OPTERR = 0"
    while getopts ":cdeh:ko:u:v:" opt "$@"; do
        case $opt in
        c)  [[ $common_options == *c* ]] || common_options+="c";;
        d)  [[ $common_options == *d* ]] || common_options+="d";;
        e)  [[ $common_options == *e* ]] || common_options+="e";;
        h)  common_errHandler="$OPTARG";;
        k)  [[ $common_options == *k* ]] || common_options+="k";;
        o)  common_file="$OPTARG";;
        u)  common_unhandled="$OPTARG";;
        v)  common_command="$OPTARG";;
        \?) #echo "Invalid option: -$OPTARG" >&2
            echo "$name: Illegal option: $OPTARG" >&2
            return "1";;
        :)  echo "$name: Option requires an argument: $OPTARG" >&2
            return "1";;
        *)  echo "$name: An error occurred while parsing options." >&2
            return "1";;
        esac
    done

    shift "$((OPTIND - 1))"
    if [[ $# -lt 1 ]]; then
        echo "$name: The fifo_file parameter is missing" >&2
        return "1"
    fi
    common_fifo="$1"
    if [[ ! -p $common_fifo ]]; then
        echo "$name: $1: The fifo_file is not an open FIFO" >&2
        return "1"  
    fi

    shift
    if [[ $# -lt 1 ]]; then
        echo "$name: The function parameter is missing" >&2
        return "1"
    fi
    common_function="$1"
    if ! chmod "0600" "$common_fifo"; then
        echo "$name: $common_fifo: Can not change file mode to 0600" >&2
        return "1"
    fi

    local "message=" "eof=TRY_CATCH_FINALLY_END_OF_FILE_$RANDOM"
    { echo "$eof" >"$common_fifo"; } 2>"/dev/null"
    if [[ $? -ne 0 ]]; then
        echo "$name: $common_fifo: Can not write" >&2
        return "1"
    fi   
    { while [[ $message != *$eof ]]; do
        read "message"
    done <"$common_fifo"; } 2>"/dev/null"
    if [[ $? -ne 0 ]]; then
        echo "$name: $common_fifo: Can not read" >&2
        return "1"
    fi   

    return "0"
}

common.DefaultUnhandled() {
    local -i "i"
    echo "-------------------------------------------------"
    echo "$(common.GetAlias "common.TryCatchFinally"): Unhandeled exception occurred"
    echo "Status: $(GetStatus)"
    echo "Messages:"
    for ((i=0; i<$(MessageCount); i++)); do
        echo "$(GetMessage "$i")"
    done
    echo "-------------------------------------------------"
}

common.TryCatchFinally() {
    local "common_file=/dev/fd/2"
    local "common_errHandler=common.DefaultErrHandler"
    local "common_unhandled=common.DefaultUnhandled"
    local "common_options="
    local "common_fifo="
    local "common_function="
    local "common_flags=$-"
    local "common_trySubshell=-1"
    local "common_initSubshell=-1"
    local "common_subshell"
    local "common_status=0"
    local "common_order=b"
    local "common_command="
    local "common_messages=()"
    local "common_handler=$(trap -p ERR)"
    [[ -n $common_handler ]] || common_handler="trap ERR"

    common.GetOptions "$@" || return "$?"
    shift "$((OPTIND + 1))"

    [[ -z $common_command ]] || common_command+="=$"
    common_command+='("$common_function" "$@")'

    set -E
    set +e
    trap "common.ErrHandler" ERR
    if true; then
        common.Try 
        eval "$common_command"
        common.EchoExitStatus
        common.yrT
    fi
    while common.Catch; do
        "$common_unhandled" >&2
        break
        common.hctaC -r
    done
    common.hctaC
    [[ $common_flags == *E* ]] || set +E
    [[ $common_flags != *e* ]] || set -e
    [[ $common_flags != *f* || $- == *f* ]] || set -f
    [[ $common_flags == *f* || $- != *f* ]] || set +f
    eval "$common_handler"
    return "$((common_status?2:0))"
}

Android findViewById() in Custom View

Change your Method as following and check it will work

private void initViews() {
    inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.id_number_edit_text_custom, this, true);
    View view = (View) inflater.inflate(R.layout.main, null);
    editText = (EditText) view.findViewById(R.id.id_number_custom);
    loadButton = (ImageButton) view.findViewById(R.id.load_data_button);
    loadButton.setVisibility(RelativeLayout.INVISIBLE);
    loadData();
} 

Getting json body in aws Lambda via API gateway

You may have forgotten to define the Content-Type header. For example:

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ items }),
  }

An error when I add a variable to a string

You're missing your database name:

$sql = "SELECT ID, ListStID, ListEmail, Title FROM ".$entry_database." WHERE ID = ". $ReqBookID .";

And make sure that $entry_database isn't null or empty:

var_dump($entry_database);

Also notice that you don't need to have $ReqBookID in '' as if it's an Int.

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient is deprecated in sdk 23.

You have to move on URLConnection or down sdk to 22

Still you need HttpClient with update gradle sdk 23

You have to add the dependencies of HttpClient in app/gradle as

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.0.1'

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    ...
}

Using CSS :before and :after pseudo-elements with inline CSS?

Yes it's possible, just add inline styles for the element which you adding after or before, Example

 <style>
     .horizontalProgress:after { width: 45%; }
 </style><!-- Change Value from Here -->

 <div class="horizontalProgress"></div>

UIScrollView Scrollable Content Size Ambiguity

I finally figured this out, I hope this is easier to understand.

You can often bypass that warning by adding a base UIView to the scrollview as a "content view", as they mentioned and make it the same size as your scroll view and, on this content view, set these 6 parameters.

enter image description here

As you can see, you need 6 total parameters! Which.. under normal circumstances, you're duplicating 2 constraints but this is the way to avoid this storyboard error.

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Rails how to run rake task

Have you tried rake reklamer:iqmedier ?

My custom rake tasks are in the lib directory, not in lib/tasks. Not sure if that matters.

What does "atomic" mean in programming?

If you have several threads executing the methods m1 and m2 in the code below:

class SomeClass {
    private int i = 0;

    public void m1() { i = 5; }
    public int m2() { return i; }
}

you have the guarantee that any thread calling m2 will either read 0 or 5.

On the other hand, with this code (where i is a long):

class SomeClass {
    private long i = 0;

    public void m1() { i = 1234567890L; }
    public long m2() { return i; }
}

a thread calling m2 could read 0, 1234567890L, or some other random value because the statement i = 1234567890L is not guaranteed to be atomic for a long (a JVM could write the first 32 bits and the last 32 bits in two operations and a thread might observe i in between).

pandas dataframe convert column type to string or categorical

You need astype:

df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)

For converting to categorical:

df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')

Another solution is Categorical:

df['zipcode'] = pd.Categorical(df.zipcode)

Sample with data:

import pandas as pd

df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot  zipcode
722         3.25         4     2.0         4670     51836    98005
2680        0.75         2     1.0         1440      3700    98107
14554       2.50         4     2.0         3180      9603    98155
17384       1.50         2     3.0         1430      1650    98125
18754       1.00         2     1.0         1130      2640    98109

print (df.dtypes)
bathrooms      float64
bedrooms         int64
floors         float64
sqft_living      int64
sqft_lot         int64
zipcode          int64
dtype: object

df['zipcode'] = df.zipcode.astype('category')

print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot zipcode
722         3.25         4     2.0         4670     51836   98005
2680        0.75         2     1.0         1440      3700   98107
14554       2.50         4     2.0         3180      9603   98155
17384       1.50         2     3.0         1430      1650   98125
18754       1.00         2     1.0         1130      2640   98109

print (df.dtypes)
bathrooms       float64
bedrooms          int64
floors          float64
sqft_living       int64
sqft_lot          int64
zipcode        category
dtype: object

Maven2: Missing artifact but jars are in place

I have tried many tips but the only one that works is this one. Update the Maven configuration. Right-click on pom.xml, Run as -> Maven build (the 2nd one). Enter "clean package" in the Goals fields. Check the Skip Tests box. Then Run, it will properly download all the jars and the problem is fixed.

.gitignore is ignored by Git

I've created .gitignore using echo "..." > .gitignore in PowerShell in Windows, because it does not let me to create it in Windows Explorer.

The problem in my case was the encoding of the created file, and the problem was solved after I changed it to ANSI.

FtpWebRequest Download File

    private static DataTable ReadFTP_CSV()
    {
        String ftpserver = "ftp://servername/ImportData/xxxx.csv";
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();

        // use the stream to read file from FTP 
        StreamReader sr = new StreamReader(responseStream);
        DataTable dt_csvFile = new DataTable();

        #region Code
        //Add Code Here To Loop txt or CSV file
        #endregion

        return dt_csvFile;

    }

I hope it can help you.

How to figure out the SMTP server host?

generally smtp servers name are smtp.yourdomain.com or mail.yourdomain.com open command prompt try to run following two commands

  1. >ping smtp.yourdomain.com
  2. >ping mail.yourdomain.com

you will most probably get response from any one from the above two commands.and that will be your smtp server

If this doesn't work open your cpanel --> go to your mailing accounts -- > click on configure mail account -- > there somewhere in the page you will get the information about your smtp server

it will be written like this way may be :

Incoming Server:    mail.yourdomain.com
IMAP Port: ---
POP3 Port: ---
Outgoing Server:    mail.yourdomain.com
SMTP Port: ---

Compare given date with today

$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');

var_dump(strtotime($today) > strtotime($expiry)); //false or true

Where can I get a virtual machine online?

koding.com has a free VM running Ubuntu. The specs are pretty good, 1 gig memory for example. They have a terminal online you can access through their website, or use SSH. The VM will go to sleep approximately 20 minutes after you log out. The reason is to discourage users from running live production code on the VM. The VM resides behind a proxy. Running web servers that only speak HTTP (port 80) should work just fine, but I think you'll get into a lot of trouble whenever you want to work directly with other ports. Many mind-like alternatives offer similar setups. Good luck!

I had the same idea as you but given all restrictions everybody keep imposing everywhere I feel that I must go out and pay for a VPS.

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

What is the use of hashCode in Java?

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

What is the difference between & and && in Java?

Besides && and || being short circuiting, also consider operator precedence when mixing the two forms. I think it will not be immediately apparent to everybody that result1 and result2 contain different values.

boolean a = true;
boolean b = false;
boolean c = false;

boolean result1 = a || b && c; //is true;  evaluated as a || (b && c)
boolean result2 = a  | b && c; //is false; evaluated as (a | b) && c

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

Most likely, you ran out of memory, so the Kernel killed your process.

Have you heard about OOM Killer?

Here's a log from a script that I developed for processing a huge set of data from CSV files:

Mar 12 18:20:38 server.com kernel: [63802.396693] Out of memory: Kill process 12216 (python3) score 915 or sacrifice child
Mar 12 18:20:38 server.com kernel: [63802.402542] Killed process 12216 (python3) total-vm:9695784kB, anon-rss:7623168kB, file-rss:4kB, shmem-rss:0kB
Mar 12 18:20:38 server.com kernel: [63803.002121] oom_reaper: reaped process 12216 (python3), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

It was taken from /var/log/syslog.

Basically:

PID 12216 elected as a victim (due to its use of +9Gb of total-vm), so oom_killer reaped it.

Here's a article about OOM behavior.

How to get the server path to the web directory in Symfony2 from inside the controller?

$host = $request->server->get('HTTP_HOST');
$base = (!empty($request->server->get('BASE'))) ? $request->server->get('BASE') : '';
$getBaseUrl = $host.$base;

java.net.SocketException: Connection reset

Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can't process, and there can be various reasons for that.

The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn't listening.

In other cases, an intervening firewall or even the remote host itself might "forget" about your TCP connection. This could happen if you don't send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.


Update in response to additional information:

Take a close look at your handling of the SocketTimeoutException. This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you'll be in a connection reset condition. setSoTimeout() is meant to give you a clean way to break out of a read() operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

To expand on others' answers, here is a compact solution that doesn't expose/add any new variables. It doesn't cover all bases, but it should suit most people who just want a single page app to remain functional (despite no data persistence after reload).

(function(){
    try {
        localStorage.setItem('_storage_test', 'test');
        localStorage.removeItem('_storage_test');
    } catch (exc){
        var tmp_storage = {};
        var p = '__unique__';  // Prefix all keys to avoid matching built-ins
        Storage.prototype.setItem = function(k, v){
            tmp_storage[p + k] = v;
        };
        Storage.prototype.getItem = function(k){
            return tmp_storage[p + k] === undefined ? null : tmp_storage[p + k];
        };
        Storage.prototype.removeItem = function(k){
            delete tmp_storage[p + k];
        };
        Storage.prototype.clear = function(){
            tmp_storage = {};
        };
    }
})();

How to remove numbers from a string?

A secondary option would be to match and return non-digits with some expression similar to,

/\D+/g

which would likely work for that specific string in the question (1 ding ?).

Demo

Test

_x000D_
_x000D_
function non_digit_string(str) {_x000D_
 const regex = /\D+/g;_x000D_
 let m;_x000D_
_x000D_
 non_digit_arr = [];_x000D_
 while ((m = regex.exec(str)) !== null) {_x000D_
  // This is necessary to avoid infinite loops with zero-width matches_x000D_
  if (m.index === regex.lastIndex) {_x000D_
   regex.lastIndex++;_x000D_
  }_x000D_
_x000D_
_x000D_
  m.forEach((match, groupIndex) => {_x000D_
   if (match.trim() != '') {_x000D_
    non_digit_arr.push(match.trim());_x000D_
   }_x000D_
  });_x000D_
 }_x000D_
 return non_digit_arr;_x000D_
}_x000D_
_x000D_
const str = `1 ding ? 124_x000D_
12 ding ?_x000D_
123 ding ? 123`;_x000D_
console.log(non_digit_string(str));
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

What does `ValueError: cannot reindex from a duplicate axis` mean?

This can also be a cause for this[:) I solved my problem like this]

It may happen even if you are trying to insert a dataframe type column inside dataframe

you can try this

df['my_new']=pd.Series(my_new.values)

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

Keep it simple and clean

var d = new Date();
var n = d.toLocaleString();

https://jsfiddle.net/rinu6200/3dkdxaad/#base

Regular expression to extract text between square brackets

if you want fillter only small alphabet letter between square bracket a-z

(\[[a-z]*\])

if you want small and caps letter a-zA-Z

(\[[a-zA-Z]*\]) 

if you want small caps and number letter a-zA-Z0-9

(\[[a-zA-Z0-9]*\]) 

if you want everything between square bracket

if you want text , number and symbols

(\[.*\])

Angular2 Routing with Hashtag to page anchor

A simple solution that works for pages without any query parameters, is browser back / forward, router and deep-linking compliant.

<a (click)="jumpToId('anchor1')">Go To Anchor 1</a>


ngOnInit() {

    // If your page is dynamic
    this.yourService.getWhatever()
        .then(
            data => {
            this.componentData = data;
            setTimeout(() => this.jumpToId( window.location.hash.substr(1) ), 100);
        }
    );

    // If your page is static
    // this.jumpToId( window.location.hash.substr(1) )
}

jumpToId( fragment ) {

    // Use the browser to navigate
    window.location.hash = fragment;

    // But also scroll when routing / deep-linking to dynamic page
    // or re-clicking same anchor
    if (fragment) {
        const element = document.querySelector('#' + fragment);
        if (element) element.scrollIntoView();
    }
}

The timeout is simply to allow the page to load any dynamic data "protected" by an *ngIf. This can also be used to scroll to the top of the page when changing route - just provide a default top anchor tag.

What does template <unsigned int N> mean?

A template class is like a macro, only a whole lot less evil.

Think of a template as a macro. The parameters to the template get substituted into a class (or function) definition, when you define a class (or function) using a template.

The difference is that the parameters have "types" and values passed are checked during compilation, like parameters to functions. The types valid are your regular C++ types, like int and char. When you instantiate a template class, you pass a value of the type you specified, and in a new copy of the template class definition this value gets substituted in wherever the parameter name was in the original definition. Just like a macro.

You can also use the "class" or "typename" types for parameters (they're really the same). With a parameter of one of these types, you may pass a type name instead of a value. Just like before, everywhere the parameter name was in the template class definition, as soon as you create a new instance, becomes whatever type you pass. This is the most common use for a template class; Everybody that knows anything about C++ templates knows how to do this.

Consider this template class example code:

#include <cstdio>
template <int I>
class foo
{
  void print()
  {
    printf("%i", I);
  }
};

int main()
{
  foo<26> f;
  f.print();
  return 0;
}

It's functionally the same as this macro-using code:

#include <cstdio>
#define MAKE_A_FOO(I) class foo_##I \
{ \
  void print() \
  { \
    printf("%i", I); \
  } \
};

MAKE_A_FOO(26)

int main()
{
  foo_26 f;
  f.print();
  return 0;
}

Of course, the template version is a billion times safer and more flexible.

The simplest way to comma-delimit a list?

(Copy paste of my own answer from here.) Many of the solutions described here are a bit over the top, IMHO, especially those that rely on external libraries. There is a nice clean, clear idiom for achieving a comma separated list that I have always used. It relies on the conditional (?) operator:

Edit: Original solution correct, but non-optimal according to comments. Trying a second time:

int[] array = {1, 2, 3};
StringBuilder builder = new StringBuilder();
for (int i = 0 ;  i < array.length; i++)
       builder.append(i == 0 ? "" : ",").append(array[i]);

There you go, in 4 lines of code including the declaration of the array and the StringBuilder.

2nd Edit: If you are dealing with an Iterator:

    List<Integer> list = Arrays.asList(1, 2, 3);
    StringBuilder builder = new StringBuilder();
    for (Iterator it = list.iterator(); it.hasNext();)
        builder.append(it.next()).append(it.hasNext() ? "," : "");

What does enumerate() mean?

The enumerate() function adds a counter to an iterable.

So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.

Demo:

>>> elements = ('foo', 'bar', 'baz')
>>> for elem in elements:
...     print elem
... 
foo
bar
baz
>>> for count, elem in enumerate(elements):
...     print count, elem
... 
0 foo
1 bar
2 baz

By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:

>>> for count, elem in enumerate(elements, 42):
...     print count, elem
... 
42 foo
43 bar
44 baz

If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:

from itertools import count

def enumerate(it, start=0):
    # return an iterator that adds a counter to each element of it
    return zip(count(start), it)

and

def enumerate(it, start=0):
    count = start
    for elem in it:
        yield (count, elem)
        count += 1

The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).

JavaScript split String with white space

str.split(' ').join('§ §').split('§');

What exactly does an #if 0 ..... #endif block do?

Not quite

int main(void)
{
   #if 0
     the apostrophe ' causes a warning
   #endif
   return 0;
}

It shows "t.c:4:19: warning: missing terminating ' character" with gcc 4.2.4

Powershell Get-ChildItem most recent file in directory

Yes I think this would be quicker.

Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1 

What is the best Java library to use for HTTP POST, GET etc.?

I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient

I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs". http://htmlunit.sourceforge.net/

Convert command line arguments into an array in Bash

Here is another usage :

#!/bin/bash
array=( "$@" )
arraylength=${#array[@]}
for (( i=0; i<${arraylength}; i++ ));
do
   echo "${array[$i]}"
done

What is perm space?

Simple (and oversimplified) answer: it's where the jvm stores its own bookkeeping data, as opposed to your data.

String to Binary in C#

The following will give you the hex encoding for the low byte of each character, which looks like what you're asking for:

StringBuilder sb = new StringBuilder();
foreach (char c in asciiString)
{
    uint i = (uint)c;
    sb.AppendFormat("{0:X2}", (i & 0xff));
}
return sb.ToString();

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I had this issue with a facebook application that I was developing for a fan page tab. If anyone faces this issue with a facebook application then

1-goto https://developers.facebook.com

2-select the application that you are developing

3-make sure that all the link to your application has tailing slash /

my issue was in the https://developers.facebook.com->Apps->MYAPPNAME->settings->Page Tab->Secure Page Tab URL, Page Tab Edit URL, Page Tab URL hope this will help

Developing C# on Linux

You can also install it using conda (tested on Ubuntu):

conda create --name csharp
conda activate csharp
conda install -c conda-forge mono

Display a float with two decimal places in Python

Using Python 3 syntax:

print('%.2f' % number)

Spring Boot not serving static content

Requests to /** are evaluated to static locations configured in resourceProperties.

adding the following on application.properties, might be the only thing you need to do...

spring.resources.static-locations=classpath:/myresources/

this will overwrite default static locations, wich is:

ResourceProperties.CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
        "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

You might not want to do that and just make sure your resources end up in one of those default folders.

Performing a request: If I would have example.html stored on /public/example.html Then I can acces it like this:

<host>/<context-path?if you have one>/example.html

If I would want another uri like <host>/<context-path>/magico/* for files in classpath:/magicofiles/* you need a bit more config

@Configuration
class MyConfigClass implements WebMvcConfigurer

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/magico/**").addResourceLocations("/magicofiles/");
}

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

Plotting a 3d cube, a sphere and a vector in Matplotlib

For drawing just the arrow, there is an easier method:-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

quiver(X, Y, Z, U, V, W, **kwargs)

Arguments:

X, Y, Z: The x, y and z coordinates of the arrow locations

U, V, W: The x, y and z components of the arrow vectors

The arguments could be array-like or scalars.

Keyword arguments:

length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes

arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3

pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’

normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.