Programs & Examples On #Django project architect

What is the correct JSON content type?

Extending the accepted responses, when you are using JSON in a REST context...

There is a strong argument about using application/x-resource+json and application/x-collection+json when you are representing REST resources and collections.

And if you decide to follow the jsonapi specification, you should use of application/vnd.api+json, as it is documented.

Altough there is not an universal standard, it is clear that the added semantic to the resources being transfered justify a more explicit Content-Type than just application/json.

Following this reasoning, other contexts could justify a more specific Content-Type.

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

Run C++ in command prompt - Windows

  • first Command is :

g++ -o program file_name.cpp

  • Second command is :

.\program.exe

Let us Check this image

How to open adb and use it to send commands

The adb tool can be found in sdk/platform-tools/

If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"

Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

Add placeholder text inside UITextView in Swift?

I like @nerdist's solution. Based on that, I created an extension to UITextView:

import Foundation
import UIKit

extension UITextView
{
  private func add(_ placeholder: UILabel) {
    for view in self.subviews {
        if let lbl = view as? UILabel  {
            if lbl.text == placeholder.text {
                lbl.removeFromSuperview()
            }
        }
    }
    self.addSubview(placeholder)
  }

  func addPlaceholder(_ placeholder: UILabel?) {
    if let ph = placeholder {
      ph.numberOfLines = 0  // support for multiple lines
      ph.font = UIFont.italicSystemFont(ofSize: (self.font?.pointSize)!)
      ph.sizeToFit()
      self.add(ph)
      ph.frame.origin = CGPoint(x: 5, y: (self.font?.pointSize)! / 2)
      ph.textColor = UIColor(white: 0, alpha: 0.3)
      updateVisibility(ph)
    }
  }

  func updateVisibility(_ placeHolder: UILabel?) {
    if let ph = placeHolder {
      ph.isHidden = !self.text.isEmpty
    }
  }
}

In a ViewController class, for example, this is how I use it:

class MyViewController: UIViewController, UITextViewDelegate {
  private var notePlaceholder: UILabel!
  @IBOutlet weak var txtNote: UITextView!
  ...
  // UIViewController
  override func viewDidLoad() {
    notePlaceholder = UILabel()
    notePlaceholder.text = "title\nsubtitle\nmore..."
    txtNote.addPlaceholder(notePlaceholder)
    ...
  }

