Programs & Examples On #Iphone sdk 3.1

Refers to the iPhone software development kit, version 3.1.

Trigger a Travis-CI rebuild without pushing a commit?

  • If you have write access to the repo: On the build's detail screen, there is a button ? Restart Build. Also under "More Options" there is a trigger build menu item.

    Note: Browser extensions like Ghostery may prevent the restart button from being displayed. Try disabling the extension or white-listing Travis CI.

    Note2: If .travis.yml configuration has changed in the upstream, clicking rebuild button will run travis with old configuration. To apply upstream changes for travis configuration one has to add commit to PR or to close / reopen it.

  • If you've sent a pull request: You can close the PR then open it again. This will trigger a new build.

Restart Build:

Restart Build Screen Shot

Trigger Build:

Trigger Build Screen Shot

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

You don't need to configure anything. Just make sure that the requests map to your PHP file and use requests with path info. For example, if you have in the root a file named handler.php with this content:

<?php

var_dump($_SERVER['REQUEST_METHOD']);
var_dump($_SERVER['REQUEST_URI']);
var_dump($_SERVER['PATH_INFO']);

if (($stream = fopen('php://input', "r")) !== FALSE)
    var_dump(stream_get_contents($stream));

The following HTTP request would work:

Established connection with 127.0.0.1 on port 81
PUT /handler.php/bla/foo HTTP/1.1
Host: localhost:81
Content-length: 5
 
boo
HTTP/1.1 200 OK
Date: Sat, 29 May 2010 16:00:20 GMT
Server: Apache/2.2.13 (Win32) PHP/5.3.0
X-Powered-By: PHP/5.3.0
Content-Length: 89
Content-Type: text/html
 
string(3) "PUT"
string(20) "/handler.php/bla/foo"
string(8) "/bla/foo"
string(5) "boo
"
Connection closed remotely.

You can hide the "php" extension with MultiViews or you can make URLs completely logical with mod_rewrite.

See also the documentation for the AcceptPathInfo directive and this question on how to make PHP not parse POST data when enctype is multipart/form-data.

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

What is the default maximum heap size for Sun's JVM from Java SE 6?

With JDK, You can also use jinfo to connect to the JVM for the <PROCESS_ID> in question and get the value for MaxHeapSize:

jinfo -flag MaxHeapSize <PROCESS_ID>

How can I get javascript to read from a .json file?

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});

Detecting an "invalid date" Date instance in JavaScript

Inspired by Borgar's approach I have made sure that the code not only validates the date, but actually makes sure the date is a real date, meaning that dates like 31/09/2011 and 29/02/2011 are not allowed.

function(dateStr) {
    s = dateStr.split('/');
    d = new Date(+s[2], s[1]-1, +s[0]);
    if (Object.prototype.toString.call(d) === "[object Date]") {
        if (!isNaN(d.getTime()) && d.getDate() == s[0] && 
            d.getMonth() == (s[1] - 1)) {
            return true;
        }
    }
    return "Invalid date!";
}

convert array into DataFrame in Python

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

Delete directory with files in it?

This one works for me:

function removeDirectory($path) {
    $files = glob($path . '/*');
    foreach ($files as $file) {
        is_dir($file) ? removeDirectory($file) : unlink($file);
    }
    rmdir($path);
    return;
}

Hot deploy on JBoss - how do I make JBoss "see" the change?

I've been developing a project with Eclipse and Wildfly and the exploded EAR file was getting big due to deploying of all the 3rd party libraries I needed in the application. I was pointing the deployment to my Maven repository which I guess was recopying the jars each time. So redeploying the application when ever I changed Java code in the service layer was turning into a nightmare.

Then having turned to Hotswap agent this helped a lot as far as seeing changes to EJB code without redeploying the application.

However I have recently upgraded to Wildfly 10, Java 8 and JBoss Developer Studio 10 and during that process I took the time to move all my 3rd party application jars e.g. primefaces into Wildfly modules and I removed my Maven repo from my deployment config. Now redeploying the entire application which is a pretty big one via Eclipse takes just a few seconds and it is much much faster than before. I don't even feel the need to install Hotswap and don't want to risk it anyway right now.

So if you are building under Eclipse with Wildfly then keep you application clear of 3rd party libs using Wildfly Modules and you'll be much better off.

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

How do you read a file into a list in Python?

The pythonic way to read a file and put every lines in a list:

from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
    lines = f.readlines()

Then, assuming that each lines contains a number,

numbers =[int(e.strip()) for e in lines]

How to download a file over HTTP?

urlretrieve and requests.get are simple, however the reality not. I have fetched data for couple sites, including text and images, the above two probably solve most of the tasks. but for a more universal solution I suggest the use of urlopen. As it is included in Python 3 standard library, your code could run on any machine that run Python 3 without pre-installing site-package

import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)

#remember to open file in bytes mode
with open(filename, 'wb') as f:
    while True:
        buffer = url_connect.read(buffer_size)
        if not buffer: break

        #an integer value of size of written data
        data_wrote = f.write(buffer)

#you could probably use with-open-as manner
url_connect.close()

This answer provides a solution to HTTP 403 Forbidden when downloading file over http using Python. I have tried only requests and urllib modules, the other module may provide something better, but this is the one I used to solve most of the problems.

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

PHP - Redirect and send data via POST

An old post but here is how I handled it. Using newms87's method:

if($action == "redemption")
{
    if($redemptionId != "")
    {
        $results = json_decode($rewards->redeemPoints($redemptionId));

        if($results->success == true)
        {
            $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete';
            // put results in session and redirect back to same page passing an action paraameter
            $_SESSION['post_data'] = json_encode($results);
            header("Location:" . $redirectLocation);
            exit();
        }
    }
}
elseif($action == "redemptionComplete")
{
    // if data is in session pull it and unset it.
    if(isset($_SESSION['post_data']))
    {
        $results = json_decode($_SESSION['post_data']);
        unset($_SESSION['post_data']);
    }
    // if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page.
    else
    {
        $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml';
        header("Location:" . $redirectLocation);
    }
}

Can local storage ever be considered secure?

WebCrypto

The concerns with cryptography in client-side (browser) javascript are detailed below. All but one of these concerns does not apply to the WebCrypto API, which is now reasonably well supported.

For an offline app, you must still design and implement a secure keystore.

Aside: If you are using Node.js, use the builtin crypto API.

Native-Javascript Cryptography (pre-WebCrypto)

I presume the primary concern is someone with physical access to the computer reading the localStorage for your site, and you want cryptography to help prevent that access.

If someone has physical access you are also open to attacks other and worse than reading. These include (but are not limited to): keyloggers, offline script modification, local script injection, browser cache poisoning, and DNS redirects. Those attacks only work if the user uses the machine after it has been compromised. Nevertheless, physical access in such a scenario means you have bigger problems.

So keep in mind that the limited scenario where local crypto is valuable would be if the machine is stolen.

There are libraries that do implement the desired functionality, e.g. Stanford Javascript Crypto Library. There are inherent weaknesses, though (as referred to in the link from @ircmaxell's answer):

  1. Lack of entropy / random number generation;
  2. Lack of a secure keystore i.e. the private key must be password-protected if stored locally, or stored on the server (which bars offline access);
  3. Lack of secure-erase;
  4. Lack of timing characteristics.

Each of these weaknesses corresponds with a category of cryptographic compromise. In other words, while you may have "crypto" by name, it will be well below the rigour one aspires to in practice.

All that being said, the actuarial assessment is not as trivial as "Javascript crypto is weak, do not use it". This is not an endorsement, strictly a caveat and it requires you to completely understand the exposure of the above weaknesses, the frequency and cost of the vectors you face, and your capacity for mitigation or insurance in the event of failure: Javascript crypto, in spite of its weaknesses, may reduce your exposure but only against thieves with limited technical capacity. However, you should presume Javascript crypto has no value against a determined and capable attacker who is targeting that information. Some would consider it misleading to call the data "encrypted" when so many weaknesses are known to be inherent to the implementation. In other words, you can marginally decrease your technical exposure but you increase your financial exposure from disclosure. Each situation is different, of course - and the analysis of reducing the technical exposure to financial exposure is non-trivial. Here is an illustrative analogy: Some banks require weak passwords, in spite of the inherent risk, because their exposure to losses from weak passwords is less than the end-user costs of supporting strong passwords.

If you read the last paragraph and thought "Some guy on the Internet named Brian says I can use Javascript crypto", do not use Javascript crypto.

For the use case described in the question it would seem to make more sense for users to encrypt their local partition or home directory and use a strong password. That type of security is generally well tested, widely trusted, and commonly available.

how to run a winform from console application?

You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

Java: Get month Integer from Date

Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1

The returned value starts from 0, so you should add one to the result.

Is it possible to log all HTTP request headers with Apache?

Here is a list of all http-headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

And here is a list of all apache-logformats: http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#formats

As you did write correctly, the code for logging a specific header is %{foobar}i where foobar is the name of the header. So, the only solution is to create a specific format string. When you expect a non-standard header like x-my-nonstandard-header, then use %{x-my-nonstandard-header}i. If your server is going to ignore this non-standard-header, why should you want to write it to your logfile? An unknown header has absolutely no effect to your system.

How to get a unix script to run every 15 seconds?

I wrote a scheduler faster than cron. I have also implemented an overlapping guard. You can configure the scheduler to not start new process if previous one is still running. Take a look at https://github.com/sioux1977/scheduler/wiki

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate

Android Studio Gradle Already disposed Module

For Solve this issue take it this simple steps.

  1. Find the .idea folder in your Android studio under the Folder Project.
  2. In .idea --> Find this one. .idea/.modules
  3. Simple Delete that .modules folder and restart Your studio.
  4. when it reopens gradle sync Automatically and also recreate .modules folder and files.
  5. Error has gone !

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

How to remove decimal values from a value of type 'double' in Java

Use Math.Round(double);

I have used it myself. It actually rounds off the decimal places.

d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20 

d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19 

Hope it Helps :-)

List of enum values in java

You can simply write

new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

How to append one DataTable to another DataTable

Consider a solution that will neatly handle arbitrarily many tables.

//ASSUMPTION: All tables must have the same columns
var tables = new List<DataTable>();
tables.Add(oneTableToRuleThemAll);
tables.Add(oneTableToFindThem);
tables.Add(oneTableToBringThemAll);
tables.Add(andInTheDarknessBindThem);
//Or in the real world, you might be getting a collection of tables from some abstracted data source.

//behold, a table too great and terrible to imagine
var theOneTable = tables.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();

Encapsulated into a helper for future reuse:

public static DataTable CombineDataTables(params DataTable[] args)
{
    return args.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
}

Just have a few tables declared in code?

var combined = CombineDataTables(dt1,dt2,dt3);

Want to combine into one of the existing tables instead of creating a new one?

dt1 = CombineDataTables(dt1,dt2,dt3);

Already have a collection of tables, instead of declared one by one?

//Pretend variable tables already exists
var tables = new[] { dt1, dt2, dt3 };
var combined = CombineDataTables(tables);

Redirect all to index.php using htaccess

just in case you were still wondering how to redirect all request either if the directory exists (for core framework folders and files) to the framework index handler, after some error/success attempts just noticed I just needed to change the RewriteCond in the .htaccess file

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

the above condition states "not found files" and "not found directories", ok, what if just remove "not found" (!-d) line, and ended with something like the below:

RewriteEngine on
RewriteBase /framework/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /framework/index.php [L,QSA]

It worked for me like a charm

SQL MAX of multiple columns?

Please try using UNPIVOT:

SELECT MAX(MaxDt) MaxDt
   FROM tbl 
UNPIVOT
   (MaxDt FOR E IN 
      (Date1, Date2, Date3)
)AS unpvt;

How do I make a list of data frames?

Very simple ! Here is my suggestion :

If you want to select dataframes in your workspace, try this :

Filter(function(x) is.data.frame(get(x)) , ls())

or

ls()[sapply(ls(), function(x) is.data.frame(get(x)))]

all these will give the same result.

You can change is.data.frame to check other types of variables like is.function

GLYPHICONS - bootstrap icon font hex value

We can find these by looking at Bootstrap's stylesheet, Bootstrap.css. Each \{number} represents a hexadecimal value, so \2a is equal to 0x2a or &#x2a;.

As for the font, that can be downloaded from http://glyphicons.com.

.glyphicon-asterisk:before {
  content: "\2a";
}

.glyphicon-plus:before {
  content: "\2b";
}

.glyphicon-euro:before {
  content: "\20ac";
}

.glyphicon-minus:before {
  content: "\2212";
}

.glyphicon-cloud:before {
  content: "\2601";
}

.glyphicon-envelope:before {
  content: "\2709";
}

.glyphicon-pencil:before {
  content: "\270f";
}