  // UITextViewDelegate
  func textViewDidChange(_ textView: UITextView) {
    txtNote.updateVisbility(notePlaceholder)
    ...
  }

Placeholder on UITextview!

enter image description here

UPDATE:

In case you change textview's text in code, remember to call updateVisibitly method to hide placeholder:

txtNote.text = "something in code"
txtNote.updateVisibility(self.notePlaceholder) // hide placeholder if text is not empty.

To prevent the placeholder being added more than once, a private add() function is added in extension.

How to config Tomcat to serve images from an external folder outside webapps?

You could have a redirect servlet. In you web.xml you'd have:

<servlet>
    <servlet-name>images</servlet-name>
    <servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>images</servlet-name>
    <url-pattern>/images/*</url-pattern>
</servlet-mapping>

All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif".... In the servlet, HttpServletRequest.getPathInfo() would yield "/smilie.gif". Which the servlet would find in the folder.

How do I break a string across more than one line of code in JavaScript?

No need of any manual break in code. Just add \n where you want to break.

alert ("Please Select file \n to delete");

This will show the alert like

Please select file 
to delete.

Entity framework linq query Include() multiple children entities

You might find this article of interest which is available at codeplex.com.

The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.

Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.

Angular ng-repeat add bootstrap row every 3 or 4 cols

You can do it without a directive but i'm not sure it's the best way. To do this you must create array of array from the data you want to display in the table, and after that use 2 ng-repeat to iterate through the array.

to create the array for display use this function like that products.chunk(3)

Array.prototype.chunk = function(chunkSize) {
    var array=this;
    return [].concat.apply([],
        array.map(function(elem,i) {
            return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
        })
    );
}

and then do something like that using 2 ng-repeat

<div class="row" ng-repeat="row in products.chunk(3)">
  <div class="col-sm4" ng-repeat="item in row">
    {{item}}
  </div>
</div>

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

convert datetime to date format dd/mm/yyyy

If you want the string use -

DateTime.ToString("dd/MM/yyyy")

String MinLength and MaxLength validation don't work (asp.net mvc)

    [StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
    [Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
    public string Password { get; set; }

Save resource like this

"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"

Rails: select unique values from a column

If you want to also select extra fields:

Model.select('DISTINCT ON (models.ratings) models.ratings, models.id').map { |m| [m.id, m.ratings] }

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

I don't think you can delete from multiple tables at once (though I'm not certain).

It sounds to me, however, that you would be best to achieve this effect with a relationship that cascades deletes. If you did this you would be able to delete the record from one table and the records in the other would be automatically deleted.

As an example, say the two tables represent a customer, and the customer's orders. If you setup the relationship to cascade deletes, you could simply delete record in the customer table, and the orders would get deleted automatically.

See the MSDN doc on cascading referential integrity constraints.

How to save select query results within temporary table?

You can also do the following:

CREATE TABLE #TEMPTABLE
(
    Column1 type1,
    Column2 type2,
    Column3 type3
)

INSERT INTO #TEMPTABLE
SELECT ...

SELECT *
FROM #TEMPTABLE ...

DROP TABLE #TEMPTABLE

Where does flask look for image files?

It took me a while to figure this out too. url_for in Flask looks for endpoints that you specified in the routes.py script.

So if you have a decorator in your routes.py file like @blah.route('/folder.subfolder') then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }} . The 'folder.subfolder' argument sends it to a Flask endpoint it recognizes.

However let us say that you stored your image file, some_image.jpg, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py, your route decorator looks like @blah.routes('/folder'). You then have to ask for your image file this way: {{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}

I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.

How do I add a tool tip to a span element?

Here's the simple, built-in way:

<span title="My tip">text</span>

That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.

Codeigniter LIKE with wildcard(%)

I'm using

$this->db->query("SELECT * FROM film WHERE film.title LIKE '%$query%'"); for such purposes

LISTAGG function: "result of string concatenation is too long"

We were able to solve a similar issue here using Oracle LISTAGG. There was a point where what we were grouping on exceeded the 4K limit but this was easily solved by having the first dataset take the first 15 items to aggregate, each of which have a 256K limit.

More info: We have projects, which have change orders, which in turn have explanations. Why the database is set up to take change text in chunks of 256K limits is not known but its one of the design constraints. So the application that feeds change explanations into the table stops at 254K and inserts, then gets the next set of text and if > 254K generates another row, etc. So we have a project to a change order, a 1:1. Then we have these as 1:n for explanations. LISTAGG concatenates all these. We have RMRKS_SN values, 1 for each remark and/or for each 254K of characters.

The largest RMRKS_SN was found to be 31, so I did the first dataset pulling SN 0 to 15, the 2nd dataset 16 to 30 and the last dataset 31 to 45 -- hey, let's plan on someone adding a LOT of explanation to some change orders!

In the SQL report, the Tablix ties to the first dataset. To get the other data, here's the expression:

=First(Fields!NON_STD_TXT.Value, "DataSet_EXPLAN") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_16_TO_30") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_31_TO_45")

For us, we have to have DB Group create functions, etc. because of security constraints. So with a bit of creativity, we didn't have to do a User Aggregate or a UDF.

If your application has some sort of SN to aggregate by, this method should work. I don't know what the equivalent TSQL is -- we're fortunate to be dealing with Oracle for this report, for which LISTAGG is a Godsend.

The code is:

SELECT
LT.C_O_NBR AS LT_CO_NUM,
RT.C_O_NBR AS RT_CO_NUM,
LT.STD_LN_ITM_NBR, 
RT.NON_STD_LN_ITM_NBR,
RT.NON_STD_PRJ_NBR, 
LT.STD_PRJ_NBR, 
NVL(LT.PRPSL_LN_NBR, RT.PRPSL_LN_NBR) AS PRPSL_LN_NBR,
LT.STD_CO_EXPL_TXT AS STD_TXT,
LT.STD_CO_EXPLN_T, 
LT.STD_CO_EXPL_SN, 
RT.NON_STD_CO_EXPLN_T,
LISTAGG(RT.RMRKS_TXT_FLD, '') 
    WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT

FROM ...

    WHERE RT.RMRKS_SN BETWEEN 0 AND 15

GROUP BY 
    LT.C_O_NBR,
    RT.C_O_NBR,
    ...

And in the other 2 datasets just select the LISTAGG only for the subqueries in the FROM:

SELECT
LISTAGG(RT.RMRKS_TXT_FLD, '') 
    WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT

FROM ...

WHERE RT.RMRKS_SN BETWEEN 31 AND 45

...

... and so on.

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

do { ... } while (0) — what is it good for?

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)

if (condition)
    FOO(x);
else // syntax error here
    ...;

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); }

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)
    FOO(x)
else
    ...

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

then the following is syntactically correct:

if (condition)
    FOO(x);
else
    ....

Create JSON object dynamically via JavaScript (Without concate strings)

Perhaps this information will help you.

_x000D_
_x000D_
var sitePersonel = {};_x000D_
var employees = []_x000D_
sitePersonel.employees = employees;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var firstName = "John";_x000D_
var lastName = "Smith";_x000D_
var employee = {_x000D_
  "firstName": firstName,_x000D_
  "lastName": lastName_x000D_
}_x000D_
sitePersonel.employees.push(employee);_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var manager = "Jane Doe";_x000D_
sitePersonel.employees[0].manager = manager;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
console.log(JSON.stringify(sitePersonel));
_x000D_
_x000D_
_x000D_

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

Your listener.ora is misconfigured. There is no orcl service.

Typedef function pointer?

Without the typedef word, in C++ the declaration would declare a variable FunctionFunc of type pointer to function of no arguments, returning void.

With the typedef it instead defines FunctionFunc as a name for that type.

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I had the same problem with Eclipse 3.4(Ganymede) and dynamic web project.
The message didn't influence successfull deploy.But I had to delete row

<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>

from org.eclipse.wst.common.component file in .settings folder of Eclipse

How To Make Circle Custom Progress Bar in Android

I'd make a new view class and derive from the existing ProgressBar. Then override the onDraw function. You're going to need to make direct draw calls to the canvas for this, since its so custom- a combination of drawText, drawArc, and drawOval should do it- an oval for the outer ring and empty portions, and an arc for the colored in parts. You may end up needing to override onMeasure and onLayout as well. Then in your xml, reference this view by class name like this when you want to use it.

How to populate HTML dropdown list with values from database

I'd suggest following a few debugging steps.

First run the query directly against the DB. Confirm it is bringing results back. Even with something as simple as this you can find you've made a mistake, or the table is empty, or somesuch oddity.

If the above is ok, then try looping and echoing out the contents of $row just directly into the HTML to see what you've getting back in the mysql_query - see if it matches what you got directly in the DB.

If your data is output onto the page, then look at what's going wrong in your HTML formatting.

However, if nothing is output from $row, then figure out why the mysql_query isn't working e.g. does the user have permission to query that DB, do you have an open DB connection, can the webserver connect to the DB etc [something on these lines can often be a gotcha]

Changing your query slightly to

$sql = mysql_query("SELECT username FROM users") or die(mysql_error());  

may help to highlight any errors: php manual

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

How do I increase modal width in Angular UI Bootstrap?

If you want to just go with the default large size you can add 'modal-lg':

var modal = $modal.open({
          templateUrl: "/partials/welcome",
          controller: "welcomeCtrl",
          backdrop: "static",
          scope: $scope,
          windowClass: 'modal-lg'
});

Double precision - decimal places

An IEEE double has 53 significant bits (that's the value of DBL_MANT_DIG in <cfloat>). That's approximately 15.95 decimal digits (log10(253)); the implementation sets DBL_DIG to 15, not 16, because it has to round down. So you have nearly an extra decimal digit of precision (beyond what's implied by DBL_DIG==15) because of that.

The nextafter() function computes the nearest representable number to a given number; it can be used to show just how precise a given number is.

This program:

#include <cstdio>
#include <cfloat>
#include <cmath>

int main() {
    double x = 1.0/7.0;
    printf("FLT_RADIX = %d\n", FLT_RADIX);
    printf("DBL_DIG = %d\n", DBL_DIG);
    printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
    printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}

gives me this output on my system:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.14285714285714282
0.14285714285714285
0.14285714285714288

(You can replace %.17g by, say, %.64g to see more digits, none of which are significant.)

As you can see, the last displayed decimal digit changes by 3 with each consecutive value. The fact that the last displayed digit of 1.0/7.0 (5) happens to match the mathematical value is largely coincidental; it was a lucky guess. And the correct rounded digit is 6, not 5. Replacing 1.0/7.0 by 1.0/3.0 gives this output:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.33333333333333326
0.33333333333333331
0.33333333333333337

which shows about 16 decimal digits of precision, as you'd expect.

Artificially create a connection timeout error

You might install Microsoft Loopback driver that will create a separate interface for you. Then you can connect on it to some service of yours (your own host). Then in Network Connections you can disable/enable such interface...

Can the Android layout folder contain subfolders?

I use Android File Grouping plugin for Android Studio.It doesn't really allows you to create sub-folders, but it can DISPLAY your files and resources AS they are in different folders. And this is exactly what I wanted.

You can install "Android File Grouping" plugin by

Windows:

Android Studio -> File -> Settings -> Plugins.

Mac:

Android Studio -> Android Studio Tab (Top Left) -> Preferences -> Plugins -> Install JetBrains Plugin..

For Mac, I was able to test it and was not able to search for the plugin. So I downloaded the plugin from here and used the Install plugin from disk option from the above setting.

How to display image from URL on Android

You can try with Picasso, it's really nice and easy. Don't forget to add the permissions in the manifest.

Picasso.with(context)
                     .load("http://ImageURL")
                     .resize(width,height)
                     .into(imageView );

You can also take a look at a tutorial here : Youtube / Github

exception in thread 'main' java.lang.NoClassDefFoundError:

Run it like this:

java -jar HelloWorld.jar

How to set background color of view transparent in React Native

Use rgba value for the backgroundColor.

For example,

backgroundColor: 'rgba(52, 52, 52, 0.8)'

This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, 0.8. This value can be anything from 0.0 to 1.0.

Setting up SSL on a local xampp/apache server

I have been through all the answers and tutorials over the internet but here are the basic steps to enable SSL (https) on localhost with XAMPP:

Required:

  1. Run -> "C:\xampp\apache\makecert.bat" (double-click on windows) Fill passowords of your choice, hit Enter for everything BUT define "localhost"!!! Be careful when asked here:

    Common Name (e.g. server FQDN or YOUR name) []:localhost

    (Certificates are issued per domain name zone only!)

  2. Restart apache
  3. Chrome -> Settings -> Search "Certificate" -> Manage Certificates -> Trusted Root Certification Authorities -> Import -> "C:\xampp\apache\conf\ssl.crt\server.crt" -> Must Ask "YES" for confirmation!
  4. https://localhost/testssl.php -> [OK, Now Green!] (any html test file)

Optional: (if above doesn't work, do more of these steps)

  1. Run XAMPP As admin (Start -> XAMPP -> right-click -> Run As Administrator)
  2. XAMPP -> Apache -> Config -> httpd.conf ("C:\xampp\apache\conf\httpd.conf")

    LoadModule ssl_module modules/mod_ssl.so (remove # form the start of line)

  3. XAMPP -> Apache -> Config -> php.ini ("C:\xampp\php\php.ini")

    extension=php_openssl.dll (remove ; from the start of line)

  4. Restart apache and chrome!

Check any problems or the status of your certificate:

Chrome -> F12 -> Security -> View Certificate

git push rejected

If push request is shows Rejected, then try first pull from your github account and then try push.

Ex:

In my case it was giving an error-

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ashif8984/git-github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

****So what I did was-****

$ git pull
$ git push

And the code was pushed successfully into my Github Account.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

TRANSLATE (column_name, 'd'||CHR(10)||CHR(13), 'd')

The 'd' is a dummy character, because translate does not work if the 3rd parameter is null.

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I had the same problem. I noticed that my db context (EF4) that was located in the project dll wasn't recognize for some reason. I deleted it and created another one instead. and that solved it for me.

how to execute php code within javascript

If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>

However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  $('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>

This runs the php script and loads whatever message it returns into <div id="resultMsg">.

order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:

<?php
// do adding to cart stuff here
echo 'Added to cart';
?>

For this to work you will need to include jQuery on your page, by adding this in your <head> tag:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

How do CSS triangles work?

SASS (SCSS) triangle mixin

I wrote this to make it easier (and DRY) to automatically generate a CSS triangle:

// Triangle helper mixin (by Yair Even-Or)
// @param {Direction} $direction - either `top`, `right`, `bottom` or `left`
// @param {Color} $color [currentcolor] - Triangle color
// @param {Length} $size [1em] - Triangle size
@mixin triangle($direction, $color: currentcolor, $size: 1em) {
  $size: $size/2;
  $transparent: rgba($color, 0);
  $opposite: (top:bottom, right:left, left:right, bottom:top);

  content: '';
  display: inline-block;
  width: 0;
  height: 0;
  border: $size solid $transparent;
  border-#{map-get($opposite, $direction)}-color: $color;
  margin-#{$direction}: -$size;
}

use-case example:

span {
  @include triangle(bottom, red, 10px);
}

Playground page


Important note:
if the triangle seems pixelated in some browsers, try one of the methods described here.

What is the purpose of the "role" attribute in HTML?

Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML via supporting specs like HTML-AAM. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.

http://www.w3.org/TR/wai-aria/

There are a few primary reasons to use roles in addition to your native semantic element.

Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.

In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.

<a href="#" role="button" aria-label="Delete item 1">Delete</a>
<!-- Note: href="#" is just a shorthand here, not a recommended technique. Use progressive enhancement when possible. -->

Screen readers users will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.

[role="button"] {
  /* style these as buttons w/o relying on a .button class */
}

[Update 7 years later: removed the * selector to make some commenters happy, since the old browser quirk that required universal selector on attribute selectors is unnecessary in 2020.]

Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.

For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <main>.

<main role="main">…</main>

This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary for main.

Reason #3. Update 7 years later (2020): As at least one commenter pointed out, this is now very useful for custom elements, and some spec work is underway to define the default accessibility role of a web component. Even if/once that API is standardized, there may be need to override the default role of a component.

Note/Reply

You also wrote:

I see some people make up their own. Is that allowed or a correct use of the role attribute?

That's an allowed use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.

<span role="foo link note bar">...</a>

Out of the list, only link and note are valid roles, and so the link role will be applied in the platform accessibility API because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

How to run a hello.js file in Node.js on windows?

type node js command prompt in start screen. and use it. OR set PATH of node in environment variable.

What is the effect of extern "C" in C++?

A function void f() compiled by a C compiler and a function with the same name void f() compiled by a C++ compiler are not the same function. If you wrote that function in C, and then you tried to call it from C++, then the linker would look for the C++ function and not find the C function.

extern "C" tells the C++ compiler that you have a function which was compiled by the C compiler. Once you tell it that it was compiled by the C compiler, the C++ compiler will know how to call it correctly.

It also allows the C++ compiler to compile a C++ function in such a way that the C compiler can call it. That function would officially be a C function, but since it is compiled by the C++ compiler, it can use all the C++ features and has all the C++ keywords.

ALTER TABLE, set null in not null column, PostgreSQL 9.1

Execute the command in this format

ALTER TABLE tablename ALTER COLUMN columnname SET NOT NULL;

for setting the column to not null.

What exactly is RESTful programming?

I would say that an important building block in understanding REST lies in the endpoints or mappings, such as /customers/{id}/balance.

You can imagine such an endpoint as being the connecting pipeline from the website (front-end) to your database/server (back-end). Using them, the front-end can perform back-end operations which are defined in the corresponding methods of any REST mapping in your application.

Use SELECT inside an UPDATE query

I did want to add one more answer that utilizes a VBA function, but it does get the job done in one SQL statement. Though, it can be slow.

UPDATE FUNCTIONS
SET FUNCTIONS.Func_TaxRef = DLookUp("MinOfTax_Code", "SELECT
FUNCTIONS.Func_ID,Min(TAX.Tax_Code) AS MinOfTax_Code
FROM TAX, FUNCTIONS
WHERE (((FUNCTIONS.Func_Pure)<=[Tax_ToPrice]) AND ((FUNCTIONS.Func_Year)=[Tax_Year]))
GROUP BY FUNCTIONS.Func_ID;", "FUNCTIONS.Func_ID=" & Func_ID)

How do I enable the column selection mode in Eclipse?

To activate the cursor and select the columns you want to select use:

Windows: Alt+Shift+A

Mac: command + option + A

Linux-based OS: Alt+Shift+A

To deactivate, press the keys again.

This information was taken from DJ's Java Blog.

RuntimeError on windows trying python multiprocessing

Try putting your code inside a main function in testMain.py

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

See the docs:

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

which say

"Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)."

... by using if __name__ == '__main__'

git-diff to ignore ^M

I struggled with this problem for a long time. By far the easiest solution is to not worry about the ^M characters and just use a visual diff tool that can handle them.

Instead of typing:

git diff <commitHash> <filename>

try:

git difftool <commitHash> <filename>

Javascript - remove an array item by value

Here are some helper functions I use:

Array.contains = function (arr, key) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return true;
    }
    return false;
};

Array.add = function (arr, key, value) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return arr[key] = value;
    }
    this.push(key);
};

Array.remove = function (arr, key) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return arr.splice(i, 1);
    }
};

Invalid length for a Base-64 char array

My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.

Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely + and /, and maybe = too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.

You can use the HttpUtility.UrlEncode method to encode your Base64 string:

string msg = "Please click on the link below or paste it into a browser "
             + "to verify your email account.<br /><br /><a href=\""
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";

"Cannot start compilation: the output path is not specified for module..."

After this

Two things to do:

Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.

Project Settings > Module > Path > Choose "Inherit project compile path""

If button ran is not active

You must reload IDEA

How to increase heap size for jBoss server

What to change?

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

Where to change? (Normally)

bin/standalone.conf(Linux) standalone.conf.bat(Windows)

What if you are using custom script which overrides the existing settings? then?

setAppServerEnvironment.cmd/.sh (kind of file name will be there)

More information are already provided by one of our committee members! BalusC.

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

How to convert a string with comma-delimited items to a list in Python?

Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:

>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'

But what you're dealing with right now, go with @Cameron's answer.

>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

How about:

(Updated)

$("#column_select").change(function () {
    $("#layout_select")
        .find("option")
        .show()
        .not("option[value*='" + this.value + "']").hide();

    $("#layout_select").val(
        $("#layout_select").find("option:visible:first").val());

}).change();

(assuming the third option should have a value col3)

Example: http://jsfiddle.net/cL2tt/

Notes:

  • Use the .change() event to define an event handler that executes when the value of select#column_select changes.
  • .show() all options in the second select.
  • .hide() all options in the second select whose value does not contain the value of the selected option in select#column_select, using the attribute contains selector.

Pass parameter from a batch file to a PowerShell script

Assuming your script is something like the below snippet and named testargs.ps1

param ([string]$w)
Write-Output $w

You can call this at the commandline as:

PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"

This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.

How to use _CRT_SECURE_NO_WARNINGS

Add by

Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS

screenshot of the relevant config interface

How do you perform a left outer join using linq extension methods

Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:

var qry = Foos.GroupJoin(
      Bars.OrderByDescending(b => b.Id),
      foo => foo.Foo_Id,
      bar => bar.Foo_Id,
      (f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });

Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).

Alter Table Add Column Syntax

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

Android: how to hide ActionBar on certain activities

Check for padding attribute if the issue still exists after changing theme.

Padding Issue creating a white space on top of fragment window / app window

Padding Issue creating a white space on top of fragment window / app window

Once you remove the padding - top value automatically the white space is removed.

How can I get a list of all values in select box?

You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

http://jsfiddle.net/WfBRr/5/

Swift Beta performance: sorting arrays

The main issue that is mentioned by others but not called out enough is that -O3 does nothing at all in Swift (and never has) so when compiled with that it is effectively non-optimised (-Onone).

Option names have changed over time so some other answers have obsolete flags for the build options. Correct current options (Swift 2.2) are:

-Onone // Debug - slow
-O     // Optimised
-O -whole-module-optimization //Optimised across files

Whole module optimisation has a slower compile but can optimise across files within the module i.e. within each framework and within the actual application code but not between them. You should use this for anything performance critical)

You can also disable safety checks for even more speed but with all assertions and preconditions not just disabled but optimised on the basis that they are correct. If you ever hit an assertion this means that you are into undefined behaviour. Use with extreme caution and only if you determine that the speed boost is worthwhile for you (by testing). If you do find it valuable for some code I recommend separating that code into a separate framework and only disabling the safety checks for that module.

setting request headers in selenium

Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.

Here are a couple of possibilities that I can propose:

  1. Use another driver/library instead of selenium
  2. Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
  3. Use browsermob-proxy or some other proxy.

I'd go with option 3 in most of cases. It's not hard.

Note that Ghostdriver has an API for it but it's not supported by other drivers.

Java, return if trimmed String in List contains String

You can do it in a single line by using regex:

if (myList.toString().matches(".*\\bA\\b.*"))

This code should perform quite well.


BTW, you could build the regex from a variable, like this:

.matches("\\[.*\\b" + word + "\\b.*]")

I added [ and ] to each end to prevent a false positive match when the search term contains an open/close square bracket at the start/end.

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

For me, I had to remove the intellij internal sdk and started to use my local sdk. When I started to use the internal, the error was gone.

my sdks

How to validate array in Laravel?

You have to loop over the input array and add rules for each input as described here: Loop Over Rules

Here is a some code for ya:

$input = Request::all();
$rules = [];

foreach($input['name'] as $key => $val)
{
    $rules['name.'.$key] = 'required|distinct|min:3';
}

$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';

$validator = Validator::make($input, $rules);

//Now check validation:
if ($validator->fails()) 
{ 
  /* do something */ 
}

Is it possible to select the last n items with nth-child?

:nth-last-child(-n+2) should do the trick

Setting HTTP headers