.glyphicon-glass:before {
  content: "\e001";
}

.glyphicon-music:before {
  content: "\e002";
}

.glyphicon-search:before {
  content: "\e003";
}

.glyphicon-heart:before {
  content: "\e005";
}

.glyphicon-star:before {
  content: "\e006";
}

.glyphicon-star-empty:before {
  content: "\e007";
}

.glyphicon-user:before {
  content: "\e008";
}

.glyphicon-film:before {
  content: "\e009";
}

.glyphicon-th-large:before {
  content: "\e010";
}

.glyphicon-th:before {
  content: "\e011";
}

.glyphicon-th-list:before {
  content: "\e012";
}

.glyphicon-ok:before {
  content: "\e013";
}

.glyphicon-remove:before {
  content: "\e014";
}

.glyphicon-zoom-in:before {
  content: "\e015";
}

.glyphicon-zoom-out:before {
  content: "\e016";
}

.glyphicon-off:before {
  content: "\e017";
}

.glyphicon-signal:before {
  content: "\e018";
}

.glyphicon-cog:before {
  content: "\e019";
}

.glyphicon-trash:before {
  content: "\e020";
}

.glyphicon-home:before {
  content: "\e021";
}

.glyphicon-file:before {
  content: "\e022";
}

.glyphicon-time:before {
  content: "\e023";
}

.glyphicon-road:before {
  content: "\e024";
}

.glyphicon-download-alt:before {
  content: "\e025";
}

.glyphicon-download:before {
  content: "\e026";
}

.glyphicon-upload:before {
  content: "\e027";
}

.glyphicon-inbox:before {
  content: "\e028";
}

.glyphicon-play-circle:before {
  content: "\e029";
}

.glyphicon-repeat:before {
  content: "\e030";
}

.glyphicon-refresh:before {
  content: "\e031";
}

.glyphicon-list-alt:before {
  content: "\e032";
}

.glyphicon-lock:before {
  content: "\e033";
}

.glyphicon-flag:before {
  content: "\e034";
}

.glyphicon-headphones:before {
  content: "\e035";
}

.glyphicon-volume-off:before {
  content: "\e036";
}

.glyphicon-volume-down:before {
  content: "\e037";
}

.glyphicon-volume-up:before {
  content: "\e038";
}

.glyphicon-qrcode:before {
  content: "\e039";
}

.glyphicon-barcode:before {
  content: "\e040";
}

.glyphicon-tag:before {
  content: "\e041";
}

.glyphicon-tags:before {
  content: "\e042";
}

.glyphicon-book:before {
  content: "\e043";
}

.glyphicon-bookmark:before {
  content: "\e044";
}

.glyphicon-print:before {
  content: "\e045";
}

.glyphicon-camera:before {
  content: "\e046";
}

.glyphicon-font:before {
  content: "\e047";
}

.glyphicon-bold:before {
  content: "\e048";
}

.glyphicon-italic:before {
  content: "\e049";
}

.glyphicon-text-height:before {
  content: "\e050";
}

.glyphicon-text-width:before {
  content: "\e051";
}

.glyphicon-align-left:before {
  content: "\e052";
}

.glyphicon-align-center:before {
  content: "\e053";
}

.glyphicon-align-right:before {
  content: "\e054";
}

.glyphicon-align-justify:before {
  content: "\e055";
}

.glyphicon-list:before {
  content: "\e056";
}

.glyphicon-indent-left:before {
  content: "\e057";
}

.glyphicon-indent-right:before {
  content: "\e058";
}

.glyphicon-facetime-video:before {
  content: "\e059";
}

.glyphicon-picture:before {
  content: "\e060";
}

.glyphicon-map-marker:before {
  content: "\e062";
}

.glyphicon-adjust:before {
  content: "\e063";
}

.glyphicon-tint:before {
  content: "\e064";
}

.glyphicon-edit:before {
  content: "\e065";
}

.glyphicon-share:before {
  content: "\e066";
}

.glyphicon-check:before {
  content: "\e067";
}

.glyphicon-move:before {
  content: "\e068";
}

.glyphicon-step-backward:before {
  content: "\e069";
}

.glyphicon-fast-backward:before {
  content: "\e070";
}

.glyphicon-backward:before {
  content: "\e071";
}

.glyphicon-play:before {
  content: "\e072";
}

.glyphicon-pause:before {
  content: "\e073";
}

.glyphicon-stop:before {
  content: "\e074";
}

.glyphicon-forward:before {
  content: "\e075";
}

.glyphicon-fast-forward:before {
  content: "\e076";
}

.glyphicon-step-forward:before {
  content: "\e077";
}

.glyphicon-eject:before {
  content: "\e078";
}

.glyphicon-chevron-left:before {
  content: "\e079";
}

.glyphicon-chevron-right:before {
  content: "\e080";
}

.glyphicon-plus-sign:before {
  content: "\e081";
}

.glyphicon-minus-sign:before {
  content: "\e082";
}

.glyphicon-remove-sign:before {
  content: "\e083";
}

.glyphicon-ok-sign:before {
  content: "\e084";
}

.glyphicon-question-sign:before {
  content: "\e085";
}

.glyphicon-info-sign:before {
  content: "\e086";
}

.glyphicon-screenshot:before {
  content: "\e087";
}

.glyphicon-remove-circle:before {
  content: "\e088";
}

.glyphicon-ok-circle:before {
  content: "\e089";
}

.glyphicon-ban-circle:before {
  content: "\e090";
}

.glyphicon-arrow-left:before {
  content: "\e091";
}

.glyphicon-arrow-right:before {
  content: "\e092";
}

.glyphicon-arrow-up:before {
  content: "\e093";
}

.glyphicon-arrow-down:before {
  content: "\e094";
}

.glyphicon-share-alt:before {
  content: "\e095";
}

.glyphicon-resize-full:before {
  content: "\e096";
}

.glyphicon-resize-small:before {
  content: "\e097";
}

.glyphicon-exclamation-sign:before {
  content: "\e101";
}

.glyphicon-gift:before {
  content: "\e102";
}

.glyphicon-leaf:before {
  content: "\e103";
}

.glyphicon-fire:before {
  content: "\e104";
}

.glyphicon-eye-open:before {
  content: "\e105";
}

.glyphicon-eye-close:before {
  content: "\e106";
}

.glyphicon-warning-sign:before {
  content: "\e107";
}

.glyphicon-plane:before {
  content: "\e108";
}

.glyphicon-calendar:before {
  content: "\e109";
}

.glyphicon-random:before {
  content: "\e110";
}

.glyphicon-comment:before {
  content: "\e111";
}

.glyphicon-magnet:before {
  content: "\e112";
}

.glyphicon-chevron-up:before {
  content: "\e113";
}

.glyphicon-chevron-down:before {
  content: "\e114";
}

.glyphicon-retweet:before {
  content: "\e115";
}

.glyphicon-shopping-cart:before {
  content: "\e116";
}

.glyphicon-folder-close:before {
  content: "\e117";
}

.glyphicon-folder-open:before {
  content: "\e118";
}

.glyphicon-resize-vertical:before {
  content: "\e119";
}

.glyphicon-resize-horizontal:before {
  content: "\e120";
}

.glyphicon-hdd:before {
  content: "\e121";
}

.glyphicon-bullhorn:before {
  content: "\e122";
}

.glyphicon-bell:before {
  content: "\e123";
}

.glyphicon-certificate:before {
  content: "\e124";
}

.glyphicon-thumbs-up:before {
  content: "\e125";
}

.glyphicon-thumbs-down:before {
  content: "\e126";
}

.glyphicon-hand-right:before {
  content: "\e127";
}

.glyphicon-hand-left:before {
  content: "\e128";
}

.glyphicon-hand-up:before {
  content: "\e129";
}

.glyphicon-hand-down:before {
  content: "\e130";
}

.glyphicon-circle-arrow-right:before {
  content: "\e131";
}

.glyphicon-circle-arrow-left:before {
  content: "\e132";
}

.glyphicon-circle-arrow-up:before {
  content: "\e133";
}

.glyphicon-circle-arrow-down:before {
  content: "\e134";
}

.glyphicon-globe:before {
  content: "\e135";
}

.glyphicon-wrench:before {
  content: "\e136";
}

.glyphicon-tasks:before {
  content: "\e137";
}

.glyphicon-filter:before {
  content: "\e138";
}

.glyphicon-briefcase:before {
  content: "\e139";
}

.glyphicon-fullscreen:before {
  content: "\e140";
}

.glyphicon-dashboard:before {
  content: "\e141";
}

.glyphicon-paperclip:before {
  content: "\e142";
}

.glyphicon-heart-empty:before {
  content: "\e143";
}

.glyphicon-link:before {
  content: "\e144";
}

.glyphicon-phone:before {
  content: "\e145";
}

.glyphicon-pushpin:before {
  content: "\e146";
}

.glyphicon-usd:before {
  content: "\e148";
}

.glyphicon-gbp:before {
  content: "\e149";
}

.glyphicon-sort:before {
  content: "\e150";
}

.glyphicon-sort-by-alphabet:before {
  content: "\e151";
}

.glyphicon-sort-by-alphabet-alt:before {
  content: "\e152";
}

.glyphicon-sort-by-order:before {
  content: "\e153";
}

.glyphicon-sort-by-order-alt:before {
  content: "\e154";
}

.glyphicon-sort-by-attributes:before {
  content: "\e155";
}

.glyphicon-sort-by-attributes-alt:before {
  content: "\e156";
}

.glyphicon-unchecked:before {
  content: "\e157";
}

.glyphicon-expand:before {
  content: "\e158";
}

.glyphicon-collapse-down:before {
  content: "\e159";
}

.glyphicon-collapse-up:before {
  content: "\e160";
}

.glyphicon-log-in:before {
  content: "\e161";
}

.glyphicon-flash:before {
  content: "\e162";
}

.glyphicon-log-out:before {
  content: "\e163";
}

.glyphicon-new-window:before {
  content: "\e164";
}

.glyphicon-record:before {
  content: "\e165";
}

.glyphicon-save:before {
  content: "\e166";
}

.glyphicon-open:before {
  content: "\e167";
}

.glyphicon-saved:before {
  content: "\e168";
}

.glyphicon-import:before {
  content: "\e169";
}

.glyphicon-export:before {
  content: "\e170";
}

.glyphicon-send:before {
  content: "\e171";
}

.glyphicon-floppy-disk:before {
  content: "\e172";
}

.glyphicon-floppy-saved:before {
  content: "\e173";
}

.glyphicon-floppy-remove:before {
  content: "\e174";
}

.glyphicon-floppy-save:before {
  content: "\e175";
}

.glyphicon-floppy-open:before {
  content: "\e176";
}

.glyphicon-credit-card:before {
  content: "\e177";
}

.glyphicon-transfer:before {
  content: "\e178";
}

.glyphicon-cutlery:before {
  content: "\e179";
}

.glyphicon-header:before {
  content: "\e180";
}

.glyphicon-compressed:before {
  content: "\e181";
}

.glyphicon-earphone:before {
  content: "\e182";
}

.glyphicon-phone-alt:before {
  content: "\e183";
}

.glyphicon-tower:before {
  content: "\e184";
}

.glyphicon-stats:before {
  content: "\e185";
}

.glyphicon-sd-video:before {
  content: "\e186";
}

.glyphicon-hd-video:before {
  content: "\e187";
}

.glyphicon-subtitles:before {
  content: "\e188";
}

.glyphicon-sound-stereo:before {
  content: "\e189";
}

.glyphicon-sound-dolby:before {
  content: "\e190";
}

.glyphicon-sound-5-1:before {
  content: "\e191";
}

.glyphicon-sound-6-1:before {
  content: "\e192";
}

.glyphicon-sound-7-1:before {
  content: "\e193";
}

.glyphicon-copyright-mark:before {
  content: "\e194";
}

.glyphicon-registration-mark:before {
  content: "\e195";
}

.glyphicon-cloud-download:before {
  content: "\e197";
}

.glyphicon-cloud-upload:before {
  content: "\e198";
}

.glyphicon-tree-conifer:before {
  content: "\e199";
}

.glyphicon-tree-deciduous:before {
  content: "\e200";
}

comparing elements of the same array in java

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            System.out.println(a[i] + " not the same with  " + a[k + 1] + "\n");
        }
    }
}

You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.

Convert ndarray from float64 to integer

There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype() does) definitely check out the link.

How to create a HashMap with two keys (Key-Pair, Value)?

Two possibilities. Either use a combined key:

class MyKey {
    int firstIndex;
    int secondIndex;
    // important: override hashCode() and equals()
}

Or a Map of Map:

Map<Integer, Map<Integer, Integer>> myMap;

How to format numbers?

You may want to consider using toLocaleString()

Working Example:

_x000D_
_x000D_
const number = 1234567890.123;

console.log(number.toLocaleString('en-US')); // US format

console.log(number.toLocaleString('en-IN')); // Indian format
_x000D_
_x000D_
_x000D_

Tested in Chrome v60 and v88

Source: Number.prototype.toLocaleString() | MDN

How to check if a variable is not null?

Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:

if(myvar) { }

It also mentions what's considered 'falsey' that you might not realise.

What's a good hex editor/viewer for the Mac?

The one that I like is HexEdit Quick and easy to use

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

How do I check for equality using Spark Dataframe without SQL Query?

To get the negation, do this ...

df.filter(not( ..expression.. ))

eg

df.filter(not($"state" === "TX"))

How to create a hidden <img> in JavaScript?

I'm not sure I understand your question. But there are two approaches to making the image invisible...

Pure HTML

<img src="a.gif" style="display: none;" />

Or...

HTML + Javascript

<script type="text/javascript">
document.getElementById("myImage").style.display = "none";
</script>

<img id="myImage" src="a.gif" />

Execute PHP function with onclick

Try to do something like this:

<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script> 

<script type="text/javascript"> 
function doSomething() { 
    $.get("somepage.php"); 
    return false; 
} 
</script>

<a href="#" onclick="doSomething();">Click Me!</a>

SQL Query NOT Between Two Dates

If the 'NOT' is put before the start_date it should work. For some reason (I don't know why) when 'NOT' is put before 'BETWEEN' it seems to return everything.

NOT (start_date BETWEEN CAST('2009-12-15' AS DATE) AND CAST('2010-01-02' AS DATE))

Show dialog from fragment?

I must cautiously doubt the previously accepted answer that using a DialogFragment is the best option. The intended (primary) purpose of the DialogFragment seems to be to display fragments that are dialogs themselves, not to display fragments that have dialogs to display.

I believe that using the fragment's activity to mediate between the dialog and the fragment is the preferable option.

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

Port 465 is for "smtp over SSL".

http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html

[...] For example, use
    props.put("mail.smtp.port", "888");
to set the mail.smtp.port property, which is of type int.

Note that if you're using the "smtps" protocol to access SMTP over SSL, 
all the properties would be named "mail.smtps.*"

How to kill an application with all its activities?

My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.

To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.

Revert to Eclipse default settings

None of the answers above worked for me for Mars, so I took drastic measures.

  • Possibly optional: Donwload newest version of Eclipse from their website
  • Possibly optional: Find where your executable of current Eclipse's at, and remove the whole folder (you can't uninstall Eclipse through Configurations because it never really installs itself on the system)
  • Remove the .metadata folder inside your workspace folder, e.g. C:/Users/bram/Documents/workspace/.metadata (you can leave the projects as they were)
  • Remove the .eclipse folder inside {User}, e.g. C:/Users/bram/.eclipse
  • Optional: clean file system (and registry?) with a tool such as CCleaner

The last step is definitely optional, but I'm not sure about the first two. In other words, I can't confirm that the corrupted files were inside eclipse's executable folder, inside .eclipse or inside the workspace's .metadata. I'm pretty sure .metadata isn't the culprit since I'd already removed that before so my guess is that the folder .eclipse in {User} is the cause!

If you've tried my steps, please comment whether or not they helped you and which removed folder you think solved it.

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

How do I check if a string contains another string in Swift?

If you want to check that one String contains another Sub-String within it or not you can check it like this too,

var name = String()  
name = "John has two apples." 

Now, in this particular string if you want to know if it contains fruit name 'apple' or not you can do,

if name.contains("apple")      
{  
print("Yes , it contains fruit name")    
}    
else      
{    
 print(it does not contain any fruit name)    
}    

Hope this works for you.

In Python, how do I determine if an object is iterable?

I'd like to shed a little bit more light on the interplay of iter, __iter__ and __getitem__ and what happens behind the curtains. Armed with that knowledge, you will be able to understand why the best you can do is

try:
    iter(maybe_iterable)
    print('iteration will probably work')
except TypeError:
    print('not iterable')

I will list the facts first and then follow up with a quick reminder of what happens when you employ a for loop in python, followed by a discussion to illustrate the facts.

Facts

  1. You can get an iterator from any object o by calling iter(o) if at least one of the following conditions holds true:

    a) o has an __iter__ method which returns an iterator object. An iterator is any object with an __iter__ and a __next__ (Python 2: next) method.

    b) o has a __getitem__ method.

  2. Checking for an instance of Iterable or Sequence, or checking for the attribute __iter__ is not enough.

  3. If an object o implements only __getitem__, but not __iter__, iter(o) will construct an iterator that tries to fetch items from o by integer index, starting at index 0. The iterator will catch any IndexError (but no other errors) that is raised and then raises StopIteration itself.

  4. In the most general sense, there's no way to check whether the iterator returned by iter is sane other than to try it out.

  5. If an object o implements __iter__, the iter function will make sure that the object returned by __iter__ is an iterator. There is no sanity check if an object only implements __getitem__.

  6. __iter__ wins. If an object o implements both __iter__ and __getitem__, iter(o) will call __iter__.

  7. If you want to make your own objects iterable, always implement the __iter__ method.

for loops

In order to follow along, you need an understanding of what happens when you employ a for loop in Python. Feel free to skip right to the next section if you already know.

When you use for item in o for some iterable object o, Python calls iter(o) and expects an iterator object as the return value. An iterator is any object which implements a __next__ (or next in Python 2) method and an __iter__ method.

By convention, the __iter__ method of an iterator should return the object itself (i.e. return self). Python then calls next on the iterator until StopIteration is raised. All of this happens implicitly, but the following demonstration makes it visible:

import random

class DemoIterable(object):
    def __iter__(self):
        print('__iter__ called')
        return DemoIterator()

class DemoIterator(object):
    def __iter__(self):
        return self

    def __next__(self):
        print('__next__ called')
        r = random.randint(1, 10)
        if r == 5:
            print('raising StopIteration')
            raise StopIteration
        return r

Iteration over a DemoIterable:

>>> di = DemoIterable()
>>> for x in di:
...     print(x)
...
__iter__ called
__next__ called
9
__next__ called
8
__next__ called
10
__next__ called
3
__next__ called
10
__next__ called
raising StopIteration

Discussion and illustrations

On point 1 and 2: getting an iterator and unreliable checks

Consider the following class:

class BasicIterable(object):
    def __getitem__(self, item):
        if item == 3:
            raise IndexError
        return item

Calling iter with an instance of BasicIterable will return an iterator without any problems because BasicIterable implements __getitem__.

>>> b = BasicIterable()
>>> iter(b)
<iterator object at 0x7f1ab216e320>

However, it is important to note that b does not have the __iter__ attribute and is not considered an instance of Iterable or Sequence:

>>> from collections import Iterable, Sequence
>>> hasattr(b, '__iter__')
False
>>> isinstance(b, Iterable)
False
>>> isinstance(b, Sequence)
False

This is why Fluent Python by Luciano Ramalho recommends calling iter and handling the potential TypeError as the most accurate way to check whether an object is iterable. Quoting directly from the book:

As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn’t. This is more accurate than using isinstance(x, abc.Iterable) , because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.

On point 3: Iterating over objects which only provide __getitem__, but not __iter__

Iterating over an instance of BasicIterable works as expected: Python constructs an iterator that tries to fetch items by index, starting at zero, until an IndexError is raised. The demo object's __getitem__ method simply returns the item which was supplied as the argument to __getitem__(self, item) by the iterator returned by iter.

>>> b = BasicIterable()
>>> it = iter(b)
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Note that the iterator raises StopIteration when it cannot return the next item and that the IndexError which is raised for item == 3 is handled internally. This is why looping over a BasicIterable with a for loop works as expected:

>>> for x in b:
...     print(x)
...
0
1
2

Here's another example in order to drive home the concept of how the iterator returned by iter tries to access items by index. WrappedDict does not inherit from dict, which means instances won't have an __iter__ method.

class WrappedDict(object): # note: no inheritance from dict!
    def __init__(self, dic):
        self._dict = dic

    def __getitem__(self, item):
        try:
            return self._dict[item] # delegate to dict.__getitem__
        except KeyError:
            raise IndexError

Note that calls to __getitem__ are delegated to dict.__getitem__ for which the square bracket notation is simply a shorthand.

>>> w = WrappedDict({-1: 'not printed',
...                   0: 'hi', 1: 'StackOverflow', 2: '!',
...                   4: 'not printed', 
...                   'x': 'not printed'})
>>> for x in w:
...     print(x)
... 
hi
StackOverflow
!

On point 4 and 5: iter checks for an iterator when it calls __iter__:

When iter(o) is called for an object o, iter will make sure that the return value of __iter__, if the method is present, is an iterator. This means that the returned object must implement __next__ (or next in Python 2) and __iter__. iter cannot perform any sanity checks for objects which only provide __getitem__, because it has no way to check whether the items of the object are accessible by integer index.

class FailIterIterable(object):
    def __iter__(self):
        return object() # not an iterator

class FailGetitemIterable(object):
    def __getitem__(self, item):
        raise Exception

Note that constructing an iterator from FailIterIterable instances fails immediately, while constructing an iterator from FailGetItemIterable succeeds, but will throw an Exception on the first call to __next__.

>>> fii = FailIterIterable()
>>> iter(fii)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: iter() returned non-iterator of type 'object'
>>>
>>> fgi = FailGetitemIterable()
>>> it = iter(fgi)
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/iterdemo.py", line 42, in __getitem__
    raise Exception
Exception

On point 6: __iter__ wins

This one is straightforward. If an object implements __iter__ and __getitem__, iter will call __iter__. Consider the following class

class IterWinsDemo(object):
    def __iter__(self):
        return iter(['__iter__', 'wins'])

    def __getitem__(self, item):
        return ['__getitem__', 'wins'][item]

and the output when looping over an instance:

>>> iwd = IterWinsDemo()
>>> for x in iwd:
...     print(x)
...
__iter__
wins

On point 7: your iterable classes should implement __iter__

You might ask yourself why most builtin sequences like list implement an __iter__ method when __getitem__ would be sufficient.

class WrappedList(object): # note: no inheritance from list!
    def __init__(self, lst):
        self._list = lst

    def __getitem__(self, item):
        return self._list[item]

After all, iteration over instances of the class above, which delegates calls to __getitem__ to list.__getitem__ (using the square bracket notation), will work fine:

>>> wl = WrappedList(['A', 'B', 'C'])
>>> for x in wl:
...     print(x)
... 
A
B
C

The reasons your custom iterables should implement __iter__ are as follows:

  1. If you implement __iter__, instances will be considered iterables, and isinstance(o, collections.abc.Iterable) will return True.
  2. If the object returned by __iter__ is not an iterator, iter will fail immediately and raise a TypeError.
  3. The special handling of __getitem__ exists for backwards compatibility reasons. Quoting again from Fluent Python:

That is why any Python sequence is iterable: they all implement __getitem__ . In fact, the standard sequences also implement __iter__, and yours should too, because the special handling of __getitem__ exists for backward compatibility reasons and may be gone in the future (although it is not deprecated as I write this).

Conda environments not showing up in Jupyter Notebook

Summary (tldr)

If you want the 'python3' kernel to always run the Python installation from the environment where it is launched, delete the User 'python3' kernel, which is taking precedence over whatever the current environment is with:

jupyter kernelspec remove python3

Full Solution

I am going to post an alternative and simpler solution for the following case:

  • You have created a conda environment
  • This environment has jupyter installed (which also installs ipykernel)
  • When you run the command jupyter notebook and create a new notebook by clicking 'python3' in the 'New' dropdown menu, that notebook executes python from the base environment and not from the current environment.
  • You would like it so that launching a new notebook with 'python3' within any environment executes the Python version from that environment and NOT the base

I am going to use the name 'test_env' for the environment for the rest of the solution. Also, note that 'python3' is the name of the kernel.

The currently top-voted answer does work, but there is an alternative. It says to do the following:

python -m ipykernel install --user --name test_env --display-name "Python (test_env)"

This will give you the option of using the test_env environment regardless of what environment you launch jupyter notebook from. But, launching a notebook with 'python3' will still use the Python installation from the base environment.

What likely is happening is that there is a user python3 kernel that exists. Run the command jupyter kernelspec list to list all of your environments. For instance, if you have a mac you will be returned the following (my user name is Ted).

python3       /Users/Ted/Library/Jupyter/kernels/python3

What Jupyter is doing here is searching through three different paths looking for kernels. It goes from User, to Env, to System. See this document for more details on the paths it searches for each operating system.

The two kernels above are both in the User path, meaning they will be available regardless of the environment that you launch a jupyter notebook from. This also means that if there is another 'python3' kernel at the environment level, then you will never be able to access it.