All of the above answers are wrong because they fail to handle the OPTIONS preflight request, the solution is to override the mux router's interface. See AngularJS $http get request failed with custom header (alllowed in CORS)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/save", saveHandler)
    http.Handle("/", &MyServer{r})
    http.ListenAndServe(":8080", nil);

}

type MyServer struct {
    r *mux.Router
}

func (s *MyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    if origin := req.Header.Get("Origin"); origin != "" {
        rw.Header().Set("Access-Control-Allow-Origin", origin)
        rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        rw.Header().Set("Access-Control-Allow-Headers",
            "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // Stop here if its Preflighted OPTIONS request
    if req.Method == "OPTIONS" {
        return
    }
    // Lets Gorilla work
    s.r.ServeHTTP(rw, req)
}

TLS 1.2 not working in cURL

TLS 1.2 is only supported since OpenSSL 1.0.1 (see the Major version releases section), you have to update your OpenSSL.

It is not necessary to set the CURLOPT_SSLVERSION option. The request involves a handshake which will apply the newest TLS version both server and client support. The server you request is using TLS 1.2, so your php_curl will use TLS 1.2 (by default) as well if your OpenSSL version is (or newer than) 1.0.1.

How to import Angular Material in project?

Import all Angular Material modules in Angular 9.

Create material.module.ts file in your_project/src/app/ directory and paste this code.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';


import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatBadgeModule } from '@angular/material/badge';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatStepperModule } from '@angular/material/stepper';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatDialogModule } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatPaginatorModule } from '@angular/material/paginator';


@NgModule( {
    imports: [
        CommonModule,
        BrowserAnimationsModule,
        MatCheckboxModule,
        MatCheckboxModule,
        MatButtonModule,
        MatInputModule,
        MatAutocompleteModule,
        MatDatepickerModule,
        MatFormFieldModule,
        MatRadioModule,
        MatSelectModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatMenuModule,
        MatSidenavModule,
        MatBadgeModule,
        MatToolbarModule,
        MatListModule,
        MatGridListModule,
        MatCardModule,
        MatStepperModule,
        MatTabsModule,
        MatExpansionModule,
        MatButtonToggleModule,
        MatChipsModule,
        MatIconModule,
        MatProgressSpinnerModule,
        MatProgressBarModule,
        MatDialogModule,
        MatTooltipModule,
        MatSnackBarModule,
        MatTableModule,
        MatSortModule,
        MatPaginatorModule

    ],
    exports: [
        MatButtonModule,
        MatToolbarModule,
        MatIconModule,
        MatSidenavModule,
        MatBadgeModule,
        MatListModule,
        MatGridListModule,
        MatInputModule,
        MatFormFieldModule,
        MatSelectModule,
        MatRadioModule,
        MatDatepickerModule,
        MatChipsModule,
        MatTooltipModule,
        MatTableModule,
        MatPaginatorModule
    ],
    providers: [
        MatDatepickerModule,
    ]
} )

export class AngularMaterialModule { }

How to remove carriage return and newline from a variable in shell script

use this command on your script file after copying it to Linux/Unix

perl -pi -e 's/\r//' scriptfilename

How to redirect a page using onclick event in php?

Please try this

    <input type="button" value="Home" class="homebutton" id="btnHome" onClick="Javascript:window.location.href = 'http://www.website.com/index.php';" />

window.location.href example:

 window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

     window.open('http://www.google.com'); //This will open Google in a new window.

Copy files on Windows Command Line with Progress

The Esentutl /y option allows copyng (single) file files with progress bar like this :

enter image description here

the command should look like :

esentutl /y "FILE.EXT" /d "DEST.EXT" /o

The command is available on every windows machine but the y option is presented in windows vista. As it works only with single files does not look very useful for a small ones. Other limitation is that the command cannot overwrite files. Here's a wrapper script that checks the destination and if needed could delete it (help can be seen by passing /h).

How to use FormData in react-native?

You can use react-native-image-picker and axios (form-data)

uploadS3 = (path) => {
    var data = new FormData();

    data.append('files',
        { uri: path, name: 'image.jpg', type: 'image/jpeg' }
    );

    var config = {
        method: 'post',
        url: YOUR_URL,
        headers: {
            Accept: "application/json",
            "Content-Type": "multipart/form-data",
        },
        data: data,
    };

    axios(config)
        .then((response) => {
            console.log(JSON.stringify(response.data));
        })
        .catch((error) => {
            console.log(error);
        });
}

react-native-image-picker

selectPhotoTapped() {
    const options = {
        quality: 1.0,
        maxWidth: 500,
        maxHeight: 500,
        storageOptions: {
            skipBackup: true,
        },
    };

    ImagePicker.showImagePicker(options, response => {
        //console.log('Response = ', response);

        if (response.didCancel) {
            //console.log('User cancelled photo picker');
        } else if (response.error) {
            //console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
            //console.log('User tapped custom button: ', response.customButton);
        } else {
            let source = { uri: response.uri };
             
            // Call Upload Function
            this.uploadS3(source.uri)

            // You can also display the image using data:
            // let source = { uri: 'data:image/jpeg;base64,' + response.data };
            this.setState({
                avatarSource: source,
            });
            // this.imageUpload(source);
        }
    });
}

What is Ruby's double-colon `::`?

Adding to previous answers, it is valid Ruby to use :: to access instance methods. All the following are valid:

MyClass::new::instance_method
MyClass::new.instance_method
MyClass.new::instance_method
MyClass.new.instance_method

As per best practices I believe only the last one is recommended.

MySQLi count(*) always returns 1

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

AngularJS ng-if with multiple conditions

JavaScript Code

function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}


$scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
    else
         return "ClassC";
}
}

How to display a range input slider vertically

First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:

... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.

Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.

Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.

For Chrome, use -webkit-appearance: slider-vertical.

For IE, use writing-mode: bt-lr.

For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.

_x000D_
_x000D_
input[type=range][orient=vertical]
{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 8px;
    height: 175px;
    padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
_x000D_
_x000D_


Disclaimers:

This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.

MDN contains an explicit warning against using -webkit-appearance on the web:

Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword none has not the same behavior on each form element on different browsers, and some doesn't support it at all.

The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode. The writing-mode property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr in favor of the currently proposed vertical-lr (which would be the equivalent of tb-lr), the slider would display upside down. Most likely, future versions would extend the writing-mode to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.

Is there a cross-browser onload event when clicking the back button?

for the people who don't want to use the whole jquery library i extracted the implementation in separate code. It's only 0,4 KB big.

You can find the code, together with a german tutorial in this wiki: http://www.easy-coding.de/wiki/html-ajax-und-co/onload-event-cross-browser-kompatibler-domcontentloaded.html

Easy pretty printing of floats in python?

First, elements inside a collection print their repr. you should learn about __repr__ and __str__.

This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:

numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933]
print "repr:", " ".join(repr(n) for n in numbers)
print "str:", " ".join(str(n) for n in numbers)

How to read and write into file using JavaScript?

The future is here! The proposals are closer to completion, no more ActiveX or flash or java. Now we can use:

You could use the Drag/Drop to get the file into the browser, or a simple upload control. Once the user has selected a file, you can read it w/ Javascript: http://www.html5rocks.com/en/tutorials/file/dndfiles/

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

First prevent default actions on your entire document as usual:

$(document).bind('touchmove', function(e){
  e.preventDefault();           
});

Then stop your class of elements from propagating to the document level. This stops it from reaching the function above and thus e.preventDefault() is not initiated:

$('.scrollable').bind('touchmove', function(e){
  e.stopPropagation();
});

This system seems to be more natural and less intensive than calculating the class on all touch moves. Use .on() rather than .bind() for dynamically generated elements.

Also consider these meta tags to prevent unfortunate things from happening while using your scrollable div:

<meta content='True' name='HandheldFriendly' />
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />

manage.py runserver

Just in case any Windows users are having trouble, I thought I'd add my own experience. When running python manage.py runserver 0.0.0.0:8000, I could view urls using localhost:8000, but not my ip address 192.168.1.3:8000.

I ended up disabling ipv6 on my wireless adapter, and running ipconfig /renew. After this everything worked as expected.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

You can't, as far as I know, make the entire OS understand an http:+domain URL. You can only register new schemes (I use x-darkslide: in my app). If the app is installed, Mobile Safari will launch the app correctly.

However, you would have to handle the case where the app isn't installed with a "Still here? Click this link to download the app from iTunes." in your web page.

How to see the actual Oracle SQL statement that is being executed

Yep, that's definitely possible. The v$sql views contain that info. Something like this piece of code should point you in the right direction. I haven't tried that specific piece of code myself - nowhere near an Oracle DB right now.

[Edit] Damn two other answers already. Must type faster next time ;-)

How do I get my C# program to sleep for 50 msec?

Thread.Sleep(50);

The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

Thread.Join

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Simply create an object of Base64 and use it to encode or decode, when using org.apache.commons.codec.binary.Base64 library

To Encode

Base64 ed=new Base64();

String encoded=new String(ed.encode("Hello".getBytes()));

Replace "Hello" with the text to be encoded in String Format.

To Decode

Base64 ed=new Base64();

String decoded=new String(ed.decode(encoded.getBytes()));

Here encoded is the String variable to be decoded

How to check if a view controller is presented modally or pushed on a navigation stack?

Best ever solution ever is here.

if ((self.navigationController?.popViewController(animated: true)) == nil) {
     self.dismiss(animated: true, completion: nil)
}

Check if Pop Navigation provide nil then Dismiss Controller. It can handle Pop and Dismiss vice versa.

How to set shadows in React Native for android?

You can use my react-native-simple-shadow-view

  • This enables almost identical shadow in Android as in iOS
  • No need to use elevation, works with the same shadow parameters of iOS (shadowColor, shadowOpacity, shadowRadius, offset, etc.) so you don't need to write platform specific shadow styles
  • Can be used with semi-transparent views
  • Supported in android 18 and up

PHP multidimensional array search by value

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Nested routes with react router v4 / v5

A complete answer for React Router v5.


const Router = () => {
  return (
    <Switch>
      <Route path={"/"} component={LandingPage} exact />
      <Route path={"/games"} component={Games} />
      <Route path={"/game-details/:id"} component={GameDetails} />
      <Route
        path={"/dashboard"}
        render={({ match: { path } }) => (
          <Dashboard>
            <Switch>
              <Route
                exact
                path={path + "/"}
                component={DashboardDefaultContent}
              />
              <Route path={`${path}/inbox`} component={Inbox} />
              <Route
                path={`${path}/settings-and-privacy`}
                component={SettingsAndPrivacy}
              />
              <Redirect exact from={path + "/*"} to={path} />
            </Switch>
          </Dashboard>
        )}
      />
      <Route path="/not-found" component={NotFound} />
      <Redirect exact from={"*"} to={"/not-found"} />
    </Switch>
  );
};

export default Router;
const Dashboard = ({ children }) => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      {children}
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-5-demo

How to fix the error "Windows SDK version 8.1" was not found?

I installed the 8.1 SDK's version:

https://developer.microsoft.com/en-us/windows/downloads/sdk-archive

It used 1GB (a little more) in the installation.


Update October, 9. There's a https error: the sdksetup link is https://go.microsoft.com/fwlink/p/?LinkId=323507

"Save link as" should help.

Throwing exceptions in a PHP Try Catch block

throw $e->getMessage();

You try to throw a string

As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data

Serializing enums with Jackson

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

Sorting hashmap based on keys

You can use TreeMap which will store values in sorted form.

Map <String, String> map = new TreeMap <String, String>();

XPath: Get parent node from child node

You can use the two dots at the end of expression, too. See this example:

//*[title="50"]/..

How can I put a ListView into a ScrollView without it collapsing?

Instead of putting the listview inside Scrollview, put the rest of the content between listview and the opening of the Scrollview as a separate view and set that view as the header of the listview. So you will finally end up only list view taking charge of Scroll.

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

  1. Go to My Computer => Local Disk(C:) => Program Files(x86) => Git => cmd
  2. Right Click the git => Select Properties
  3. Under the location Copy the text eg - C:\Program Files (x86)\Git\cmd
  4. Come back to the Desktop
  5. Right-click My Computer
  6. Select property
  7. Open Advanced
  8. Click Environment Variables
  9. In the System variables Find the Variable call Path
  10. Click the variable
  11. Click the Edit Button
  12. Select the Variable value Text Box .
  13. Go to the edge of the text and put semicolon(;)
  14. Then Right-click and press Paste
  15. Press Ok

How to convert a currency string to a double with jQuery or Javascript?

You can try this

_x000D_
_x000D_
var str = "$1,112.12";_x000D_
str = str.replace(",", "");_x000D_
str = str.replace("$", "");_x000D_
console.log(parseFloat(str));
_x000D_
_x000D_
_x000D_

Permutation of array

If you're using C++, you can use std::next_permutation from the <algorithm> header file:

int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
  // print a's elements
} while(std::next_permutation(a, a+size));

Creating a DateTime in a specific Time Zone in c#

You'll have to create a custom object for that. Your custom object will contain two values:

Not sure if there already is a CLR-provided data type that has that, but at least the TimeZone component is already available.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Try to this cors npm modules.

var cors = require('cors')

var app = express()
app.use(cors())

This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.

Rename computer and join to domain in one step with PowerShell

I have a tested code to join domain and rename the computer to the servicetag.

code:

$servicetag = Get-WmiObject win32_bios | Select-Object -ExpandProperty SerialNumber
Add-Computer -Credential DOMAIN\USER -DomainName DOMAIN -NewName $servicetag

DOMAIN\USER = edit to a user on the domain that can join computers to the domain. Example:

mydomain\admin

DOMAIN = edit to the domain that you want to join. Example:

mydomain.local

How to define custom configuration variables in rails

Update 1

Very recommended: I'm going with Rails Config gem nowadays for the fine grained control it provides.

Update2

If you want a quick solution, then check Jack Pratt's answer below.

Although my original answer below still works, this answer is now outdated. I recommend looking at updates 1 and 2.

Original Answer:

For a quick solution, watching the "YAML Configuration File" screen cast by Ryan Bates should be very helpful.

In summary:

# config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]

# application.rb
if APP_CONFIG['perform_authentication']
  # Do stuff
end

How to free memory from char array in C

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

What is the best way to uninstall gems from a rails3 project?

Bundler now has a bundle remove GEM_NAME command (since v1.17.0, 25 October 2018).

Get $_POST from multiple checkboxes

you have to name your checkboxes accordingly:

<input type="checkbox" name="check_list[]" value="…" />

you can then access all checked checkboxes with

// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
   // do something
}

ps. make sure to properly escape your output (htmlspecialchars())

Printing result of mysql query from variable

From php docs:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

http://php.net/manual/en/function.mysql-query.php

SSL Connection / Connection Reset with IISExpress

The issue that I had was related to @Jason Kleban's answer, but I had one small problem with my settings in the Visual Studio Properties for IIS Express.

Make sure that after you've changed the port to be in the range: 44300 to 44399, the address also starts with HTTPS

enter image description here

Chart won't update in Excel (2007)

My two cents for this problem--I was having a similar issue with a chart on an Access 2010 report. I was dynamically building a querydef, setting that as the rowsource on my report and then trying to loop through each series and set the properties of each series. What I eventually had to do was to break out the querydef creation and the property setting into separate subs. Additionally, I put a

SendKeys ("{DOWN}")
SendKeys ("{UP}")

at the bottom of each of the two subs.

Can't use modulus on doubles?

The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}

Multiprocessing vs Threading Python

As I learnd in university most of the answers above are right. In PRACTISE on different platforms (always using python) spawning multiple threads ends up like spawning one process. The difference is the multiple cores share the load instead of only 1 core processing everything at 100%. So if you spawn for example 10 threads on a 4 core pc, you will end up getting only the 25% of the cpus power!! And if u spawn 10 processes u will end up with the cpu processing at 100% (if u dont have other limitations). Im not a expert in all the new technologies. Im answering with own real experience background

R legend placement in a plot

?legend will tell you:

Arguments

x, y
the x and y co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords: See ‘Details’.

Details:

Arguments x, y, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.

The coordinates can be specified in any way which is accepted by xy.coords. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).

The location may also be specified by setting x to a single keyword from the list bottomright, bottom, bottomleft, left, topleft, top, topright, right and center. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.

Insert into a MySQL table or update if exists

When using SQLite:

REPLACE into table (id, name, age) values(1, "A", 19)

Provided that id is the primary key. Or else it just inserts another row. See INSERT (SQLite).

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

View google chrome's cached pictures

You can make a bookmark with this as the url:

javascript:
var cached_anchors = $$('a');
for (var i in cached_anchors) {
    var ca = cached_anchors[i];
    if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {
        var a = document.createElement('a');
        a.href = ca.innerHTML;
        a.target = '_blank';

        var img = document.createElement('img');
        img.src = ca.innerHTML;
        img.style.maxHeight = '100px';

        a.appendChild(img);
        document.getElementsByTagName('body')[0].appendChild(a);
    }
}
document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]);
void(0);

Then just go to chrome://cache and then click your bookmark and it'll show you all the images.

Load image from resources area of project in C#

Are you using Windows Forms? If you've added the image using the Properties/Resources UI, you get access to the image from generated code, so you can simply do this:

var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);

java.io.IOException: Server returned HTTP response code: 500

HTTP status code 500 usually means that the webserver code has crashed. You need to determine the status code beforehand using HttpURLConnection#getResponseCode() and in case of errors, read the HttpURLConnection#getErrorStream() instead. It may namely contain information about the problem.