To me, it makes more sense that choosing the 'python3' kernel from the environment you launched the notebook from should execute Python from that environment.

You can check to see if you have another 'python3' environment by looking in the Env search path for your OS (see the link to the docs above). For me (on my mac), I issued the following command:

 ls /Users/Ted/anaconda3/envs/test_env/share/jupyter/kernels

And I indeed had a 'python3' kernel listed there.

Thanks to this GitHub issue comment (look at the first response), you can remove the User 'python3' environment with the following command:

jupyter kernelspec remove python3

Now when you run jupyter kernelspec list, assuming the test_env is still active, you will get the following:

python3       /Users/Ted/anaconda3/envs/test_env/share/jupyter/kernels/python3

Notice that this path is located within the test_env directory. If you create a new environment, install jupyter, activate it, and list the kernels, you will get another 'python3' kernel located in its environment path.

The User 'python3' kernel was taking precedence over any of the Env 'python3' kernels. By removing it, the active environment 'python3' kernel was exposed and able to be chosen every time. This eliminates the need to manually create kernels. It also makes more sense in terms of software development where one would want to isolate themselves into a single environment. Running a kernel that is different from the host environment doesn't seem natural.

It also seems that this User 'python3' is not installed for everyone by default, so not everyone is confronted by this issue.

Execution failed app:processDebugResources Android Studio

In my case, I cleaned the project (Menubar -> Build -> Clean Project) and then did the build again. It worked.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon destroys the session as stated above so you should use this when logging someone out. I think a good use of Session.Clear would be for a shopping basket on an ecommerce website. That way the basket gets cleared without logging out the user.

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

Is there a way to collapse all code blocks in Eclipse?

Just to sum up:

  1. anycode:
    • ctrl + shift + NUMPAD_divide = collapse all
    • NUMPAD_multiply = exand all
  2. pydev:
    • -ctrl + 0 = collapse all
    • -ctrl + 9 = exand all

How to validate white spaces/empty spaces? [Angular 2]

You can create a custom validator to handle this.

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])

Add noWhitespaceValidator method to your component

public noWhitespaceValidator(control: FormControl) {
    const isWhitespace = (control.value || '').trim().length === 0;
    const isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true };
}

and in the HTML

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>

Android "elevation" not showing a shadow

Adding to the accepted answer, there is one more reason due to which elevation may not work as expected if the Bluelight filter feature on the phone is ON.

I was facing this issue when the elevation appeared completely distorted and unbearable in my device. But the elevation was fine in the preview. Turning off the Bluelight filter on phone resolved the issue.

So even after setting

android:outlineProvider="bounds"

The elevation is not working properly, then you can try to tinker with phone's color settings.

How to add a class to body tag?

$('body').toggleClass("className");

perfectly works

Python Prime number checker

max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
    isPrime=True
    for y in range(2,int(x**0.5)+1) :
        if x%y==0:
            isPrime=False
            break

    if isPrime:
        primeList.append(x)
print(primeList)

Change window location Jquery

you can use the new push/pop state functions in the history manipulation API.

How do you remove the title text from the Android ActionBar?

ActionBar actionBar = getActionBar();
actionBar.setTitle("");

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

mssql convert varchar to float

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED

above will return values

however below query wont work

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED

as @INPUT_1 actually has varchar in it.

So your output column must have a varchar in it.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

This help me a lot:

http://maestric.com/doc/mac/apache_php_mysql_snow_leopard

It also works for Mac OS X Lion :D

.:EDIT:. On my case the prefepane only allows to start and stop mysql, but after some issues i've uninstalled him. If you need a application to run queries and create DB, you could use: Sequel Pro (it's free) or Navicat

If you need start and stop mysql in ~/.bash_profile you can add these lines:

#For MySQL
alias mysql_start="/Library/StartupItems/MySQLCOM/MySQLCOM start"
alias mysql_stop="/Library/StartupItems/MySQLCOM/MySQLCOM stop"

After reloaded the console just call:

$mysql_start 

or

$mysql_stop 

agreding the desired action. Hope helped you.

Is there an opposite to display:none?

In the case of a printer friendly stylesheet, I use the following:

/* screen style */
.print_only { display: none; }

/* print stylesheet */
div.print_only { display: block; }
span.print_only { display: inline; }
.no_print { display: none; }

I used this when I needed to print a form containing values and the input fields were difficult to print. So I added the values wrapped in a span.print_only tag (div.print_only was used elsewhere) and then applied the .no_print class to the input fields. So on-screen you would see the input fields and when printed, only the values. If you wanted to get fancy you could use JS to update the values in the span tags when the fields were updated but that wasn't necessary in my case. Perhaps not the the most elegant solution but it worked for me!

node.js remove file

Use NPM module fs-extra, which gives you everything in fs, plus everything is Promisified. As a bonus, there's a fs.remove() method available.

Why does Java's hashCode() in String use 31 as a multiplier?

On (mostly) old processors, multiplying by 31 can be relatively cheap. On an ARM, for instance, it is only one instruction:

RSB       r1, r0, r0, ASL #5    ; r1 := - r0 + (r0<<5)

Most other processors would require a separate shift and subtract instruction. However, if your multiplier is slow this is still a win. Modern processors tend to have fast multipliers so it doesn't make much difference, so long as 32 goes on the correct side.

It's not a great hash algorithm, but it's good enough and better than the 1.0 code (and very much better than the 1.0 spec!).

How do I get the offset().top value of an element without using jQuery?

Seems you can just use the prop method on the angular element:

var top = $el.prop('offsetTop');

Works for me. Does anyone know any downside to this?

count (non-blank) lines-of-code in bash

This gives the count of number of lines without counting the blank lines:

grep -v ^$ filename wc -l | sed -e 's/ //g' 

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I had this same problem, but I'm a Linux user.

I resolved the problem by reattempting the installation with adminstrator privileges. [For those Linux users reading this, I ran studio.sh with sudo.]

OS X Terminal shortcut: Jump to beginning/end of line

I am not sure if this will work for you (I still use OS 10.8), but these work for my terminal:

home = move cursor to the start of the line
shift+end = move cursor to the end of the line

alt+leftArrow = move one "word" to the left
alt+rightArrow = move one "word" to the right

Hope this helps!

Is there a CSS selector for text nodes?

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

Laravel 5 PDOException Could Not Find Driver

Same thing happend to me after upgrading distro.

Running sudo apt-get install php7.0-mysql fixed it for me.

How do I get the current username in .NET using C#?

String myUserName = Environment.UserName

This will give you output - your_user_name

gpg: no valid OpenPGP data found

In my case, the problem turned out to be that the keyfile was behind a 301 Moved Permanently redirect, which the curl command failed to follow. I fixed it by using wget instead:

wget URL
sudo apt-key add FILENAME

...where FILENAME is the file name that wget outputs after it downloads the file.

Update: Alternatively, you can use curl -L to make curl follow redirects.

How to convert upper case letters to lower case

You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.

w.strip(',.').lower()

How to hide console window in python?

In linux, just run it, no problem. In Windows, you want to use the pythonw executable.

Update

Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?

  • UNIX (Linux)

$ nohup mypythonprog &

  • Windows

C:/> start pythonw mypythonprog

I think that's right. In any case, now you can close the terminal.

how to get all child list from Firebase android

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference mMainMenuRef = mRootRef.child("tut_master");//main
        DatabaseReference mSubMenuRef = mMainMenuRef.child("english");//sub
        List<Tutorial>   tutorialNames=new ArrayList<>();
        mSubMenuRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    long id = ds.child("id").getValue(Long.class);
                    String name = ds.child("name").getValue(String.class);

                    Tutorial tut = new Tutorial();
                    tut.setTutId(id+"");
                    tut.setTutName(name);
                    tutList.add(tut);

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }


        });

Correct modification of state arrays in React.js

This code work for me:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
    this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
  })

Convert string to variable name in JavaScript

It can be done like this

_x000D_
_x000D_
(function(X, Y) {_x000D_
  _x000D_
  // X is the local name of the 'class'_x000D_
  // Doo is default value if param X is empty_x000D_
  var X = (typeof X == 'string') ? X: 'Doo';_x000D_
  var Y = (typeof Y == 'string') ? Y: 'doo';_x000D_
  _x000D_
  // this refers to the local X defined above_x000D_
  this[X] = function(doo) {_x000D_
    // object variable_x000D_
    this.doo = doo || 'doo it';_x000D_
  }_x000D_
  // prototypal inheritance for methods_x000D_
  // defined by another_x000D_
  this[X].prototype[Y] = function() {_x000D_
    return this.doo || 'doo';_x000D_
  };_x000D_
  _x000D_
  // make X global_x000D_
  window[X] = this[X];_x000D_
}('Dooa', 'dooa')); // give the names here_x000D_
_x000D_
// test_x000D_
doo = new Dooa('abc');_x000D_
doo2 = new Dooa('def');_x000D_
console.log(doo.dooa());_x000D_
console.log(doo2.dooa());
_x000D_
_x000D_
_x000D_

In C, how should I read a text file and print all strings

Use "read()" instead o fscanf:

ssize_t read(int fildes, void *buf, size_t nbyte);

DESCRIPTION

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf.

Here is an example:

http://cmagical.blogspot.com/2010/01/c-programming-on-unix-implementing-cat.html

Working part from that example:

f=open(argv[1],O_RDONLY);
while ((n=read(f,l,80)) > 0)
    write(1,l,n);

An alternate approach is to use getc/putc to read/write 1 char at a time. A lot less efficient. A good example: http://www.eskimo.com/~scs/cclass/notes/sx13.html

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

Deserialize json object into dynamic object using Json.net

If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.

var converter = new ExpandoObjectConverter();    
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);

How to specify jdk path in eclipse.ini on windows 8 when path contains space

Go to C drive root in cmd Type dir /x This will list down the directories name with ~.use that instead of Program Files in your jdk path

Center a button in a Linear layout

Center using a LinearLayout:

<LinearLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/btnFindMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/findme" />
</LinearLayout>

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

Concatenate chars to form String in java

Use str = ""+a+b+c;

Here the first + is String concat, so the result will be a String. Note where the "" lies is important.

Or (maybe) better, use a StringBuilder.

How do we download a blob url video

  1. Find the playlist/manifest with the developer tools network tab. There is always one, as that's how it works. It might have a m3u8 extension that you can type into the Filter. (The youtube-dl tool can also find the m3u8 tool automatically some time give it direct link to the webpage where the video is being displayed.)

  2. Give it to the youtube-dl tool (Download) . It can download much more than just YouTube. It'll auto-download each segment then combine everything with FFmpeg then discard the parts. There is a good chance it supports the site you want to download from natively, and you don't even need to do step #1.

  3. If you find a site that is stubborn and you run into 403 errors... Telerik Fiddler to the rescue. It can catch and save anything transmitted (such as the video file) as it acts as a local proxy. Everything you see/hear can be downloaded, unless it's DRM content like Spotify.

Note: in windows, you can use youtube-dl.exe using "Command Prompt" or creating a batch file. i.e

d:\youtube-dl.exe https://www.youtube.com/watch?v=gbdFOwKHil0

Thanks

What is a 'NoneType' object?

Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>

Python's None object is roughly equivalent to null, nil, etc. in other languages.

Print a div using javascript in angularJS single page application

I don't think there's any need of writing this much big codes.

I've just installed angular-print bower package and all is set to go.

Just inject it in module and you're all set to go Use pre-built print directives & fun is that you can also hide some div if you don't want to print

http://angular-js.in/angularprint/

Mine is working awesome .

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

You should use your language's URL encoding methods when placing strings in URLs.

You can see a handy list of characters with man ascii. It has this compact diagram available for mapping hexadecimal codes to the character:

   2 3 4 5 6 7       
 -------------      