If the host has blocked you, you would rather have gotten a 4nn status code like 401 or 403.

See also:

DataGridView checkbox column - value and functionality

It is quite simple

DataGridViewCheckBoxCell checkedCell = (DataGridViewCheckBoxCell) grdData.Rows[e.RowIndex].Cells["grdChkEnable"];
    
bool isEnabled = false;
if (checkedCell.AccessibilityObject.State.HasFlag(AccessibleStates.Checked))
{
    isEnabled = true;
}
if (isEnabled)
{
   // do your business process;
}

What are database constraints?

Constraints dictate what values are valid for data in the database. For example, you can enforce the a value is not null (a NOT NULL constraint), or that it exists as a unique constraint in another table (a FOREIGN KEY constraint), or that it's unique within this table (a UNIQUE constraint or perhaps PRIMARY KEY constraint depending on your requirements). More general constraints can be implemented using CHECK constraints.

The MSDN documentation for SQL Server 2008 constraints is probably your best starting place.

Message 'src refspec master does not match any' when pushing commits in Git

Github changed the default branch name from master to main. So if you created the repo recently, try pushing main branch

git push origin main

Github Article

Catching an exception while using a Python 'with' statement

Catching an exception while using a Python 'with' statement

The with statement has been available without the __future__ import since Python 2.6. You can get it as early as Python 2.5 (but at this point it's time to upgrade!) with:

from __future__ import with_statement

Here's the closest thing to correct that you have. You're almost there, but with doesn't have an except clause:

with open("a.txt") as f: 
    print(f.readlines())
except:                    # <- with doesn't have an except clause.
    print('oops')

A context manager's __exit__ method, if it returns False will reraise the error when it finishes. If it returns True, it will suppress it. The open builtin's __exit__ doesn't return True, so you just need to nest it in a try, except block:

try:
    with open("a.txt") as f:
        print(f.readlines())
except Exception as error: 
    print('oops')

And standard boilerplate: don't use a bare except: which catches BaseException and every other possible exception and warning. Be at least as specific as Exception, and for this error, perhaps catch IOError. Only catch errors you're prepared to handle.

So in this case, you'd do:

>>> try:
...     with open("a.txt") as f:
...         print(f.readlines())
... except IOError as error: 
...     print('oops')
... 
oops

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

smtpclient " failure sending mail"

Well, the "failure sending e-mail" should hopefully have a bit more detail. But there are a few things that could cause this.

  1. Restrictions on the "From" address. If you are using different from addresses, some could be blocked by your SMTP service from being able to send.
  2. Flood prevention on your SMTP service could be stopping the e-mails from going out.

Regardless if it is one of these or another error, you will want to look at the exception and inner exception to get a bit more detail.

"unadd" a file to svn before commit

Full process (Unix svn package):

Check files are not in SVN:

> svn st -u folder 
? folder

Add all (including ignored files):

> svn add folder
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt
A   folder/folderToIgnore
A   folder/folderToIgnore/fileToIgnore1.txt
A   fileToIgnore2.txt

Remove "Add" Flag to All * Ignore * files:

> cd folder

> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'


> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'

Edit svn ignore on folder

svn propedit svn:ignore .

Add two singles lines with just the following:

folderToIgnore
fileToIgnore2.txt

Check which files will be upload and commit:

> cd ..

> svn st -u
A   folder
A   folder/file1.txt
A   folder/folder2
A   folder/folder2/file2.txt


> svn ci -m "Commit message here"

clk'event vs rising_edge()

Practical example:

Imagine that you are modelling something like an I2C bus (signals called SCL for clock and SDA for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.

scl <= 'H'; -- Testbench resistor pullup

Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'

Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.

  • If you have a line of code that relies on (scl'event and scl = '1'), then you'll get a false trigger.

  • If you have a line of code that relies on rising_edge(scl), then you won't get a false trigger.

Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.

Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl) condition (correct), but the (scl'event and scl = '1') case will miss it (incorrect).

General Recommenation:

Use rising_edge(clk) and falling_edge(clk) instead of clk'event for all code.

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

What is the difference between range and xrange functions in Python 2.X?

Everyone has explained it greatly. But I wanted it to see it for myself. I use python3. So, I opened the resource monitor (in Windows!), and first, executed the following command first:

a=0
for i in range(1,100000):
    a=a+i

and then checked the change in 'In Use' memory. It was insignificant. Then, I ran the following code:

for i in list(range(1,100000)):
    a=a+i

And it took a big chunk of the memory for use, instantly. And, I was convinced. You can try it for yourself.

If you are using Python 2X, then replace 'range()' with 'xrange()' in the first code and 'list(range())' with 'range()'.

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

phpMyAdmin + CentOS 6.0 - Forbidden

Non of the above mentioned solutions worked for me. Below is what finally worked:

#yum update
#yum install phpmyadmin

Be advised, phpmyadmin was working a few hours earlier. I don't know what happened.

After this, going to the browser, I got an error that said ./config.inic.php can't be accessed

#cd /usr/share/phpmyadmin/
#stat -c %a config.inic.php
#640
#chmod 644 config.inic.php

This shows that the file permissions were 640, then I changed them to 644. Finially, it worked.

Remember to restart httpd.

#service httpd restart

How do I get the path to the current script with Node.js?

So basically you can do this:

fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);

Use resolve() instead of concatenating with '/' or '\' else you will run into cross-platform issues.

Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:

require.main.filename

or, to just get the folder name:

require('path').dirname(require.main.filename)

Ellipsis for overflow text in dropdown boxes

The simplest solution might be to limit the number of characters in the HTML itself. Rails has a truncate(string, length) helper, and I'm certain that whichever backend you're using provides something similar.

Due to the cross-browser issues you're already familiar with regarding the width of select boxes, this seems to me to be the most straightforward and least error-prone option.

<select>
  <option value="1">One</option>
  <option value="100">One hund...</option>
<select>

Programmatically scroll to a specific position in an Android ListView

I have set OnGroupExpandListener and override onGroupExpand() as:

and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs)

    yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
    {

        @Override
        public void onGroupExpand(int groupPosition) {

            expList.setSelectionFromTop(groupPosition, 0);
            //your other code
        }
    });

Finding all objects that have a given property inside a collection

Here's an idea for a searcher class you could parameterize with the specific values you want to look for.

You could go further and store the names of the properties as well, probably in a Map with the desired values. In this case you would use reflection on the Cat class to call the appropriate methods given the property names.

public class CatSearcher {

  private Integer ageToFind = null;
  private String  foodToFind = null;

  public CatSearcher( Integer age, String food ) {
    this.ageToFind = age;
    this.foodToFind = food;
  }

  private boolean isMatch(Cat cat) {
    if ( this.ageToFind != null && !cat.getAge().equals(this.ageToFind) ) {
       return false;
    }
    if ( this.foodToFind != null && !cat.getFood().equals(this.foodToFind) {
       return false;
    }
    return true;
  }

  public Collection<Cat> search( Collection<Cat> listToSearch ) {
    // details left to the imagination, but basically iterate over
    // the input list, call isMatch on each element, and if true
    // add it to a local collection which is returned at the end.
  }

}

When do I need to use a semicolon vs a slash in Oracle SQL?

It's a matter of preference, but I prefer to see scripts that consistently use the slash - this way all "units" of work (creating a PL/SQL object, running a PL/SQL anonymous block, and executing a DML statement) can be picked out more easily by eye.

Also, if you eventually move to something like Ant for deployment it will simplify the definition of targets to have a consistent statement delimiter.

Error You must specify a region when running command aws ecs list-container-instances

#1- Run this to configure the region once and for all:

aws configure set region us-east-1 --profile admin
  • Change admin next to the profile if it's different.

  • Change us-east-1 if your region is different.

#2- Run your command again:

aws ecs list-container-instances --cluster default

php - insert a variable in an echo string

echo '<p class="paragraph'.$i.'"></p>';

Compare two columns using pandas

Use lambda expression:

df[df.apply(lambda x: x['col1'] != x['col2'], axis = 1)]

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

One solution is to disable the resharper, or spell checker extension and restart. Granted this is not ideal.

How can I disable a button on a jQuery UI dialog?

If you're using knockout, then this even cleaner. Imagine you have the following:

_x000D_
_x000D_
var dialog = $('#my-dialog').dialog({_x000D_
    width: '100%',_x000D_
    buttons: [_x000D_
        { text: 'Submit', click: $.noop, 'data-bind': 'enable: items() && items().length > 0, click: onSubmitClicked' },_x000D_
        { text: 'Enable Submit', click: $.noop, 'data-bind': 'click: onEnableSubmitClicked' }_x000D_
    ]_x000D_
});_x000D_
_x000D_
function ViewModel(dialog) {_x000D_
    var self = this;_x000D_
_x000D_
    this.items = ko.observableArray([]);_x000D_
_x000D_
    this.onSubmitClicked = function () {_x000D_
        dialog.dialog('option', 'title', 'On Submit Clicked!');_x000D_
    };_x000D_
_x000D_
    this.onEnableSubmitClicked = function () {_x000D_
        dialog.dialog('option', 'title', 'Submit Button Enabled!');_x000D_
        self.items.push('TEST ITEM');_x000D_
        dialog.text('Submit button is enabled.');_x000D_
    };_x000D_
}_x000D_
_x000D_
var vm = new ViewModel(dialog);_x000D_
ko.applyBindings(vm, dialog.parent()[0]); //Don't forget to bind to the dialog parent, or the buttons won't get bound.
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>_x000D_
_x000D_
<div id="my-dialog">_x000D_
  Submit button is disabled at initialization._x000D_
</div>
_x000D_
_x000D_
_x000D_

The magic comes from the jQuery UI source:

$( "<button></button>", props )

You can basically call ANY jQuery instance function by passing it through the button object.

For example, if you want to use HTML:

{ html: '<span class="fa fa-user"></span>User' }

Or, if you want to add a class to the button (you can do this multiple ways):

{ addClass: 'my-custom-button-class' }

Maybe you're nuts, and you want to remove the button from the dom when it's hovered:

{ mouseover: function () { $(this).remove(); } }

I'm really surprised that no one seems to have mentioned this in the countless number of threads like this...

Better way to revert to a previous SVN revision of a file?

What you're looking for is called a "reverse merge". You should consult the docs regarding the merge function in the SVN book (as luapyad, or more precisely the first commenter on that post, points out). If you're using Tortoise, you can also just go into the log view and right-click and choose "revert changes from this revision" on the one where you made the mistake.

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

How to mock private method for testing using PowerMock?

A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.

  1. Change your private method to protected.
  2. In your test class extend the class
  3. override the previously-private method to return whatever constant you want

This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.

To mock a private method directly, you'll need to use PowerMock as shown in the other answer.

Why does this iterative list-growing code give IndexError: list assignment index out of range?

You could use a dictionary (similar to an associative array) for j

i = [1, 2, 3, 5, 8, 13]
j = {} #initiate as dictionary
k = 0

for l in i:
    j[k] = l
    k += 1

print(j)

will print :

{0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}

Select first empty cell in column F starting from row 1. (without using offset )

There is another way which ignores all empty cells before a nonempty cell and selects the last empty cell from the end of the first column. Columns should be addressed with their number eg. Col "A" = 1.

With ThisWorkbook.Sheets("sheet1")

        .Cells(.Cells(.Cells.Rows.Count, 1).End(xlUp).Row + 1, 1).select

End With

The next code is exactly as the above but can be understood better.

i = ThisWorkbook.Sheets("sheet1").Cells.Rows.Count

j = ThisWorkbook.Sheets("sheet1").Cells(i, 1).End(xlUp).Row

ThisWorkbook.Sheets("sheet1").Cells(j + 1, 1) = textbox1.value

How to calculate the time interval between two time strings

    import datetime
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    start_date = datetime.date(year, month, day)
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    end_date = datetime.date(year, month, day)
    
    time_difference = end_date - start_date
    age = time_difference.days
    print("Total days: " + str(age))

How to ignore a particular directory or file for tslint?

Can confirm that on version tslint 5.11.0 it works by modifying lint script in package.json by defining exclude argument:

"lint": "ng lint --exclude src/models/** --exclude package.json"

Cheers!!

Loading an image to a <img> from <input file>

As iEamin said in his answer, HTML 5 does now support this. The link he gave, http://www.html5rocks.com/en/tutorials/file/dndfiles/ , is excellent. Here is a minimal sample based on the samples at that site, but see that site for more thorough examples.

Add an onchange event listener to your HTML:

<input type="file" onchange="onFileSelected(event)">

Make an image tag with an id (I'm specifying height=200 to make sure the image isn't too huge onscreen):

<img id="myimage" height="200">

Here is the JavaScript of the onchange event listener. It takes the File object that was passed as event.target.files[0], constructs a FileReader to read its contents, and sets up a new event listener to assign the resulting data: URL to the img tag:

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var imgtag = document.getElementById("myimage");
  imgtag.title = selectedFile.name;

  reader.onload = function(event) {
    imgtag.src = event.target.result;
  };

  reader.readAsDataURL(selectedFile);
}

How can I iterate over files in a given directory?

This will iterate over all descendant files, not just the immediate children of the directory:

import os

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".asm"):
            print (filepath)

Convert String to Uri

If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.

val uri = myUriString.toUri()

To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle

  repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-rc01'
}

converting a javascript string to a html object

If the browser that you are planning to use is Mozilla (Addon development) (not sure of chrome) you can use the following method in Javascript

function DOM( string )
{
    var {Cc, Ci} = require("chrome");
    var parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
    console.log("PARSING OF DOM COMPLETED ...");
    return (parser.parseFromString(string, "text/html"));
};

Hope this helps

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Provide a User-Agent header:

import requests

url = 'http://www.ichangtou.com/#company:data_000008.html'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

response = requests.get(url, headers=headers)
print(response.content)

FYI, here is a list of User-Agent strings for different browsers:


As a side note, there is a pretty useful third-party package called fake-useragent that provides a nice abstraction layer over user agents:

fake-useragent

Up to date simple useragent faker with real world database

Demo:

>>> from fake_useragent import UserAgent
>>> ua = UserAgent()
>>> ua.chrome
u'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36'
>>> ua.random
u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

VARCHAR to DECIMAL

In MySQL

select convert( if( listPrice REGEXP '^[0-9]+$', listPrice, '0' ), DECIMAL(15, 3) ) from MyProduct WHERE 1

How to pass prepareForSegue: an object

In Swift 4.2 I would do something like that:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destination as? YourViewController {
        yourVC.yourData = self.someData
    }
}

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

This happened with me yesterday cause I downloaded the code from original repo and try to pushed it on my forked repo, spend so much time on searching for solving "Unable to push error" and pushed it forcefully.

Solution:

Simply Refork the repo by deleting previous one and clone the repo from forked repo to the new folder.

Replace the file with old one in new folder and push it to repo and do a new pull request.

python paramiko ssh

The code of @ThePracticalOne is great for showing the usage except for one thing: Somtimes the output would be incomplete.(session.recv_ready() turns true after the if session.recv_ready(): while session.recv_stderr_ready() and session.exit_status_ready() turned true before entering next loop)

so my thinking is to retrieving the data when it is ready to exit the session.

while True:
if session.exit_status_ready():
while True:
    while True:
        print "try to recv stdout..."
        ret = session.recv(nbytes)
        if len(ret) == 0:
            break
        stdout_data.append(ret)

    while True:
        print "try to recv stderr..."
        ret = session.recv_stderr(nbytes)
        if len(ret) == 0:
            break
        stderr_data.append(ret)
    break

Can you install and run apps built on the .NET framework on a Mac?

.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.

How to change background color in android app

android:background="#64B5F6"
You can change the value after '#' according to your own specification or need depending on how you want to use them.
Here is a sample code:

_x000D_
_x000D_
<TextView_x000D_
        android:text="Abir"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:textSize="24sp"_x000D_
        android:background="#D4E157"  />
_x000D_
_x000D_
_x000D_

Thank you :)

What is the use of a private static variable in Java?

Another perspective :

  1. A class and its instance are two different things at the runtime. A class info is "shared" by all the instances of that class.
  2. The non-static class variables belong to instances and the static variable belongs to class.
  3. Just like an instance variables can be private or public, static variables can also be private or public.

Changing ImageView source

Supplemental visual answer

ImageView: setImageResource() (standard method, aspect ratio is kept)

enter image description here

View: setBackgroundResource() (image is stretched)

enter image description here

Both

enter image description here

My fuller answer is here.

How can I change CSS display none or block property using jQuery?

(function($){
    $.fn.displayChange = function(fn){
        $this = $(this);
        var state = {};
        state.old = $this.css('display');
        var intervalID = setInterval(function(){
            if( $this.css('display') != state.old ){
                state.change = $this.css('display');
                fn(state);
                state.old = $this.css('display');
            }
        }, 100);        
    }

    $(function(){
        var tag = $('#content');
        tag.displayChange(function(obj){
            console.log(obj);
        });  
    })   
})(jQuery);

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

calling a function from class in python - different way

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

Style input element to fill remaining width of its container

If you're using Bootstrap 4:

<form class="d-flex">
  <label for="myInput" class="align-items-center">Sample label</label>
  <input type="text" id="myInput" placeholder="Sample Input" class="flex-grow-1"/>
</form>

Better yet, use what's built into Bootstrap:

  <form>
    <div class="input-group">
      <div class="input-group-prepend">
        <label for="myInput" class="input-group-text">Default</label>
      </div>
      <input type="text" class="form-control" id="myInput">
    </div>
  </form>

https://jsfiddle.net/nap1ykbr/

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Check if an object belongs to a class in Java

If you ever need to do this dynamically, you can use the following:

boolean isInstance(Object object, Class<?> type) {
    return type.isInstance(object);
}

You can get an instance of java.lang.Class by calling the instance method Object::getClass on any object (returns the Class which that object is an instance of), or you can do class literals (for example, String.class, List.class, int[].class). There are other ways as well, through the reflection API (which Class itself is the entry point for).

What's a good (free) visual merge tool for Git? (on windows)

  • TortoiseMerge (part of ToroiseSVN) is much better than kdiff3 (I use both and can compare);
  • p4merge (from Perforce) works also very well;
  • Diffuse isn't so bad;
  • Diffmerge from SourceGear has only one flaw in handling UTF8-files without BOM, making in unusable for this case.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.

Check if a string contains a string in C++

If the size of strings is relatively big (hundreds of bytes or more) and c++17 is available, you might want to use Boyer-Moore-Horspool searcher (example from cppreference.com):

#include <iostream>
#include <string>
#include <algorithm>
#include <functional>

int main()
{
    std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
                     " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
    std::string needle = "pisci";
    auto it = std::search(in.begin(), in.end(),
                   std::boyer_moore_searcher(
                       needle.begin(), needle.end()));
    if(it != in.end())
        std::cout << "The string " << needle << " found at offset "
                  << it - in.begin() << '\n';
    else
        std::cout << "The string " << needle << " not found\n";
}

Using Google maps API v3 how do I get LatLng with a given address?

I don't think location.LatLng is working, however this works:

results[0].geometry.location.lat(), results[0].geometry.location.lng()

Found it while exploring Get Lat Lon source code.

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

How do I quickly rename a MySQL database (change schema name)?

For those who are Mac users, Sequel Pro has a Rename Database option in the Database menu. http://www.sequelpro.com/

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

How to set session timeout in web.config

The value you are setting in the timeout attribute is the one of the correct ways to set the session timeout value.

The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.

By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.

To test this, create a simple aspx page, and write this code in the Page_Load event,

Response.Write(Session.SessionID);

Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.

Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -

Session["UserId"] = 1;

Now, you will have to perform a check on every page for this variable like this -

if(Session["UserId"] == null)
    Response.Redirect("login.aspx");

This is a bare-bones example of how this will work.

But, for making your production quality secure apps, use Roles & Membership classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use.

Difference between hamiltonian path and euler path

An Euler path is a path that passes through every edge exactly once. If it ends at the initial vertex then it is an Euler cycle.

A Hamiltonian path is a path that passes through every vertex exactly once (NOT every edge). If it ends at the initial vertex then it is a Hamiltonian cycle.

In an Euler path you might pass through a vertex more than once.

In a Hamiltonian path you may not pass through all edges.

How to test abstract class in Java with JUnit?

You can instantiate an anonymous class and then test that class.

public class ClassUnderTest_Test {

    private ClassUnderTest classUnderTest;

    private MyDependencyService myDependencyService;

    @Before
    public void setUp() throws Exception {
        this.myDependencyService = new MyDependencyService();
        this.classUnderTest = getInstance();
    }

    private ClassUnderTest getInstance() {
        return new ClassUnderTest() {    
            private ClassUnderTest init(
                    MyDependencyService myDependencyService
            ) {
                this.myDependencyService = myDependencyService;
                return this;
            }

            @Override
            protected void myMethodToTest() {
                return super.myMethodToTest();
            }
        }.init(myDependencyService);
    }
}

Keep in mind that the visibility must be protected for the property myDependencyService of the abstract class ClassUnderTest.

You can also combine this approach neatly with Mockito. See here.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx

use context.Database.BeginTransaction.

From MSDN:

using (var context = new BloggingContext()) 
{ 
    using (var dbContextTransaction = context.Database.BeginTransaction()) 
    { 
        try 
        { 
            context.Database.ExecuteSqlCommand( 
                @"UPDATE Blogs SET Rating = 5" + 
                    " WHERE Name LIKE '%Entity Framework%'" 
                ); 

            var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
            foreach (var post in query) 
            { 
                post.Title += "[Cool Blog]"; 
            } 

            context.SaveChanges(); 

            dbContextTransaction.Commit(); 
        } 
        catch (Exception) 
        { 
            dbContextTransaction.Rollback(); //Required according to MSDN article 
            throw; //Not in MSDN article, but recommended so the exception still bubbles up
        } 
    } 
} 

How to find server name of SQL Server Management Studio

the default server name is your computer name, but you can use "." (Dot) instead of local server name.

another thing you should consider is maybe you installed sql server express edition. in this case you must enter ".\sqlexpress" as server name.

What is attr_accessor in Ruby?

Simply attr-accessor creates the getter and setter methods for the specified attributes

creating list of objects in Javascript

dynamically build list of objects

var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    listOfObjects.push(singleObj);
});

here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output

How to check if a json key exists?

you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

use optString instead of getString:

Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists

How to create a dump with Oracle PL/SQL Developer?

There are some easy steps to make Dump file of your Tables,Users and Procedures:

Goto sqlplus or any sql*plus connect by your username or password

  1. Now type host it looks like SQL>host.
  2. Now type "exp" means export.
  3. It ask u for username and password give the username and password of that user of which you want to make a dump file.
  4. Now press Enter.
  5. Now option blinks for Export file: EXPDAT.DMP>_ (Give a path and file name to where you want to make a dump file e.g e:\FILENAME.dmp) and the press enter
  6. Select the option "Entire Database" or "Tables" or "Users" then press Enter
  7. Again press Enter 2 more times table data and compress extent
  8. Enter the name of table like i want to make dmp file of table student existing so type student and press Enter
  9. Enter to quit now your file at your given path is dump file now import that dmp file to get all the table data.

Remove unused imports in Android Studio

Press Ctrl + Alt + O.

A dialog box will appear with a few options. You can choose to have the dialog box not appear again in the future if you wish, setting a default behavior.

enter image description here

How to transfer some data to another Fragment?

Complete code of passing data using fragment to fragment

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                bundle.putString("key","value"); // use as per your need
                fragment.setArguments(bundle);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(viewID,fragment);
                fragmentTransaction.commit();

In custom fragment class

Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key);  // key must be same which was given in first fragment

How to use Session attributes in Spring-mvc

Try this...

@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

    @ModelAttribute("types")

    public Collection<PetType> populatePetTypes() {
        return this.clinic.getPetTypes();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, 
            BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId="
                + pet.getOwner().getId();
        }
    }
}

How can I add an item to a SelectList in ASP.net MVC

A work-around is to use @tvanfosson's answer (the selected answer) and use JQuery (or Javascript) to set the option's value to 0:

$(document).ready(function () {
        $('#DropDownListId option:first').val('0');
    });

Hope this helps.

Parse JSON with R

RJSONIO from Omegahat is another package which provides facilities for reading and writing data in JSON format.

rjson does not use S4/S3 methods and so is not readily extensible, but still useful. Unfortunately, it does not used vectorized operations and so is too slow for non-trivial data. Similarly, for reading JSON data into R, it is somewhat slow and so does not scale to large data, should this be an issue.

Update (new Package 2013-12-03):

jsonlite: This package is a fork of the RJSONIO package. It builds on the parser from RJSONIO but implements a different mapping between R objects and JSON strings. The C code in this package is mostly from the RJSONIO Package, the R code has been rewritten from scratch. In addition to drop-in replacements for fromJSON and toJSON, the package has functions to serialize objects. Furthermore, the package contains a lot of unit tests to make sure that all edge cases are encoded and decoded consistently for use with dynamic data in systems and applications.

how to stop a running script in Matlab

One solution I adopted--for use with java code, but the concept is the same with mexFunctions, just messier--is to return a FutureValue and then loop while FutureValue.finished() or whatever returns true. The actual code executes in another thread/process. Wrapping a try,catch around that and a FutureValue.cancel() in the catch block works for me.

In the case of mex functions, you will need to return somesort of pointer (as an int) that points to a struct/object that has all the data you need (native thread handler, bool for complete etc). In the case of a built in mexFunction, your mexFunction will most likely need to call that mexFunction in the separate thread. Mex functions are just DLLs/shared objects after all.

PseudoCode

FV = mexLongProcessInAnotherThread();
try
  while ~mexIsDone(FV);
    java.lang.Thread.sleep(100); %pause has a memory leak
    drawnow; %allow stdout/err from mex to display in command window
  end
catch
  mexCancel(FV);
end

How can I make PHP display the error instead of giving me 500 Internal Server Error

It's worth noting that if your error is due to .htaccess, for example a missing rewrite_module, you'll still see the 500 internal server error.

Unicode character as bullet for list-item in CSS

This topic may be old, but here's a quick fix ul {list-style:outside none square;} or ul {list-style:outside none disc;} , etc...

then add left padding to list element

ul li{line-height: 1.4;padding-bottom: 6px;}