0:   0 @ P ` p     
1: ! 1 A Q a q     
2: " 2 B R b r     
3: # 3 C S c s     
4: $ 4 D T d t     
5: % 5 E U e u     
6: & 6 F V f v     
7: ' 7 G W g w     
8: ( 8 H X h x     
9: ) 9 I Y i y     
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL

You can also quickly check a character's hexadecimal equivalent with:

$ echo -n , | xxd -p
2c

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You should have a table with the list of emails to check. Then do this query:

SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status
FROM EmailsToCheck E
LEFT JOIN (SELECT DISTINCT Email FROM Users) U
ON E.Email = U.Email

Get hours difference between two dates in Moment Js

 var start=moment(1541243900000);
 var end=moment(1541243942882);
 var duration = moment.duration(end.diff(startTime));
 var hours = duration.asHours();

As you can see, the start and end date needed to be moment objects for this method to work.

Entity Framework and SQL Server View

Agree with @Tillito, however in most cases it will foul SQL optimizer and it will not use right indexes.

It may be obvious for somebody, but I burned hours solving performance issues using Tillito solution. Lets say you have the table:

 Create table OrderDetail
    (  
       Id int primary key,
       CustomerId int references Customer(Id),
       Amount decimal default(0)
    );
 Create index ix_customer on OrderDetail(CustomerId);

and your view is something like this

 Create view CustomerView
    As
      Select 
          IsNull(CustomerId, -1) as CustomerId, -- forcing EF to use it as key
          Sum(Amount) as Amount
      From OrderDetail
      Group by CustomerId

Sql optimizer will not use index ix_customer and it will perform table scan on primary index, but if instead of:

Group by CustomerId

you use

Group by IsNull(CustomerId, -1)

it will make MS SQL (at least 2008) include right index into plan.

If

How to clear textarea on click?

Here's a solution if you have dynamic data coming in from a database...
The 'data' variable represents database data.
If there is no data saved yet, the placeholder will show instead.
Once the user starts typing, the placeholder will disappear and they can then enter text.

Hope this helps someone!

// If data is NOT saved in the database
if (data == "") {
    var desc_text = "";
    var placeholder = "Please describe why";
// If data IS saved in the database
} else {
    var desc_text = data;
    var placeholder = "";
}

<textarea placeholder="'+placeholder+'">'+desc_text+'</textarea>

How to get size in bytes of a CLOB column in Oracle?

Try this one for CLOB sizes bigger than VARCHAR2:

We have to split the CLOB in parts of "VARCHAR2 compatible" sizes, run lengthb through every part of the CLOB data, and summarize all results.

declare
   my_sum int;
begin
   for x in ( select COLUMN, ceil(DBMS_LOB.getlength(COLUMN) / 2000) steps from TABLE ) 
   loop
       my_sum := 0;
       for y in 1 .. x.steps
       loop
          my_sum := my_sum + lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 ));
          -- some additional output
          dbms_output.put_line('step:' || y );
          dbms_output.put_line('char length:' || DBMS_LOB.getlength(dbms_lob.substr( x.COLUMN, 2000 , (y-1)*2000+1 )));
          dbms_output.put_line('byte length:' || lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 )));
          continue;
        end loop;
        dbms_output.put_line('char summary:' || DBMS_LOB.getlength(x.COLUMN));
        dbms_output.put_line('byte summary:' || my_sum);
        continue;
    end loop;
end;
/

Why is the jquery script not working?

if you have some other scripts that conflicts with jQuery wrap your code with this

(function($) {
    //here is your code
})(jQuery);

How do I set browser width and height in Selenium WebDriver?

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.window.width',0)
profile.set_preference('browser.window.height',0)
profile.update_preferences()

write this code into setup part of your test code, before the: webdriver.Firefox() line.

WPF global exception handler

You can handle the AppDomain.UnhandledException event

EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException

How do I split a string by a multi-character delimiter in C#?

string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));

Django CSRF Cookie Not Set

I came across a similar situation while working with DRF, the solution was appending .as_view() method to the View in urls.py

Add Facebook Share button to static HTML page

 <div class="fb_share">
     <a name="fb_share" type="box_count" share_url="<?php the_permalink() ?>"
       href="http://www.facebook.com/sharer.php">Partilhar</a>
     <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script> </div> <?php }  }

 add_action('thesis_hook_byline_item','fb_share');

How can I check the size of a collection within a Django template?

I need the collection length to decide whether I should render table <thead></thead>

but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

I got to use {% if forloop.first %} {% endif %} to overcome:

<table>
    {% for record in service_list %}
        {% if forloop.first %}
            <thead>
            <tr>
                <th>??</th>
            </tr>
            </thead>
        {% endif %}
        <tbody>
        <tr>
            <td>{{ record.date }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

'\r': command not found - .bashrc / .bash_profile

When all else fails in Cygwin...

Try running the dos2unix command on the file in question.

It might help when you see error messages like this:

-bash: '\r': command not found

Windows style newline characters can cause issues in Cygwin.

The dos2unix command modifies newline characters so they are Unix / Cygwin compatible.

CAUTION: the dos2unix command modifies files in place, so take precaution if necessary.

If you need to keep the original file, you should back it up first.

Note for Mac users: The dos2unix command does not exist on Mac OS X.

Check out this answer for a variety of solutions using different tools.


There is also a unix2dos command that does the reverse:

It modifies Unix newline characters so they're compatible with Windows tools.

If you open a file with Notepad and all the lines run together, try unix2dos filename.

jQuery $.ajax(), pass success data into separate function

Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:

function GetProcedureById(procedureId)
{
    var includeMaster = true;
    pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: pString,
        datatype: "json",
        dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
                    typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
        success: function(msg)
        {
            LoadProcedure(msg);
        },
        failure: function(msg)
        {
            // $("#sometextplace").text("Procedure did not load");
        }
    });
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
    if (jdata.length < 10)
    {
        $("select#cptIcdProcedureSelect").attr('size', jdata.length);
    }
    else
    {
        $("select#cptIcdProcedureSelect").attr('size', '10');
    };
    var options = '';
    for (var i = 0; i < jdata.length; i++)
    {
        options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
    };
    $("select#cptIcdProcedureSelect").html(options);
};

ComboBox.SelectedText doesn't give me the SelectedText

To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:

string myItem = comboBox1.SelectedItem.ToString(); //this does the trick

Difference between java HH:mm and hh:mm on SimpleDateFormat

Use the built-in localized formats

If this is for showing a time of day to a user, then in at least 19 out of 20 you don’t need to care about kk, HH nor hh. I suggest that you use something like this:

    DateTimeFormatter defaultTimeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    System.out.format("%s: %s%n",
            Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));

The point is that it gives different output in different default locales. For example:

en_SS: 12:00 AM
fr_BL: 00:00
ps_AF: 0:00
es_CO: 12:00 a.m.

The localized formats have been designed to conform with the expectations of different cultures. So they generally give the user a better experience and they save you of writing a format pattern string, which is always error-prone.

I furthermore suggest that you don’t use SimpleDateFormat. That class is notoriously troublesome and fortunately long outdated. Instead I use java.time, the modern Java date and time API. It is so much nicer to work with.

Four pattern letters for hour: H, h, k and K

Of course if you need to parse a string with a specified format, and also if you have a very specific formatting requirement, it’s good to use a format pattern string. There are actually four different pattern letters to choose from for hour (quoted from the documentation):

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-day (1-24)    number            24
   H       hour-of-day (0-23)          number            0

In practice H and h are used. As far as I know k and K are not (they may just have been included for the sake of completeness). But let’s just see them all in action:

    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("hh:mm a  HH:mm  kk:mm  KK:mm a", Locale.ENGLISH);
    System.out.println(LocalTime.of(0, 0).format(timeFormatter));
    System.out.println(LocalTime.of(1, 15).format(timeFormatter));
    System.out.println(LocalTime.of(11, 25).format(timeFormatter));
    System.out.println(LocalTime.of(12, 35).format(timeFormatter));
    System.out.println(LocalTime.of(13, 40).format(timeFormatter));
12:00 AM  00:00  24:00  00:00 AM
01:15 AM  01:15  01:15  01:15 AM
11:25 AM  11:25  11:25  11:25 AM
12:35 PM  12:35  12:35  00:35 PM
01:40 PM  13:40  13:40  01:40 PM

If you don’t want the leading zero, just specify one pattern letter, that is h instead of hh or H instead of HH. It will still accept two digits when parsing, and if a number to be printed is greater than 9, two digits will still be printed.

Links

Error - trustAnchors parameter must be non-empty

Slim chance this will help anyone but....for anyone running Java 8 from a Docker Image on a Raspberry Pi (using AMD CPU) I got the following Dockerfile to build and run successfully for me

FROM hypriot/rpi-java
USER root

WORKDIR /usr/build/

RUN /usr/bin/printf '\xfe\xed\xfe\xed\x00\x00\x00\x02\x00\x00\x00\x00\xe2\x68\x6e\x45\xfb\x43\xdf\xa4\xd9\x92\xdd\x41\xce\xb6\xb2\x1c\x63\x30\xd7\x92' > /etc/ssl/certs/java/cacerts
RUN update-ca-certificates -f
RUN /var/lib/dpkg/info/ca-certificates-java.postinst configure

EXPOSE 8080

ARG JAR_FILE=target/app-0.0.1-SNAPSHOT.jar

ADD ${JAR_FILE} app.jar

ENTRYPOINT ["java", "-Djavax.net.ssl.trustStorePassword=changeit", "-Djavax.net.ssl.trustStore=/etc/ssl/certs/java/cacerts", "-jar", "app.jar"]

Get only part of an Array in Java?

You can use subList(int fromIndex, int toIndex) method on your integers arr, something like this:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        List<Integer> partialArr = arr.subList(1, 3);

        // print the subArr
        for (Integer i: partialArr)
            System.out.println(i + " ");
    }
}

Output will be: 2 3.

Note that subList(int fromIndex, int toIndex) method performs minus 1 on the 2nd variable it receives (var2 - 1), i don't know exactly why, but that's what happens, maybe to reduce the chance of exceeding the size of the array.

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

How can I store JavaScript variable output into a PHP variable?

The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

<script>
  var a="Hello";
  window.location.href = window.location.href+'?a='+a;
</script>

Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

<?php 
  $variable = $_GET['a'];
?>

Android: how to make keyboard enter button say "Search" and handle its click?

In the layout set your input method options to search.

<EditText
    android:imeOptions="actionSearch" 
    android:inputType="text" />

In the java add the editor action listener.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();
            return true;
        }
        return false;
    }
});

How to convert a string to an integer in JavaScript?

The safest way to ensure you get a valid integer:

let integer = (parseInt(value, 10) || 0);

Examples:

// Example 1 - Invalid value:
let value = null;
let integer = (parseInt(value, 10) || 0);
// => integer = 0
// Example 2 - Valid value:
let value = "1230.42";
let integer = (parseInt(value, 10) || 0);
// => integer = 1230
// Example 3 - Invalid value:
let value = () => { return 412 };
let integer = (parseInt(value, 10) || 0);
// => integer = 0

What is REST? Slightly confused

http://en.wikipedia.org/wiki/Representational_State_Transfer

The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.

Pass connection string to code-first DbContext

from here

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
    }

note you may need to add Microsoft.EntityFrameworkCore.SqlServer

Open application after clicking on Notification

Here's example using NotificationCompact.Builder class which is the recent version to build notification.

private void startNotification() {
    Log.i("NextActivity", "startNotification");

 // Sets an ID for the notification
      int mNotificationId = 001;

    // Build Notification , setOngoing keeps the notification always in status bar
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ldb)
                    .setContentTitle("Stop LDB")
                    .setContentText("Click to stop LDB")
                    .setOngoing(true);

    // Create pending intent, mention the Activity which needs to be 
    //triggered when user clicks on notification(StopScript.class in this case)

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, StopScript.class), PendingIntent.FLAG_UPDATE_CURRENT);


    mBuilder.setContentIntent(contentIntent);


    // Gets an instance of the NotificationManager service
   NotificationManager mNotificationManager =
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


    // Builds the notification and issues it.
    mNotificationManager.notify(mNotificationId, mBuilder.build());


}

How to tell if node.js is installed or not

Open a terminal window. Type:

node -v

This will display your nodejs version.

Navigate to where you saved your script and input:

node script.js

This will run your script.

How to make MySQL table primary key auto increment with some prefix

Here is PostgreSQL example without trigger if someone need it on PostgreSQL:

CREATE SEQUENCE messages_seq;

 CREATE TABLE IF NOT EXISTS messages (
    id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
    name CHAR(30) NOT NULL,
);

ALTER SEQUENCE messages_seq OWNED BY messages.id;

Calculating the area under a curve given a set of coordinates, without knowing the function

You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.

Python script that calculates Simpsons rule:

def integrate(y_vals, h):
    i = 1
    total = y_vals[0] + y_vals[-1]
    for y in y_vals[1:-1]:
        if i % 2 == 0:
            total += 2 * y
        else:
            total += 4 * y
        i += 1
    return total * (h / 3.0)

h is the offset (or gap) between y values, and y_vals is an array of well, y values.

Example (In same file as above function):

y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)

ngrok command not found

In shorts,ngrok should be in same directory in which you are running ngrok command.

Binding a Button's visibility to a bool value in ViewModel

In View:

<Button
 Height="50" Width="50"
 Style="{StaticResource MyButtonStyle}"
 Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>

In view Model:

public _advancedFormat = Visibility.visible (whatever you start with)

public Visibility AdvancedFormat
{
 get{return _advancedFormat;}
 set{
   _advancedFormat = value;
   //raise property changed here
}

You will need to have a property changed event

 protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
        PropertyChanged.Raise(this, e); 
    } 

    protected void OnPropertyChanged(string propertyName) 
    { 
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 
    } 

This is how they use Model-view-viewmodel

But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.

Can someone explain __all__ in Python?

Explain __all__ in Python?

I keep seeing the variable __all__ set in different __init__.py files.

What does this do?

What does __all__ do?

It declares the semantically "public" names from a module. If there is a name in __all__, users are expected to use it, and they can have the expectation that it will not change.

It also will have programmatic affects:

import *

__all__ in a module, e.g. module.py:

__all__ = ['foo', 'Bar']

means that when you import * from the module, only those names in the __all__ are imported:

from module import *               # imports foo and Bar

Documentation tools

Documentation and code autocompletion tools may (in fact, should) also inspect the __all__ to determine what names to show as available from a module.

__init__.py makes a directory a Python package

From the docs:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

So the __init__.py can declare the __all__ for a package.

Managing an API:

A package is typically made up of modules that may import one another, but that are necessarily tied together with an __init__.py file. That file is what makes the directory an actual Python package. For example, say you have the following files in a package:

package
+-- __init__.py
+-- module_1.py
+-- module_2.py

Let's create these files with Python so you can follow along - you could paste the following into a Python 3 shell:

from pathlib import Path

package = Path('package')
package.mkdir()

(package / '__init__.py').write_text("""
from .module_1 import *
from .module_2 import *
""")

package_module_1 = package / 'module_1.py'
package_module_1.write_text("""
__all__ = ['foo']
imp_detail1 = imp_detail2 = imp_detail3 = None
def foo(): pass
""")

package_module_2 = package / 'module_2.py'
package_module_2.write_text("""
__all__ = ['Bar']
imp_detail1 = imp_detail2 = imp_detail3 = None
class Bar: pass
""")

And now you have presented a complete api that someone else can use when they import your package, like so:

import package
package.foo()
package.Bar()

And the package won't have all the other implementation details you used when creating your modules cluttering up the package namespace.

__all__ in __init__.py

After more work, maybe you've decided that the modules are too big (like many thousands of lines?) and need to be split up. So you do the following:

package
+-- __init__.py
+-- module_1
¦   +-- foo_implementation.py
¦   +-- __init__.py
+-- module_2
    +-- Bar_implementation.py
    +-- __init__.py

First make the subpackage directories with the same names as the modules:

subpackage_1 = package / 'module_1'
subpackage_1.mkdir()
subpackage_2 = package / 'module_2'
subpackage_2.mkdir()

Move the implementations:

package_module_1.rename(subpackage_1 / 'foo_implementation.py')
package_module_2.rename(subpackage_2 / 'Bar_implementation.py')

create __init__.pys for the subpackages that declare the __all__ for each:

(subpackage_1 / '__init__.py').write_text("""
from .foo_implementation import *
__all__ = ['foo']
""")
(subpackage_2 / '__init__.py').write_text("""
from .Bar_implementation import *
__all__ = ['Bar']
""")

And now you still have the api provisioned at the package level:

>>> import package
>>> package.foo()
>>> package.Bar()
<package.module_2.Bar_implementation.Bar object at 0x7f0c2349d210>

And you can easily add things to your API that you can manage at the subpackage level instead of the subpackage's module level. If you want to add a new name to the API, you simply update the __init__.py, e.g. in module_2:

from .Bar_implementation import *
from .Baz_implementation import *
__all__ = ['Bar', 'Baz']

And if you're not ready to publish Baz in the top level API, in your top level __init__.py you could have:

from .module_1 import *       # also constrained by __all__'s
from .module_2 import *       # in the __init__.py's
__all__ = ['foo', 'Bar']     # further constraining the names advertised

and if your users are aware of the availability of Baz, they can use it:

import package
package.Baz()

but if they don't know about it, other tools (like pydoc) won't inform them.

You can later change that when Baz is ready for prime time:

from .module_1 import *
from .module_2 import *
__all__ = ['foo', 'Bar', 'Baz']

Prefixing _ versus __all__:

By default, Python will export all names that do not start with an _. You certainly could rely on this mechanism. Some packages in the Python standard library, in fact, do rely on this, but to do so, they alias their imports, for example, in ctypes/__init__.py:

import os as _os, sys as _sys

Using the _ convention can be more elegant because it removes the redundancy of naming the names again. But it adds the redundancy for imports (if you have a lot of them) and it is easy to forget to do this consistently - and the last thing you want is to have to indefinitely support something you intended to only be an implementation detail, just because you forgot to prefix an _ when naming a function.

I personally write an __all__ early in my development lifecycle for modules so that others who might use my code know what they should use and not use.

Most packages in the standard library also use __all__.

When avoiding __all__ makes sense

It makes sense to stick to the _ prefix convention in lieu of __all__ when:

  • You're still in early development mode and have no users, and are constantly tweaking your API.
  • Maybe you do have users, but you have unittests that cover the API, and you're still actively adding to the API and tweaking in development.

An export decorator

The downside of using __all__ is that you have to write the names of functions and classes being exported twice - and the information is kept separate from the definitions. We could use a decorator to solve this problem.

I got the idea for such an export decorator from David Beazley's talk on packaging. This implementation seems to work well in CPython's traditional importer. If you have a special import hook or system, I do not guarantee it, but if you adopt it, it is fairly trivial to back out - you'll just need to manually add the names back into the __all__

So in, for example, a utility library, you would define the decorator:

import sys

def export(fn):
    mod = sys.modules[fn.__module__]
    if hasattr(mod, '__all__'):
        mod.__all__.append(fn.__name__)
    else:
        mod.__all__ = [fn.__name__]
    return fn

and then, where you would define an __all__, you do this:

$ cat > main.py
from lib import export
__all__ = [] # optional - we create a list if __all__ is not there.

@export
def foo(): pass

@export
def bar():
    'bar'

def main():
    print('main')

if __name__ == '__main__':
    main()

And this works fine whether run as main or imported by another function.

$ cat > run.py
import main
main.main()

$ python run.py
main

And API provisioning with import * will work too:

$ cat > run.py
from main import *
foo()
bar()
main() # expected to error here, not exported

$ python run.py
Traceback (most recent call last):
  File "run.py", line 4, in <module>
    main() # expected to error here, not exported
NameError: name 'main' is not defined

Commit only part of a file in Git

With TortoiseGit:

right click on the file and use Context Menu ? Restore after commit. This will create a copy of the file as it is. Then you can edit the file, e.g. in TortoiseGitMerge and undo all the changes you don't want to commit. After saving those changes you can commit the file.

How do I flush the PRINT buffer in TSQL?

Another better option is to not depend on PRINT or RAISERROR and just load your "print" statements into a ##Temp table in TempDB or a permanent table in your database which will give you visibility to the data immediately via a SELECT statement from another window. This works the best for me. Using a permanent table then also serves as a log to what happened in the past. The print statements are handy for errors, but using the log table you can also determine the exact point of failure based on the last logged value for that particular execution (assuming you track the overall execution start time in your log table.)

How to make Bootstrap 4 cards the same height in card-columns?

I came across this problem, most people use jQuery... Here was my solution. "Do not mind, I am just a beginner in this..."

.cards-collection {
    .card-item { 
        width: 100%;
        margin: 20px 20px;
        padding:0 ;
        .card {
            border-radius: 10px;
                button {
                    border: inherit;
                }
        }
    }
}
     .container-fluid
         .row.cards-collection.justify-content-center
           .card-item.col-lg-3.col-md-4.col-sm-6.col-11
              .card.h-100

If any card item height is e.g. 400px (based on it's contents), because the default for flex-align is stretch, then .card-item (child of row or card-collection class) will be stretched. making the height of the card to be 100% of the parent will occupy this full height.

I hope I was correct. Am I?

How do you launch the JavaScript debugger in Google Chrome?

Windows: CTRL-SHIFT-J OR F12

Mac: ?-?-J

Also available through the wrench menu (Tools > JavaScript Console):

JavaScript Console Menu

C# how to use enum with switch

All the other answers are correct, but you also need to call your method correctly:

Calculate(5, 5, Operator.PLUS))

And since you use int for left and right, the result will be int as well (3/2 will result in 1). you could cast to double before calculating the result or modify your parameters to accept double

How to hide a column (GridView) but still access its value?

If you do have a TemplateField inside the columns of your GridView and you have, say, a control named blah bound to it. Then place the outlook_id as a HiddenField there like this:

<asp:TemplateField HeaderText="OutlookID">
    <ItemTemplate>
        <asp:Label ID="blah" runat="server">Existing Control</asp:Label>
        <asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
    </ItemTemplate>
</asp:TemplateField>

Now, grab the row in the event you want the outlook_id and then access the control.
For RowDataBound access it like:

string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;

Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.

Auto-size dynamic text to fill fixed size container

As much as I love the occasional upvotes I get for this answer (thanks!), this is really not the greatest approach to this problem. Please check out some of the other wonderful answers here, especially the ones that have found solutions without looping.


Still, for the sake of reference, here's my original answer:

<html>
<head>
<style type="text/css">
    #dynamicDiv
    {
    background: #CCCCCC;
    width: 300px;
    height: 100px;
    font-size: 64px;
    overflow: hidden;
    }
</style>

<script type="text/javascript">
    function shrink()
    {
        var textSpan = document.getElementById("dynamicSpan");
        var textDiv = document.getElementById("dynamicDiv");

        textSpan.style.fontSize = 64;

        while(textSpan.offsetHeight > textDiv.offsetHeight)
        {
            textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
        }
    }
</script>

</head>
<body onload="shrink()">
    <div id="dynamicDiv"><span id="dynamicSpan">DYNAMIC FONT</span></div>
</body>
</html>

And here's a version with classes:

<html>
<head>
<style type="text/css">
.dynamicDiv
{
    background: #CCCCCC;
    width: 300px;
    height: 100px;
    font-size: 64px;
    overflow: hidden;
}
</style>

<script type="text/javascript">
    function shrink()
    {
        var textDivs = document.getElementsByClassName("dynamicDiv");
        var textDivsLength = textDivs.length;

        // Loop through all of the dynamic divs on the page
        for(var i=0; i<textDivsLength; i++) {

            var textDiv = textDivs[i];

            // Loop through all of the dynamic spans within the div
            var textSpan = textDiv.getElementsByClassName("dynamicSpan")[0];

            // Use the same looping logic as before
            textSpan.style.fontSize = 64;

            while(textSpan.offsetHeight > textDiv.offsetHeight)
            {
                textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
            }

        }

    }
</script>

</head>
<body onload="shrink()">
    <div class="dynamicDiv"><span class="dynamicSpan">DYNAMIC FONT</span></div>
    <div class="dynamicDiv"><span class="dynamicSpan">ANOTHER DYNAMIC FONT</span></div>
    <div class="dynamicDiv"><span class="dynamicSpan">AND YET ANOTHER DYNAMIC FONT</span></div>
</body>
</html>

Java "?" Operator for checking null - What is it? (Not Ternary!)

That's actually Groovy's safe-dereference operator. You can't use it in pure Java (sadly), so that post is simply wrong (or more likely slightly misleading, if it's claiming Groovy to be the "latest version of Java").

Tools for making latex tables in R

The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.

Function to return only alpha-numeric characters from string?

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

How to hide code from cells in ipython notebook visualized with nbviewer?

jupyter nbconvert yourNotebook.ipynb --no-input --no-prompt

jupyter nbconvert yourNotebook.ipynb This part of the code will take the latex file format of the jupyter notebook and converts it to a html

--no-input This is like a parameter we are saying during conversion that dont add any inputs : here the input to a cell is the code.. so we hide it

--no-prompt Here also we are saying, During conversion dont show any prompts form the code like errors or warnings in the final HTML file ) so that that html will have only the Text and the code output in the form of a report !!..

Hope it helps :)

SASS - use variables across multiple files

Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:

@import 'base/_reset';

@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';

@import 'base/_typography';

@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';

@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';

@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';

@import 'vendors/_ui-grid';

@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';

And you can watch them with gulp/grunt/webpack etc, like:

gulpfile.js

// SASS Task

var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function(){
    return gulp
            .src('sass/**/*.scss')
            .pipe(sourcemaps.init())
            .pipe(sass().on('error', sass.logError))
            .pipe(concat('styles.css'))
            .pipe(uglifycss({
                "maxLineLen": 80,
                "uglyComments": true
            }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest('./build/css/'));
});

gulp.task('watch', function () {
    gulp.watch('sass/**/*.scss', ['styles']);
});

gulp.task('default', ['watch']);

How to check command line parameter in ".bat" file?

You need to check for the parameter being blank: if "%~1"=="" goto blank

Once you've done that, then do an if/else switch on -b: if "%~1"=="-b" (goto specific) else goto unknown

Surrounding the parameters with quotes makes checking for things like blank/empty/missing parameters easier. "~" ensures double quotes are stripped if they were on the command line argument.

What is an OS kernel ? How does it differ from an operating system?

A kernel is the part of the operating system that mediates access to system resources. It's responsible for enabling multiple applications to effectively share the hardware by controlling access to CPU, memory, disk I/O, and networking.

An operating system is the kernel plus applications that enable users to get something done (i.e compiler, text editor, window manager, etc).

What Are Some Good .NET Profilers?

If you're looking for something quick, easy, and free, http://code.google.com/p/slimtune/ seems to do the job fine.

How to atomically delete keys matching a pattern using Redis

Disclaimer: the following solution doesn't provide atomicity.

Starting with v2.8 you really want to use the SCAN command instead of KEYS[1]. The following Bash script demonstrates deletion of keys by pattern:

#!/bin/bash

if [ $# -ne 3 ] 
then
  echo "Delete keys from Redis matching a pattern using SCAN & DEL"
  echo "Usage: $0 <host> <port> <pattern>"
  exit 1
fi

cursor=-1
keys=""

while [ $cursor -ne 0 ]; do
  if [ $cursor -eq -1 ]
  then
    cursor=0
  fi

  reply=`redis-cli -h $1 -p $2 SCAN $cursor MATCH $3`
  cursor=`expr "$reply" : '\([0-9]*[0-9 ]\)'`
  keys=${reply##[0-9]*[0-9 ]}
  redis-cli -h $1 -p $2 DEL $keys
done

[1] KEYS is a dangerous command that can potentially result in a DoS. The following is a quote from its documentation page:

Warning: consider KEYS as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace, consider using sets.

UPDATE: a one liner for the same basic effect -

$ redis-cli --scan --pattern "*:foo:bar:*" | xargs -L 100 redis-cli DEL

Gradle Build Android Project "Could not resolve all dependencies" error

Go to wherever you installed Android Studio (for me it's under C:\Users\username\AppData\Local\Android\android-studio\) and open sdk\tools, then run android.bat. From here, update and download any missing build-tools and make sure you update the Android Support Repository and Android Support Library under Extras. Restart Android Studio after the SDK Manager finishes.

It seems that Android Studio completely ignores any installed Android SDK files and keeps a copy of its own. After running an update, everything compiled successfully for me using compile com.android.support:appcompat-v7:18.0.+

Detecting an undefined object property

Review

A lot of the given answers give a wrong result because they do not distinguish between the case when an object property does not exist and the case when a property has value undefined. Here is proof for most popular solutions:

_x000D_
_x000D_
let obj = {
  a: 666,
  u: undefined // The 'u' property has value 'undefined'
               // The 'x' property does not exist
}

console.log('>>> good results:');
console.log('A', "u" in obj, "x" in obj);
console.log('B', obj.hasOwnProperty("u"),      obj.hasOwnProperty("x"));

console.log('\n>>> bad results:');
console.log('C', obj.u === undefined,          obj.x === undefined);
console.log('D', obj.u == undefined,           obj.x == undefined);
console.log('E', obj["u"] === undefined,       obj["x"] === undefined);
console.log('F', obj["u"] == undefined,        obj["x"] == undefined);
console.log('G', !obj.u,                      !obj.x);
console.log('H', typeof obj.u === 'undefined', typeof obj.x === 'undefined');
_x000D_
_x000D_
_x000D_

Is optimisation level -O3 dangerous in g++?

In my somewhat checkered experience, applying -O3 to an entire program almost always makes it slower (relative to -O2), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2 relative to -Os!

The intended use pattern for -O3 is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3 optimizations to hot functions -- effectively automating this process.

Right way to write JSON deserializer in Spring or extend it

With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.

Dont use this

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

Use this instead.

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>  

Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson

What exactly is LLVM?

LLVM (used to mean "Low Level Virtual Machine" but not anymore) is a compiler infrastructure, written in C++, which is designed for compile-time, link-time, run-time, and "idle-time" optimization of programs written in arbitrary programming languages. Originally implemented for C/C++, the language-independent design (and the success) of LLVM has since spawned a wide variety of front-ends, including Objective C, Fortran, Ada, Haskell, Java bytecode, Python, Ruby, ActionScript, GLSL, and others.

Read this for more explanation
Also check out Unladen Swallow

Removing fields from struct or hiding them in JSON Response

I just published sheriff, which transforms structs to a map based on tags annotated on the struct fields. You can then marshal (JSON or others) the generated map. It probably doesn't allow you to only serialize the set of fields the caller requested, but I imagine using a set of groups would allow you to cover most cases. Using groups instead of the fields directly would most likely also increase cache-ability.

Example:

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/hashicorp/go-version"
    "github.com/liip/sheriff"
)

type User struct {
    Username string   `json:"username" groups:"api"`
    Email    string   `json:"email" groups:"personal"`
    Name     string   `json:"name" groups:"api"`
    Roles    []string `json:"roles" groups:"api" since:"2"`
}

func main() {
    user := User{
        Username: "alice",
        Email:    "[email protected]",
        Name:     "Alice",
        Roles:    []string{"user", "admin"},
    }

    v2, err := version.NewVersion("2.0.0")
    if err != nil {
        log.Panic(err)
    }

    o := &sheriff.Options{
        Groups:     []string{"api"},
        ApiVersion: v2,
    }

    data, err := sheriff.Marshal(o, user)
    if err != nil {
        log.Panic(err)
    }

    output, err := json.MarshalIndent(data, "", "  ")
    if err != nil {
        log.Panic(err)
    }
    fmt.Printf("%s", output)
}

How can I get file extensions with JavaScript?

If you are dealing with web urls, you can use:

function getExt(filepath){
     return filepath.split("?")[0].split("#")[0].split('.').pop();
}

getExt("../js/logic.v2.min.js") // js
getExt("http://example.net/site/page.php?id=16548") // php
getExt("http://example.net/site/page.html#welcome.to.me") // html
getExt("c:\\logs\\yesterday.log"); // log

Demo: https://jsfiddle.net/squadjot/q5ard4fj/

Postgres integer arrays as parameters?

I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,

SELECT * FROM some_table WHERE id_column = ANY(@id_list)

where @id_list is bound to an int[] parameter by way of

command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;

where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).

How do I get monitor resolution in Python?

In case you have PyQt4 installed, try the following code:

from PyQt4 import QtGui
import sys

MyApp = QtGui.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))

For PyQt5, the following will work:

from PyQt5 import QtWidgets
import sys

MyApp = QtWidgets.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))

What is the Swift equivalent of respondsToSelector?

I guess you want to make a default implementation for delegate. You can do this:

let defaultHandler = {}
(delegate?.method ?? defaultHandler)()

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

Differences in string compare methods in C#

Using .Equals is also a lot easier to read.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

How to set text size of textview dynamically for different screens

In Style.xml pre-define the style:

<style name="largeText">
    <item name="android:textAppearance">@android:style/TextAppearance.Large.Inverse</item>
    <item name="android:textStyle">bold</item>
</style>

in code:

text.setTextAppearance(context, R.style.largeText);

Convert a String of Hex into ASCII in Java

Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
    String str = hex.substring(i, i+2);
    output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);

Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

System.out.println(Arrays
        .stream(hex.split("(?<=\\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
        .map(s -> Character.toString((char)Integer.parseInt(s, 16)))
        .collect(Collectors.joining()));

Either way, this gives a few lines starting with the following:

uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3

Hmmm... :-)

Accessing an SQLite Database in Swift

Sometimes, a Swift version of the "SQLite in 5 minutes or less" approach shown on sqlite.org is sufficient. The "5 minutes or less" approach uses sqlite3_exec() which is a convenience wrapper for sqlite3_prepare(), sqlite3_step(), sqlite3_column(), and sqlite3_finalize().

Swift 2.2 can directly support the sqlite3_exec() callback function pointer as either a global, non-instance procedure func or a non-capturing literal closure {}.

Readable typealias

typealias sqlite3 = COpaquePointer
typealias CCharHandle = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>
typealias CCharPointer = UnsafeMutablePointer<CChar>
typealias CVoidPointer = UnsafeMutablePointer<Void>

Callback Approach

func callback(
    resultVoidPointer: CVoidPointer, // void *NotUsed 
    columnCount: CInt,               // int argc
    values: CCharHandle,             // char **argv     
    columns: CCharHandle             // char **azColName
    ) -> CInt {
    for  i in 0 ..< Int(columnCount) {
        guard let value = String.fromCString(values[i]) 
        else { continue }
        guard let column = String.fromCString(columns[i]) 
        else { continue }
        print("\(column) = \(value)")
    }
    return 0 // status ok
}

func sqlQueryCallbackBasic(argc: Int, argv: [String]) -> Int {
    var db: sqlite3 = nil 
    var zErrMsg:CCharPointer = nil
    var rc: Int32 = 0 // result code

    if argc != 3 {
        print(String(format: "ERROR: Usage: %s DATABASE SQL-STATEMENT", argv[0]))
        return 1
    }

    rc = sqlite3_open(argv[1], &db)
    if  rc != 0 {
        print("ERROR: sqlite3_open " + String.fromCString(sqlite3_errmsg(db))! ?? "" )
        sqlite3_close(db)
        return 1
    }

    rc = sqlite3_exec(db, argv[2], callback, nil, &zErrMsg)
    if rc != SQLITE_OK {
        print("ERROR: sqlite3_exec " + String.fromCString(zErrMsg)! ?? "")
        sqlite3_free(zErrMsg)
    }

    sqlite3_close(db)
    return 0
}

Closure Approach

func sqlQueryClosureBasic(argc argc: Int, argv: [String]) -> Int {
    var db: sqlite3 = nil 
    var zErrMsg:CCharPointer = nil
    var rc: Int32 = 0

    if argc != 3 {
        print(String(format: "ERROR: Usage: %s DATABASE SQL-STATEMENT", argv[0]))
        return 1
    }

    rc = sqlite3_open(argv[1], &db)
    if  rc != 0 {
        print("ERROR: sqlite3_open " + String.fromCString(sqlite3_errmsg(db))! ?? "" )
        sqlite3_close(db)
        return 1
    }

    rc = sqlite3_exec(
        db,      // database 
        argv[2], // statement
        {        // callback: non-capturing closure
            resultVoidPointer, columnCount, values, columns in

            for i in 0 ..< Int(columnCount) {
                guard let value = String.fromCString(values[i]) 
                else { continue }
                guard let column = String.fromCString(columns[i]) 
                else { continue }
                print("\(column) = \(value)")
            }
            return 0
        }, 
        nil, 
        &zErrMsg
    )

    if rc != SQLITE_OK {
        let errorMsg = String.fromCString(zErrMsg)! ?? ""
        print("ERROR: sqlite3_exec \(errorMsg)")
        sqlite3_free(zErrMsg)
    }
    sqlite3_close(db)
    return 0
}

To prepare an Xcode project to call a C library such as SQLite, one needs to (1) add a Bridging-Header.h file reference C headers like #import "sqlite3.h", (2) add Bridging-Header.h to Objective-C Bridging Header in project settings, and (3) add libsqlite3.tbd to Link Binary With Library target settings.

The sqlite.org's "SQLite in 5 minutes or less" example is implemented in a Swift Xcode7 project here.

How to fill the whole canvas with specific color?

We don't need to access the canvas context.

Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8'). But my preferred method requires converting the kabab-case to camelCase.

canvas.style.backgroundColor = '#00F8'

Max or Default?

litt late, but I had the same concern...

Rephrasing your code from the original post, you want the max of the set S defined by

(From y In context.MyTable _
 Where y.MyField = value _
 Select y.MyCounter)

Taking in account your last comment

Suffice to say that I know I want 0 when there are no records to select from, which definitely has an impact on the eventual solution

I can rephrase your problem as: You want the max of {0 + S}. And it looks like the proposed solution with concat is semantically the right one :-)

var max = new[]{0}
          .Concat((From y In context.MyTable _
                   Where y.MyField = value _
                   Select y.MyCounter))
          .Max();

Powershell: Get FQDN Hostname

A cleaner format FQDN remotely

[System.Net.Dns]::GetHostByName('remotehost').HostName

JQuery Redirect to URL after specified time

You can use

    $(document).ready(function(){
      setTimeout(function() {
       window.location.href = "http://test.example.com/;"
      }, 5000);
    });

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Try adding below code in build.gradle, it worked for me -

compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    multiDexEnabled true
}

How to insert values in two dimensional array programmatically?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

But you can chain the index operator for array element access.

String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];

x[0][0] = "a1";
    // No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";

Note the dimensions of the child arrays don't need to match.

PHP: How to remove all non printable characters in a string?

My UTF-8 compliant version:

preg_replace('/[^\p{L}\s]/u','',$value);

How to redirect back to form with input - Laravel 5

You can use the following:

return Redirect::back()->withInput(Input::all());

If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.

Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:

return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());

Reading from text file until EOF repeats last line

I like this example, which for now, leaves out the check which you could add inside the while block:

ifstream iFile("input.txt");        // input.txt has integers, one per line
int x;

while (iFile >> x) 
{
    cerr << x << endl;
}

Not sure how safe it is...

Throw keyword in function's signature

A no throw specification on an inlined function that only returns a member variable and could not possibly throw exceptions may be used by some compilers to do pessimizations (a made-up word for the opposite of optimizations) that can have a detrimental effect on performance. This is described in the Boost literature: Exception-specification

With some compilers a no-throw specification on non-inline functions may be beneficial if the correct optimizations are made and the use of that function impacts performance in a way that it justifies it.

To me it sounds like whether to use it or not is a call made by a very critical eye as part of a performance optimization effort, perhaps using profiling tools.

A quote from the above link for those in a hurry (contains an example of bad unintended effects of specifying throw on an inline function from a naive compiler):

Exception-specification rationale

Exception specifications [ISO 15.4] are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:

T& operator*() const throw() { return *ptr; }

This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.

For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.

Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.

A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.

Make A List Item Clickable (HTML/CSS)

Here is a working solution - http://jsfiddle.net/STTaf/

I used simple jQuery:

$(function() {
    $('li').css('cursor', 'pointer')

    .click(function() {
        window.location = $('a', this).attr('href');
        return false;
    });
});

TCPDF output without saving file

Use I for "inline" to send the PDF to the browser, opposed to F to save it as a file.

$pdf->Output('name.pdf', 'I');

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.

jQuery:

$(function(){
   $("#innerContainer").hover(
        function(){
            $("#innerContainer").css('border-color','#FFF');
            $("#outerContainer").css('border-color','#FFF');
        },
        function(){
            $("#innerContainer").css('border-color','#000');
            $("#outerContainer").css('border-color','#000');
        }
    );
});

Adjust the values and element id's accordingly :)

How to plot a function curve in R

You mean like this?

> eq = function(x){x*x}
> plot(eq(1:1000), type='l')

Plot of eq over range 1:1000

(Or whatever range of values is relevant to your function)

How can I align all elements to the left in JPanel?

You should use setAlignmentX(..) on components you want to align, not on the container that has them..

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);

c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);

Printing everything except the first field with awk

Maybe the most concise way:

$ awk '{$(NF+1)=$1;$1=""}sub(FS,"")' infile
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN

Explanation:

$(NF+1)=$1: Generator of a "new" last field.

$1="": Set the original first field to null

sub(FS,""): After the first two actions {$(NF+1)=$1;$1=""} get rid of the first field separator by using sub. The final print is implicit.

Toggle visibility property of div

There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.

Example:

function toggleVideo() {
     var e = document.getElementById('video-over');

     if(e.style.visibility == 'visible') {
          e.style.visibility = 'hidden';
     } else if(e.style.visibility == 'hidden') {
          e.style.visibility = 'visible';
     }
}

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

You only need to delete one folder it is throwing error for. Just go to your M2 repo and org/apache/maven/plugins/maven-compiler-plugins and delete the folder 2.3.2

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

How to connect a Windows Mobile PDA to Windows 10

Here is the answer: Download the "Windows Mobile Device Center" for your machine type, likely 64bit.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3182

Before you run the install, change the compatibility settings to 'Windows 7'. Then install it... Then run it: You'll find it under 'WMDC'.. Your device should now recognize, when plugged in, mine did!

Use '=' or LIKE to compare strings in SQL?

LIKE does matching like wildcards char [*, ?] at the shell
LIKE '%suffix' - give me everything that ends with suffix. You couldn't do that with =
Depends on the case actually.

DataAdapter.Fill(Dataset)

leDbConnection connection = 
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();

OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*,  tbl_Besitzer.*
  FROM tbl_Computer 
  INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
  WHERE (((tbl_Besitzer.Vorname)='ma'));", 
connection);

Understanding checked vs unchecked exceptions in Java

  • Java distinguishes between two categories of exceptions (checked & unchecked).
  • Java enforces a catch or declared requirement for checked exceptions.
  • An exception's type determines whether an exception is checked or unchecked.
  • All exception types that are direct or indirect subclasses of class RuntimeException are unchecked exception.
  • All classes that inherit from class Exception but not RuntimeException are considered to be checked exceptions.
  • Classes that inherit from class Error are considered to be unchecked.
  • Compiler checks each method call and deceleration to determine whether the method throws checked exception.
    • If so the compiler ensures the exception is caught or is declared in a throws clause.
  • To satisfy the declare part of the catch-or-declare requirement, the method that generates the exception must provide a throws clause containing the checked-exception.
  • Exception classes are defined to be checked when they are considered important enough to catch or declare.

Gridview get Checkbox.Checked value

    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
        if (chkbox.Checked == true)
        {
            // Your Code
        }
    }

LINQ - Full Outer Join

Yet another full outer join

As was not that happy with the simplicity and the readability of the other propositions, I ended up with this :

It does not have the pretension to be fast ( about 800 ms to join 1000 * 1000 on a 2020m CPU : 2.4ghz / 2cores). To me, it is just a compact and casual full outer join.

It works the same as a SQL FULL OUTER JOIN (duplicates conservation)

Cheers ;-)

using System;
using System.Collections.Generic;
using System.Linq;
namespace NS
{
public static class DataReunion
{
    public static List<Tuple<T1, T2>> FullJoin<T1, T2, TKey>(List<T1> List1, Func<T1, TKey> KeyFunc1, List<T2> List2, Func<T2, TKey> KeyFunc2)
    {
        List<Tuple<T1, T2>> result = new List<Tuple<T1, T2>>();

        Tuple<TKey, T1>[] identifiedList1 = List1.Select(_ => Tuple.Create(KeyFunc1(_), _)).OrderBy(_ => _.Item1).ToArray();
        Tuple<TKey, T2>[] identifiedList2 = List2.Select(_ => Tuple.Create(KeyFunc2(_), _)).OrderBy(_ => _.Item1).ToArray();

        identifiedList1.Where(_ => !identifiedList2.Select(__ => __.Item1).Contains(_.Item1)).ToList().ForEach(_ => {
            result.Add(Tuple.Create<T1, T2>(_.Item2, default(T2)));
        });

        result.AddRange(
            identifiedList1.Join(identifiedList2, left => left.Item1, right => right.Item1, (left, right) => Tuple.Create<T1, T2>(left.Item2, right.Item2)).ToList()
        );

        identifiedList2.Where(_ => !identifiedList1.Select(__ => __.Item1).Contains(_.Item1)).ToList().ForEach(_ => {
            result.Add(Tuple.Create<T1, T2>(default(T1), _.Item2));
        });

        return result;
    }
}
}

The idea is to

  1. Build Ids based on provided key function builders
  2. Process left only items
  3. Process inner join
  4. Process right only items

Here is a succinct test that goes with it :

Place a break point at the end to manually verify that it behaves as expected

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NS;

namespace Tests
{
[TestClass]
public class DataReunionTest
{
    [TestMethod]
    public void Test()
    {
        List<Tuple<Int32, Int32, String>> A = new List<Tuple<Int32, Int32, String>>();
        List<Tuple<Int32, Int32, String>> B = new List<Tuple<Int32, Int32, String>>();

        Random rnd = new Random();

        /* Comment the testing block you do not want to run
        /* Solution to test a wide range of keys*/

        for (int i = 0; i < 500; i += 1)
        {
            A.Add(Tuple.Create(rnd.Next(1, 101), rnd.Next(1, 101), "A"));
            B.Add(Tuple.Create(rnd.Next(1, 101), rnd.Next(1, 101), "B"));
        }

        /* Solution for essential testing*/

        A.Add(Tuple.Create(1, 2, "B11"));
        A.Add(Tuple.Create(1, 2, "B12"));
        A.Add(Tuple.Create(1, 3, "C11"));
        A.Add(Tuple.Create(1, 3, "C12"));
        A.Add(Tuple.Create(1, 3, "C13"));
        A.Add(Tuple.Create(1, 4, "D1"));

        B.Add(Tuple.Create(1, 1, "A21"));
        B.Add(Tuple.Create(1, 1, "A22"));
        B.Add(Tuple.Create(1, 1, "A23"));
        B.Add(Tuple.Create(1, 2, "B21"));
        B.Add(Tuple.Create(1, 2, "B22"));
        B.Add(Tuple.Create(1, 2, "B23"));
        B.Add(Tuple.Create(1, 3, "C2"));
        B.Add(Tuple.Create(1, 5, "E2"));

        Func<Tuple<Int32, Int32, String>, Tuple<Int32, Int32>> key = (_) => Tuple.Create(_.Item1, _.Item2);

        var watch = System.Diagnostics.Stopwatch.StartNew();
        var res = DataReunion.FullJoin(A, key, B, key);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        String aser = JToken.FromObject(res).ToString(Formatting.Indented);
        Console.Write(elapsedMs);
    }
}

}

What is "android.R.layout.simple_list_item_1"?

No need to go to external links, everything you need is located on your computer already:

Android\android-sdk\platforms\android-x\data\res\layout.

Source code for all android layouts are located here.

SQL Query - Using Order By in UNION

SELECT field1
FROM ( SELECT field1 FROM table1
       UNION
       SELECT field1 FROM table2
     ) AS TBL
ORDER BY TBL.field1

(use ALIAS)

How to have stored properties in Swift, the same way I had on Objective-C?

if you are looking to set a custom string attribute to a UIView, this is how I did it on Swift 4

Create a UIView extension

extension UIView {

    func setStringValue(value: String, key: String) {
        layer.setValue(value, forKey: key)
    }

    func stringValueFor(key: String) -> String? {
        return layer.value(forKey: key) as? String
    }
}

To use this extension

let key = "COLOR"

let redView = UIView() 

// To set
redView.setStringAttribute(value: "Red", key: key)

// To read
print(redView.stringValueFor(key: key)) // Optional("Red")

Debugging with command-line parameters in Visual Studio

The Mozilla.org FAQ on debugging Mozilla on Windows is of interest here.

In short, the Visual Studio debugger can be invoked on a program from the command line, allowing one to specify the command line arguments when invoking a command line program, directly on the command line.

This looks like the following for Visual Studio 8 or 9 (Visual Studio 2005 or Visual Studio 2008, respectively)

  devenv /debugexe 'program name' 'program arguments'

It is also possible to have an explorer action to start a program in the Visual Studio debugger.

Target Unreachable, identifier resolved to null in JSF 2.2

  1. You need

    @ManagedBean(name="userBean")

  2. Make sure you have getUser() method.

  3. Type of setUser() method should be void.

  4. Make sure that User class has proper setters and getters as well.

How do I solve the INSTALL_FAILED_DEXOPT error?

As this seems to be a problem I have myself encountered multiple times and this time none of the shared solutions helped me, I'll still post what helped me personally and what I believe may help someone else in future:

Go to your project's directory and find build/intermediates/dex-cache/cache file. Remove it - as name suggests, it's a cached dex file that may be outdated if you have made changes to your project's dependencies, build tools version etc.

Python function overloading

Either use multiple keyword arguments in the definition, or create a Bullet hierarchy whose instances are passed to the function.

Replacing Numpy elements if condition is met

I am not sure I understood your question, but if you write:

mask_data[:3, :3] = 1
mask_data[3:, 3:] = 0

This will make all values of mask data whose x and y indexes are less than 3 to be equal to 1 and all rest to be equal to 0

How to skip a iteration/loop in while-loop

while (rs.next())
{
  if (f.exists() && !f.isDirectory())
    continue;

  //proceed
}

How to remove the first character of string in PHP?

Trims occurrences of every word in an array from the beginning and end of a string + whitespace and optionally extra single characters as per normal trim()

<?php
function trim_words($what, $words, $char_list = '') {
    if(!is_array($words)) return false;
    $char_list .= " \t\n\r\0\x0B"; // default trim chars
    $pattern = "(".implode("|", array_map('preg_quote', $words)).")\b";
    $str = trim(preg_replace('~'.$pattern.'$~i', '', preg_replace('~^'.$pattern.'~i', '', trim($what, $char_list))), $char_list);
    return $str;
}

// for example:
$trim_list = array('AND', 'OR');

$what = ' OR x = 1 AND b = 2 AND ';
print_r(trim_words($what, $trim_list)); // => "x = 1 AND b = 2"

$what = ' ORDER BY x DESC, b ASC, ';
print_r(trim_words($what, $trim_list, ',')); // => "ORDER BY x DESC, b ASC"
?>

What is __declspec and when do I need to use it?

I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec() can bee used at the same level as the export keyword.

/** Declare a public MRuby API function. */
#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif