Programs & Examples On #Versions

0

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Adding a file, and then deleting it is the kind of operation that's considered an error - and so SVN is telling you. You told it to expect some file data and then don't supply it when you commit, the red lights flash and the sirens go off!

The answer is to undo your add, alternatively commit the file and then use 'svn rm' to remove it from the filesystem and the repo.

The system cannot find the file specified. in Visual Studio

This is because you have not compiled it. Click 'Project > compile'. Then, either click 'start debugging', or 'start without debugging'.

How to set background image of a view?

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

more info with example project

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

jQuery click event not working after adding class

on document ready event there is no a tag with class tabclick. so you have to bind click event dynamically when you are adding tabclick class. please this code:

$("a.applicationdata").click(function() {
    var appid = $(this).attr("id");

   $('#gentab a').addClass("tabclick")
    .click(function() {
          var liId = $(this).parent("li").attr("id");
         alert(liId);        
      });


 $('#gentab a').attr('href', '#datacollector');

});

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

With JDBC, that error usually occurs because your JDBC driver implements an older version of the JDBC API than the one included in your JRE. These older versions are fine so long as you don't try and use a method that appeared in the newer API.

I'm not sure what version of JDBC setBinaryStream appeared in. It's been around for a while, I think.

Regardless, your JDBC driver version (10.2.0.4.0) is quite old, I recommend upgrading it to the version that was released with 11g (download here), and try again.

Passing a varchar full of comma delimited values to a SQL Server IN function

Best and simple approach.

DECLARE @AccumulateKeywordCopy NVARCHAR(2000),@IDDupCopy NVARCHAR(50);
SET @AccumulateKeywordCopy ='';
SET @IDDupCopy ='';
SET @IDDup = (SELECT CONVERT(VARCHAR(MAX), <columnName>) FROM <tableName> WHERE <clause>)

SET @AccumulateKeywordCopy = ','+@AccumulateKeyword+',';
SET @IDDupCopy = ','+@IDDup +',';
SET @IDDupCheck = CHARINDEX(@IDDupCopy,@AccumulateKeywordCopy)

Spring boot - Not a managed type

I have the same probblem, in version spring boot v1.3.x what i did is upgrade spring boot to version 1.5.7.RELEASE. Then the probblem gone.

How to create an AVD for Android 4.0

Another solution, for those of us without an internet connection to our development machine is:

Create a folder called system-images in the top level of your SDK directory (next to platforms and tools). Create subdirs android-14 and android-15 (as applicable). Extract the complete armeabi-v7a folder to these directory; sysimg_armv7a-15_r01.zip (from, e.g. google's repository) goes to android-15, sysimg_armv7a-14_r02.zip to android-14.

I've not tried this procedure offline, I finally relented and used my broadband allowance at home, but these are the target locations for these large sysimg's, for future reference.

I've tried creating the image subdirs where they were absent in 14 and 15 but while this allowed the AVD to create an image (for 15 but not 14) it hadn't shown the Android logo after 15 minutes.

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

SVN Error - Not a working copy

I just got "not a working copy", and for me the reason was the Automouter on Unix. Just a fresh "cd /path/to/work/directory" did the trick.

How do I search within an array of hashes by hash values in ruby?

if your array looks like

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

Java associative-array

Regarding the PHP comment 'No, PHP wouldn't like it'. Actually, PHP would keep on chugging unless you set some very restrictive (for PHP) exception/error levels, (and maybe not even then).

What WILL happen by default is that an access to a non existing variable/out of bounds array element 'unsets' your value that you're assigning to. NO, that is NOT null. PHP has a Perl/C lineage, from what I understand. So there are: unset and non existing variables, values which ARE set but are NULL, Boolean False values, then everything else that standard langauges have. You have to test for those separately, OR choose the RIGHT evaluation built in function/syntax.

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

Semantic Difference

According to HTML 5.2:

When specified on an element, [the hidden attribute] indicates that the element is not yet, or is no longer, directly relevant to the page’s current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user.

Examples include a tab list where some panels are not exposed, or a log-in screen that goes away after a user logs in. I like to call these things “temporally relevant” i.e. they are relevant based on timing.

On the other hand, ARIA 1.1 says:

[The aria-hidden state] indicates whether an element is exposed to the accessibility API.

In other words, elements with aria-hidden="true" are removed from the accessibility tree, which most assistive technology honors, and elements with aria-hidden="false" will definitely be exposed to the tree. Elements without the aria-hidden attribute are in the "undefined (default)" state, which means user agents should expose it to the tree based on its rendering. E.g. a user agent may decide to remove it if its text color matches its background color.

Now let’s compare semantics. It’s appropriate to use hidden, but not aria-hidden, for an element that is not yet “temporally relevant”, but that might become relevant in the future (in which case you would use dynamic scripts to remove the hidden attribute). Conversely, it’s appropriate to use aria-hidden, but not hidden, on an element that is always relevant, but with which you don’t want to clutter the accessibility API; such elements might include “visual flair”, like icons and/or imagery that are not essential for the user to consume.

Effective Difference

The semantics have predictable effects in browsers/user agents. The reason I make a distinction is that user agent behavior is recommended, but not required by the specifications.

The hidden attribute should hide an element from all presentations, including printers and screen readers (assuming these devices honor the HTML specs). If you want to remove an element from the accessibility tree as well as visual media, hidden would do the trick. However, do not use hidden just because you want this effect. Ask yourself if hidden is semantically correct first (see above). If hidden is not semantically correct, but you still want to visually hide the element, you can use other techniques such as CSS.

Elements with aria-hidden="true" are not exposed to the accessibility tree, so for example, screen readers won’t announce them. This technique should be used carefully, as it will provide different experiences to different users: accessible user agents won’t announce/render them, but they are still rendered on visual agents. This can be a good thing when done correctly, but it has the potential to be abused.

Syntactic Difference

Lastly, there is a difference in syntax between the two attributes.

hidden is a boolean attribute, meaning if the attribute is present it is true—regardless of whatever value it might have—and if the attribute is absent it is false. For the true case, the best practice is to either use no value at all (<div hidden>...</div>), or the empty string value (<div hidden="">...</div>). I would not recommend hidden="true" because someone reading/updating your code might infer that hidden="false" would have the opposite effect, which is simply incorrect.

aria-hidden, by contrast, is an enumerated attribute, allowing one of a finite list of values. If the aria-hidden attribute is present, its value must be either "true" or "false". If you want the "undefined (default)" state, remove the attribute altogether.


Further reading: https://github.com/chharvey/chharvey.github.io/wiki/Hidden-Content

PHP multidimensional array search by value

/**
 * searches a simple as well as multi dimension array
 * @param type $needle
 * @param type $haystack
 * @return boolean
 */
public static function in_array_multi($needle, $haystack){
    $needle = trim($needle);
    if(!is_array($haystack))
        return False;

    foreach($haystack as $key=>$value){
        if(is_array($value)){
            if(self::in_array_multi($needle, $value))
                return True;
            else
               self::in_array_multi($needle, $value);
        }
        else
        if(trim($value) === trim($needle)){//visibility fix//
            error_log("$value === $needle setting visibility to 1 hidden");
            return True;
        }
    }

    return False;
}

Change drive in git bash for windows

How I do it in Windows 10

Go to your folder directory you want to open in git bash like so

enter image description here

After you have reached the folder simply type git bash in the top navigation area like so and hit enter.

enter image description here

A git bash for the destined folder will open for you.

enter image description here

Hope that helps.

equivalent of vbCrLf in c#

Add a reference to Microsoft.VisualBasic to your project.

Then insert the using statement

using Microsoft.VisualBasic;

Use the defined constant vbCrLf:

private const string myString = "abc" + Constants.vbCrLf;

How to get string objects instead of Unicode from JSON?

Mike Brennan's answer is close, but there is no reason to re-traverse the entire structure. If you use the object_hook_pairs (Python 2.7+) parameter:

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

With it, you get each JSON object handed to you, so you can do the decoding with no need for recursion:

def deunicodify_hook(pairs):
    new_pairs = []
    for key, value in pairs:
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        if isinstance(key, unicode):
            key = key.encode('utf-8')
        new_pairs.append((key, value))
    return dict(new_pairs)

In [52]: open('test.json').read()
Out[52]: '{"1": "hello", "abc": [1, 2, 3], "def": {"hi": "mom"}, "boo": [1, "hi", "moo", {"5": "some"}]}'                                        

In [53]: json.load(open('test.json'))
Out[53]: 
{u'1': u'hello',
 u'abc': [1, 2, 3],
 u'boo': [1, u'hi', u'moo', {u'5': u'some'}],
 u'def': {u'hi': u'mom'}}

In [54]: json.load(open('test.json'), object_pairs_hook=deunicodify_hook)
Out[54]: 
{'1': 'hello',
 'abc': [1, 2, 3],
 'boo': [1, 'hi', 'moo', {'5': 'some'}],
 'def': {'hi': 'mom'}}

Notice that I never have to call the hook recursively since every object will get handed to the hook when you use the object_pairs_hook. You do have to care about lists, but as you can see, an object within a list will be properly converted, and you don't have to recurse to make it happen.

EDIT: A coworker pointed out that Python2.6 doesn't have object_hook_pairs. You can still use this will Python2.6 by making a very small change. In the hook above, change:

for key, value in pairs:

to

for key, value in pairs.iteritems():

Then use object_hook instead of object_pairs_hook:

In [66]: json.load(open('test.json'), object_hook=deunicodify_hook)
Out[66]: 
{'1': 'hello',
 'abc': [1, 2, 3],
 'boo': [1, 'hi', 'moo', {'5': 'some'}],
 'def': {'hi': 'mom'}}

Using object_pairs_hook results in one less dictionary being instantiated for each object in the JSON object, which, if you were parsing a huge document, might be worth while.

Simplest way to download and unzip files in Node.js cross-platform?

I tried a few of the nodejs unzip libraries including adm-zip and unzip, then settled on extract-zip which is a wrapper around yauzl. Seemed the simplest to implement.

https://www.npmjs.com/package/extract-zip

var extract = require('extract-zip')
extract(zipfile, { dir: outputPath }, function (err) {
   // handle err
})

PIL image to array (numpy array to array) - Python

I think what you are looking for is:

list(im.getdata())

or, if the image is too big to load entirely into memory, so something like that:

for pixel in iter(im.getdata()):
    print pixel

from PIL documentation:

getdata

im.getdata() => sequence

Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).

Retain precision with double in Java

As others have mentioned, you'll probably want to use the BigDecimal class, if you want to have an exact representation of 11.4.

Now, a little explanation into why this is happening:

The float and double primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.

More specifically, a double-precision floating point value such as the double type is a 64-bit value, where:

  • 1 bit denotes the sign (positive or negative).
  • 11 bits for the exponent.
  • 52 bits for the significant digits (the fractional part as a binary).

These parts are combined to produce a double representation of a value.

(Source: Wikipedia: Double precision)

For a detailed description of how floating point values are handled in Java, see the Section 4.2.3: Floating-Point Types, Formats, and Values of the Java Language Specification.

The byte, char, int, long types are fixed-point numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999 as the result of 5.6 + 5.8.

When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.

As has been mentioned several times already, Java has a BigDecimal class which will handle very large numbers and very small numbers.

From the Java API Reference for the BigDecimal class:

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10^-scale).

There has been many questions on Stack Overflow relating to the matter of floating point numbers and its precision. Here is a list of related questions that may be of interest:

If you really want to get down to the nitty gritty details of floating point numbers, take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Uploading files to file server using webclient class

when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

Concatenation of strings in Lua

Strings can be joined together using the concatenation operator ".."

this is the same for variables I think

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Custom checkbox image android

Based on the Enselic and Rahul answers.

It works for me (before and after API 21):

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:text=""
    android:gravity="center"

    android:background="@drawable/checkbox_selector"
    android:button="@null"
    app:buttonCompat="@null" />

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

How do I combine a background-image and CSS3 gradient on the same element?

If you have to get gradients and background images working together in IE 9 (HTML 5 & HTML 4.01 Strict), add the following attribute declaration to your css class and it should do the trick:

filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr='#000000', endColorstr='#ff00ff'), progid:DXImageTransform.Microsoft.AlphaImageLoader(src='[IMAGE_URL]', sizingMethod='crop');

Notice that you use the filter attribute and that there are two instances of progid:[val] separated by a comma before you close the attribute value with a semicolon. Here's the fiddle. Also notice that when you look at the fiddle the gradient extends beyond the rounded corners. I don't have a fix for that other not using rounded corners. Also note that when using a relative path in the src [IMAGE_URL] attribute, the path is relative to the document page and not the css file (See source).

This article (http://coding.smashingmagazine.com/2010/04/28/css3-solutions-for-internet-explorer/) is what lead me to this solution. It's pretty helpful for IE-specific CSS3.

Hibernate, @SequenceGenerator and allocationSize

Steve Ebersole & other members,
Would you kindly explain the reason for an id with a larger gap(by default 50)? I am using Hibernate 4.2.15 and found the following code in org.hibernate.id.enhanced.OptimizerFactory cass.

if ( lo > maxLo ) {
   lastSourceValue = callback.getNextValue();
   lo = lastSourceValue.eq( 0 ) ? 1 : 0;
   hi = lastSourceValue.copy().multiplyBy( maxLo+1 ); 
}  
value = hi.copy().add( lo++ );

Whenever it hits the inside of the if statement, hi value is getting much larger. So, my id during the testing with the frequent server restart generates the following sequence ids:
1, 2, 3, 4, 19, 250, 251, 252, 400, 550, 750, 751, 752, 850, 1100, 1150.

I know you already said it didn't conflict with the spec, but I believe this will be very unexpected situation for most developers.

Anyone's input will be much helpful.

Jihwan

UPDATE: ne1410s: Thanks for the edit.
cfrick: OK. I will do that. It was my first post here and wasn't sure how to use it.

Now, I understood better why maxLo was used for two purposes: Since the hibernate calls the DB sequence once, keep increase the id in Java level, and saves it to the DB, the Java level id value should consider how much was changed without calling the DB sequence when it calls the sequence next time.

For example, sequence id was 1 at a point and hibernate entered 5, 6, 7, 8, 9 (with allocationSize = 5). Next time, when we get the next sequence number, DB returns 2, but hibernate needs to use 10, 11, 12... So, that is why "hi = lastSourceValue.copy().multiplyBy( maxLo+1 )" is used to get a next id 10 from the 2 returned from the DB sequence. It seems only bothering thing was during the frequent server restart and this was my issue with the larger gap.

So, when we use the SEQUENCE ID, the inserted id in the table will not match with the SEQUENCE number in DB.

What is SaaS, PaaS and IaaS? With examples

I know this question has been answered a while ago but this could help.

What do the following terms mean?

SaaS

Software as a Service - Essentially, any application that runs with its contents from the cloud is referred to as Software as a Service, As long as you do not own it.

Some examples are Gmail, Netflix, OneDrive etc.

AUDIENCE: End users, everybody

IaaS

Infrastructure as a Service means that the provider allows a portion of their computing power to its customers, It is purchased by the potency of the computing power and they are bundled in Virtual Machines. A company like Google Cloud platform, AWS, Alibaba Cloud can be referred to as IaaS providers because they sell processing powers (servers, storage, networking) to their users in terms of Virtual Machines.

AUDIENCE: IT professionals, System Admins

PaaS

Platform as a Service is more like the middle-man between IaaS and SaaS, Instead of a customer having to deal with the nitty-gritty of servers, networks and storage, everything is readily available by the PaaS providers. Essentially a development environment is initialized to make building applications easier.

Examples would be Heroku, AWS Elastic Beanstalk, Google App Engine etc

AUDIENCE: Software developers.

There are various cloud services available today, such as Amazon's EC2 and AWS, Apache Hadoop, Microsoft Azure and many others. Which category does each belong to and why?

Amazon EC2 and AWS - is an Infrastructure as a Service because you'll need System Administrators to manage the working process of your operating system. There is no abstraction to build a fully featured app ordinarily. Microsoft Azure would also fall under this category following the aforementioned guidelines.

I really haven't used Apache Hadoop, so I really cannot say.

Test if string is URL encoded in PHP

I am using the following test to see if strings have been urlencoded:

if(urlencode($str) != str_replace(['%','+'], ['%25','%2B'], $str))

If a string has already been urlencoded, the only characters that will changed by double encoding are % (which starts all encoded character strings) and + (which replaces spaces.) Change them back and you should have the original string.

Let me know if this works for you.

Keyboard shortcuts in WPF

I found this to be exactly what I was looking for related to key binding in WPF:

<Window.InputBindings>
        <KeyBinding Modifiers="Control"
                    Key="N"
                    Command="{Binding CreateCustomerCommand}" />
</Window.InputBindings>

See blog post MVVM CommandReference and KeyBinding

Axios get access to response header fields

Faced same problem in asp.net core Hope this helps

public static class CorsConfig
{
    public static void AddCorsConfig(this IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder
                .WithExposedHeaders("X-Pagination")
                );
        });
    }
}

How to use the toString method in Java?

The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

in SQL*Plus you could also use a REFCURSOR variable:

SQL> VARIABLE x REFCURSOR
SQL> DECLARE
  2   V_Sqlstatement Varchar2(2000);
  3  BEGIN
  4   V_Sqlstatement := 'SELECT * FROM DUAL';
  5   OPEN :x for v_Sqlstatement;
  6  End;
  7  /

ProcÚdure PL/SQL terminÚe avec succÞs.

SQL> print x;

D
-
X

how to write javascript code inside php

You can put up all your JS like this, so it doesn't execute before your HTML is ready

$(document).ready(function() {
   // some code here
 });

Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload

How can I get the username of the logged-in user in Django?

For template, you can use

{% firstof request.user.get_full_name request.user.username %}

firstof will return the first one if not null else the second one

Rewrite URL after redirecting 404 error htaccess

Try adding this rule to the top of your htaccess:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]

Then under that (or any other rules that you have):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]

Xcode 10 Error: Multiple commands produce

My situation was similar to the Damo's one - some Products were added to the Pods project twice. The structure of my Podfile was:

# platform :ios, '11.0' 

def shared_pods
  use_frameworks!
  pod 'SharedPod1'
end

target 'Target1' do
  pod 'SomePod1'
  shared_pods
end

target 'Target2' do
  shared_pods
end

and all shared pods were added twice. Uncommenting of first line and then pod install solved the problem.

How can I divide two integers stored in variables in Python?

if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b

Try float(a)/b

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

com.sun.mail.util.MailLogger is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.

Oracle docs:

The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.

99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.

If you're using maven add the following dependency (you might want to change version):

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.0</version>
</dependency>

How to stop INFO messages displaying on spark console?

If anyone else is stuck on this,

nothing of the above worked for me. I had to remove

implementation group: "ch.qos.logback", name: "logback-classic", version: "1.2.3"
implementation group: 'com.typesafe.scala-logging', name: "scala-logging_$scalaVersion", version: '3.9.2'

from my build.gradle for the logs to disappear. TLDR: Don't import any other logging frameworks, you should be fine just using org.apache.log4j.Logger

Android: how to convert whole ImageView to Bitmap?

Have you tried:

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

How to join entries in a set into one string?

I think you just have it backwards.

print ", ".join(set_3)

Rails create or update magic?

In Rails 4 you can add to a specific model:

def self.update_or_create(attributes)
  assign_or_new(attributes).save
end

def self.assign_or_new(attributes)
  obj = first || new
  obj.assign_attributes(attributes)
  obj
end

and use it like

User.where(email: "[email protected]").update_or_create(name: "Mr A Bbb")

Or if you'd prefer to add these methods to all models put in an initializer:

module ActiveRecordExtras
  module Relation
    extend ActiveSupport::Concern

    module ClassMethods
      def update_or_create(attributes)
        assign_or_new(attributes).save
      end

      def update_or_create!(attributes)
        assign_or_new(attributes).save!
      end

      def assign_or_new(attributes)
        obj = first || new
        obj.assign_attributes(attributes)
        obj
      end
    end
  end
end

ActiveRecord::Base.send :include, ActiveRecordExtras::Relation

Python: Checking if a 'Dictionary' is empty doesn't seem to work

A dictionary can be automatically cast to boolean which evaluates to False for empty dictionary and True for non-empty dictionary.

if myDictionary: non_empty_clause()
else: empty_clause()

If this looks too idiomatic, you can also test len(myDictionary) for zero, or set(myDictionary.keys()) for an empty set, or simply test for equality with {}.

The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.

  1. The return False statement is indented one level too deep. It should be outside the for loop and at the same level as the for statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives.
  2. If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
  3. Let us say you correct the indentation of the return False statement and bring it outside the for loop. Then what you get is the boolean OR of all the keys, or False if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.

myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}

How can I delete an item from an array in VB.NET?

The variable i represents the index of the element you want to delete:

System.Array.Clear(ArrayName, i, 1)

Generate a UUID on iOS from Swift

Try this one:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3/4/5

let uuid = UUID().uuidString
print(uuid)

How to drop a table if it exists?

A better visual and easy way, if you are using Visual Studio, just open from menu bar,

View -> SQL Server Object Explorer

it should open like shown here

enter image description here

Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.

enter image description here

This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

Oracle ORA-12154: TNS: Could not resolve service name Error?

It has nothing to do with a space embedded in the folder structure.

I had the same problem. But when I created an environmental variable (defined both at the system- and user-level) called TNS_HOME and made it to point to the folder where TNSNAMES.ORA existed, the problem was resolved. Voila!

venki

jQuery load more data on scroll

The accepted answer of this question has some issue with chrome when the window is zoomed in to a value >100%. Here is the code recommended by chrome developers as part of a bug i had raised on the same.

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()){
     //Your code here
  }
});

For reference:

Related SO question

Chrome Bug

Count number of times value appears in particular column in MySQL

select name, count(*) from table group by name;

i think should do it

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.

If you add / before /n, it should work, you need to escape new line character.

"Hello there //n start coding"

The result should be as following

Hello there
start coding

Vertical Menu in Bootstrap

here is vertical menu base on Bootstrap http://www.okvee.net/articles/okvee-bootstrap-sidebar-menu it is also support responsive design.

How do you compare structs for equality in C?

C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.

Can't drop table: A foreign key constraint fails

This probably has the same table to other schema the reason why you're getting that error.

You need to drop first the child row then the parent row.

How to copy data from one table to another new table in MySQL?

IF the table is existed. you can try insert into table_name select * from old_tale;

IF the table is not existed. you should try create table table_name like old_table; insert into table_name select * from old_tale;

Append text with .bat

I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.

http://technet.microsoft.com/en-us/library/bb490986.aspx

Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.

Is the NOLOCK (Sql Server hint) bad practice?

If you don't care about dirty reads (i.e. in a predominately READ situation), then NOLOCK is fine.

BUT, be aware that the majority of locking problems are due to not having the 'correct' indexes for your query workload (assuming the hardware is up to the task).

And the guru's explanation was correct. It is usually a band-aid solution to a more serious problem.

Edit: I'm definitely not suggesting that NOLOCK should be used. I guess I should have made that obviously clear. (I would only ever use it, in extreme circumstances where I had analysed that it was OK). AS an example, a while back I worked on some TSQL that had been sprinkled with NOLOCK to try and alleviate locking problems. I removed them all, implemented the correct indexes, and ALL of the deadlocks went away.

Concatenate string with field value in MySQL

Here is a great answer to that:

SET sql_mode='PIPES_AS_CONCAT';

Find more here: https://stackoverflow.com/a/24777235/4120319

Here's the full SQL:

SET sql_mode='PIPES_AS_CONCAT';

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = 'category_id=' || tableOne.category_id;

Why can templates only be implemented in the header file?

Actually, prior to C++11 the standard defined the export keyword that would make it possible to declare templates in a header file and implement them elsewhere.

None of the popular compilers implemented this keyword. The only one I know about is the frontend written by the Edison Design Group, which is used by the Comeau C++ compiler. All others required you to write templates in header files, because the compiler needs the template definition for proper instantiation (as others pointed out already).

As a result, the ISO C++ standard committee decided to remove the export feature of templates with C++11.

What is the difference between encrypting and signing in asymmetric encryption?

You are describing exactly how and why signing is used in public key cryptography. Note that it's very dangerous to sign (or encrypt) aritrary messages supplied by others - this allows attacks on the algorithms that could compromise your keys.

How to copy file from one location to another location?

You can use this (or any variant):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.

Since you're not sure how to temporarily store files, take a look at ArrayList:

List<File> files = new ArrayList();
files.add(foundFile);

To move a List of files into a single directory:

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
    Files.copy(file.toPath(),
        (new File(path + file.getName())).toPath(),
        StandardCopyOption.REPLACE_EXISTING);
}

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Running shell command and capturing the output

eg, execute('ls -ahl') differentiated three/four possible returns and OS platforms:

  1. no output, but run successfully
  2. output empty line, run successfully
  3. run failed
  4. output something, run successfully

function below

def execute(cmd, output=True, DEBUG_MODE=False):
"""Executes a bash command.
(cmd, output=True)
output: whether print shell output to screen, only affects screen display, does not affect returned values
return: ...regardless of output=True/False...
        returns shell output as a list with each elment is a line of string (whitespace stripped both sides) from output
        could be 
        [], ie, len()=0 --> no output;    
        [''] --> output empty line;     
        None --> error occured, see below

        if error ocurs, returns None (ie, is None), print out the error message to screen
"""
if not DEBUG_MODE:
    print "Command: " + cmd

    # https://stackoverflow.com/a/40139101/2292993
    def _execute_cmd(cmd):
        if os.name == 'nt' or platform.system() == 'Windows':
            # set stdin, out, err all to PIPE to get results (other than None) after run the Popen() instance
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        else:
            # Use bash; the default is sh
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, executable="/bin/bash")

        # the Popen() instance starts running once instantiated (??)
        # additionally, communicate(), or poll() and wait process to terminate
        # communicate() accepts optional input as stdin to the pipe (requires setting stdin=subprocess.PIPE above), return out, err as tuple
        # if communicate(), the results are buffered in memory

        # Read stdout from subprocess until the buffer is empty !
        # if error occurs, the stdout is '', which means the below loop is essentially skipped
        # A prefix of 'b' or 'B' is ignored in Python 2; 
        # it indicates that the literal should become a bytes literal in Python 3 
        # (e.g. when code is automatically converted with 2to3).
        # return iter(p.stdout.readline, b'')
        for line in iter(p.stdout.readline, b''):
            # # Windows has \r\n, Unix has \n, Old mac has \r
            # if line not in ['','\n','\r','\r\n']: # Don't print blank lines
                yield line
        while p.poll() is None:                                                                                                                                        
            sleep(.1) #Don't waste CPU-cycles
        # Empty STDERR buffer
        err = p.stderr.read()
        if p.returncode != 0:
            # responsible for logging STDERR 
            print("Error: " + str(err))
            yield None

    out = []
    for line in _execute_cmd(cmd):
        # error did not occur earlier
        if line is not None:
            # trailing comma to avoid a newline (by print itself) being printed
            if output: print line,
            out.append(line.strip())
        else:
            # error occured earlier
            out = None
    return out
else:
    print "Simulation! The command is " + cmd
    print ""

What's the difference between align-content and align-items?

Having read some of the answers, they identify correctly that align-content takes no affect if the flex content is not wrapped. However what they don't understand is align-items still plays an important role when there is wrapped content:

In the following two examples, align-items is used to center the items within each row, then we change align-content to see it's effect.

Example 1:

align-content: flex-start;

enter image description here

Example 2:

    align-content: flex-end;

enter image description here

Here's the code:

<div class="container">
    <div class="child" style="height: 30px;">1</div>
    <div class="child" style="height: 50px;">2</div>
    <div class="child" style="height: 60px;">3</div>
    <div class="child" style="height: 40px;">4</div>
    <div class="child" style="height: 50px;">5</div>
    <div class="child" style="height: 20px;">6</div>
    <div class="child" style="height: 90px;">7</div>
    <div class="child" style="height: 50px;">8</div>
    <div class="child" style="height: 30px;">9</div>
    <div class="child" style="height: 40px;">10</div>
    <div class="child" style="height: 30px;">11</div>
    <div class="child" style="height: 60px;">12</div>
</div>

<style>
.container {
    display: flex;
    width: 300px;
    flex-flow: row wrap;
    justify-content: space-between;
    align-items: center;
    align-content: flex-end;
    background: lightgray;
    height: 400px;
}
.child {
    padding: 12px;
    background: red;
    border: solid 1px black;
}
</style>

Converting string to title case

Personally I tried the TextInfo.ToTitleCase method, but, I don´t understand why it doesn´t work when all chars are upper-cased.

Though I like the util function provided by Winston Smith, let me provide the function I'm currently using:

public static String TitleCaseString(String s)
{
    if (s == null) return s;

    String[] words = s.Split(' ');
    for (int i = 0; i < words.Length; i++)
    {
        if (words[i].Length == 0) continue;

        Char firstChar = Char.ToUpper(words[i][0]); 
        String rest = "";
        if (words[i].Length > 1)
        {
            rest = words[i].Substring(1).ToLower();
        }
        words[i] = firstChar + rest;
    }
    return String.Join(" ", words);
}

Playing with some tests strings:

String ts1 = "Converting string to title case in C#";
String ts2 = "C";
String ts3 = "";
String ts4 = "   ";
String ts5 = null;

Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts1)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts2)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts3)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts4)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts5)));

Giving output:

|Converting String To Title Case In C#|
|C|
||
|   |
||

How to list all `env` properties within jenkins pipeline job?

another way to get exactly the output mentioned in the question:

envtext= "printenv".execute().text
envtext.split('\n').each
{   envvar=it.split("=")
    println envvar[0]+" is "+envvar[1]
}

This can easily be extended to build a map with a subset of env vars matching a criteria:

envdict=[:]
envtext= "printenv".execute().text
envtext.split('\n').each
{   envvar=it.split("=")
    if (envvar[0].startsWith("GERRIT_"))
        envdict.put(envvar[0],envvar[1])
}    
envdict.each{println it.key+" is "+it.value}

What is the difference between DAO and Repository patterns?

DAO and Repository pattern are ways of implementing Data Access Layer (DAL). So, let's start with DAL, first.

Object-oriented applications that access a database, must have some logic to handle database access. In order to keep the code clean and modular, it is recommended that database access logic should be isolated into a separate module. In layered architecture, this module is DAL.

So far, we haven't talked about any particular implementation: only a general principle that putting database access logic in a separate module.

Now, how we can implement this principle? Well, one know way of implementing this, in particular with frameworks like Hibernate, is the DAO pattern.

DAO pattern is a way of generating DAL, where typically, each domain entity has its own DAO. For example, User and UserDao, Appointment and AppointmentDao, etc. An example of DAO with Hibernate: http://gochev.blogspot.ca/2009/08/hibernate-generic-dao.html.

Then what is Repository pattern? Like DAO, Repository pattern is also a way achieving DAL. The main point in Repository pattern is that, from the client/user perspective, it should look or behave as a collection. What is meant by behaving like a collection is not that it has to be instantiated like Collection collection = new SomeCollection(). Instead, it means that it should support operations such as add, remove, contains, etc. This is the essence of Repository pattern.

In practice, for example in the case of using Hibernate, Repository pattern is realized with DAO. That is an instance of DAL can be both at the same an instance of DAO pattern and Repository pattern.

Repository pattern is not necessarily something that one builds on top of DAO (as some may suggest). If DAOs are designed with an interface that supports the above-mentioned operations, then it is an instance of Repository pattern. Think about it, If DAOs already provide a collection-like set of operations, then what is the need for an extra layer on top of it?

SQLAlchemy equivalent to SQL "LIKE" statement

try this code

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

How to check whether a int is not null or empty?

An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.

Example:

int x;

// Some Code...

if (x <= 0 || x > 0){
    // What you want the code to do if x has a value
} else {
    // What you want the code to do if x has no value 
}

Disclaimer: I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.

what do these symbolic strings mean: %02d %01d?

http://en.wikipedia.org/wiki/Printf#printf_format_placeholders

The article is about the class of printf functions, in several languages, from the 50s to this day.

Select columns from result set of stored procedure

Can you split up the query? Insert the stored proc results into a table variable or a temp table. Then, select the 2 columns from the table variable.

Declare @tablevar table(col1 col1Type,..
insert into @tablevar(col1,..) exec MyStoredProc 'param1', 'param2'

SELECT col1, col2 FROM @tablevar

Use placeholders in yaml

With Yglu Structural Templating, your example can be written:

foo: !()
  !? $.propname: 
     type: number 
     default: !? $.default

bar:
  !apply .foo: 
    propname: "some_prop"
    default: "some default"

Disclaimer: I am the author or Yglu.

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

In SQL Server, how to create while loop in select

  1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
  2. Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.

SQL query to select dates between two dates

Since a datetime without a specified time segment will have a value of date 00:00:00.000, if you want to be sure you get all the dates in your range, you must either supply the time for your ending date or increase your ending date and use <.

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date between '2011/02/25' and '2011/02/27 23:59:59.999'

OR

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date >= '2011/02/25' and Date < '2011/02/28'

OR

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'

DO NOT use the following, as it could return some records from 2011/02/28 if their times are 00:00:00.000.

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date between '2011/02/25' and '2011/02/28'

Convert all strings in a list to int

Use the map function (in Python 2.x):

results = map(int, results)

In Python 3, you will need to convert the result from map to a list:

results = list(map(int, results))

Export DataTable to Excel File

I had a project that I also needed an exact replica of a DataTable in Excel format. Using ClosedXML, the following code did exactly that for me.

using ClosedXML.Excel;

        private void DumpDataTableToExcel(DataTable dt, string SavePathAndFilename)
        {
            try
            {
                using (XLWorkbook excelWorkbook = new XLWorkbook())
                {
                    excelWorkbook.AddWorksheet(dt);
                    excelWorkbook.SaveAs(SavePathAndFilename);
                }
            }
            catch
            {
                //Insert error handling here...
            }
        }

This method will use your DataTable's column names as the column names in Excel and the DataTable name itself will be the sheet name. Hard to accomplish all of this with fewer lines of code.

Adding ClosedXML to your project is equally simple. There are instructions in the link above as well as directly on nuget.org.

Git submodule update

This GitPro page does summarize the consequence of a git submodule update nicely

When you run git submodule update, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.


Note March 2013:

As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 
# or (with rebase)
git submodule update --rebase --remote

See "git submodule update --remote vs git pull".

MindTooth's answer illustrate a manual update (without local configuration):

git submodule -q foreach git pull -q origin master

In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.

The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).


To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.

Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:


So, to answer your questions:

can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?

You can create a branch and push modifications.

WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.

how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)

The page "Understanding Submodules" can help

Git submodules are implemented using two moving parts:

  • the .gitmodules file and
  • a special kind of tree object.

These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.


From the git submodule page

you cannot modify the contents of the submodule from within the main project

100% correct: you cannot modify a submodule, only refer to one of its commits.

This is why, when you do modify a submodule from within the main project, you:

  • need to commit and push within the submodule (to the upstream module), and
  • then go up in your main project, and re-commit (in order for that main project to refer to the new submodule commit you just created and pushed)

A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").

A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.

However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.

But the main idea remains: referencing specific components which:

  • have their own lifecycle
  • have their own set of tags
  • have their own development

The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)

If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.

Does that help understanding the true nature of Git Submodules?

Delegates in swift?

In swift 4.0

Create a delegate on class that need to send some data or provide some functionality to other classes

Like

protocol GetGameStatus {
    var score: score { get }
    func getPlayerDetails()
}

After that in the class that going to confirm to this delegate

class SnakesAndLadders: GetGameStatus {
    func getPlayerDetails() {

 }
}

Django: List field in model?

I think it will help you.

from django.db import models
import ast

class ListField(models.TextField):
    __metaclass__ = models.SubfieldBase
    description = "Stores a python list"

    def __init__(self, *args, **kwargs):
        super(ListField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value:
            value = []

        if isinstance(value, list):
            return value

        return ast.literal_eval(value)

    def get_prep_value(self, value):
        if value is None:
            return value

        return unicode(value)

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

class ListModel(models.Model):
    test_list = ListField()

Example :

>>> ListModel.objects.create(test_list= [[1,2,3], [2,3,4,4]])

>>> ListModel.objects.get(id=1)

>>> o = ListModel.objects.get(id=1)
>>> o.id
1L
>>> o.test_list
[[1, 2, 3], [2, 3, 4, 4]]
>>> 

How to load a jar file at runtime

I googled a bit, and found this code here:

File file = getJarFileToLoadFrom();   
String lcStr = getNameOfClassToLoad();   
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");    
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });   
Class loadedClass = cl.loadClass(lcStr);   

Can anyone share opinions/comments/answers regarding this approach?

How to specify credentials when connecting to boto3 S3?

You can get a client with new session directly like below.

 s3_client = boto3.client('s3', 
                      aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, 
                      aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, 
                      region_name=REGION_NAME
                      )

Mongoose delete array element in document and save

keywords = [1,2,3,4];
doc.array.pull(1) //this remove one item from a array
doc.array.pull(...keywords) // this remove multiple items in a array

if you want to use ... you should call 'use strict'; at the top of your js file; :)

PHP Error: Cannot use object of type stdClass as array (array and object issues)

The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

The simplest method - access $blog as an object directly:

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

The alternative method - access $blog as an array:

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

Better than either of the above - Inline PHP Syntax

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

Hope this helped.

How to make a great R reproducible example

To quickly create a dput of your data you can just copy (a piece of) the data to your clipboard and run the following in R:

for data in Excel:

dput(read.table("clipboard",sep="\t",header=TRUE))

for data in a txt file:

dput(read.table("clipboard",sep="",header=TRUE))

You can change the sep in the latter if necessary. This will only work if your data is in the clipboard of course.

Why does Java have transient fields?

A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

How to set css style to asp.net button?

If you have a button in asp.net design page like "Default.asp" and you want to create CSS file and specified attributes for a button,labels or other controller. Then first of all create a css page

  1. Right click on Project
  2. Add new item
  3. Select StyleSheet

now you have a css page now write these code in your css page(StyleSheet.css)

StyleSheet.css

.mybtnstyle
{
 border:1px solid Red;
 background-color:Red;
 border-style:groove;
 border-top:5px;
 outline-style:dotted;
}

Default.asp

{

  <head> 
  <title> testing.com </title>
 </head>
<body>
 <b>Using Razer<b/>
<form id="form1" runat="server">
 <link id="Link1" rel="stylesheet" runat="server" media="screen" href="Stylesheet1.css" />
 <asp:Button ID="mybtn" class="mybtn" runat="server" Width="339px"/>
 </form>
 </body>
</html>

}

Multiple select statements in Single query

If you use MyISAM tables, the fastest way is querying directly the stats:

select table_name, table_rows 
     from information_schema.tables 
where 
     table_schema='databasename' and 
     table_name in ('user_table','cat_table','course_table')

If you have InnoDB you have to query with count() as the reported value in information_schema.tables is wrong.

Open Redis port for remote connections

  1. Open the file at location /etc/redis.conf

  2. Comment out bind 127.0.0.1

  3. Restart Redis:

     sudo systemctl start redis.service
    
  4. Disable Firewalld:

     systemctl disable firewalld
    
  5. Stop Firewalld:

     systemctl stop firewalld
    

Then try:

redis-cli -h 192.168.0.2(ip) -a redis(username)

Regex: matching up to the first occurrence of a character

I found that

/^[^,]*,/

works well.

',' being the "delimiter" here.

How to open in default browser in C#

In UWP:

await Launcher.LaunchUriAsync(new Uri("http://google.com"));

How to set text color to a text view programmatically

Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:

textView.setTextColor(getResources().getColor(R.color.some_color));

Please note that from API 23, getResources().getColor() is deprecated. Use instead:

textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));

where the required color is defined in an xml as:

<resources>
  <color name="some_color">#bdbdbd</color>
</resources>

Update:

This method was deprecated in API level 23. Use getColor(int, Theme) instead.

Check this.

ASP.NET set hiddenfield a value in Javascript

  • First you need to create the Hidden Field properly

    <asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>

  • Then you need to set value to the hidden field

    If you aren't using Jquery you should use it:

    document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";

    If you are using Jquery, this is how it should be:

    $("#<%= hdntxtbxTaksit.ClientID %>").val("test");

"Uncaught TypeError: Illegal invocation" in Chrome

You can also use:

var obj = {
    alert: alert.bind(window)
};
obj.alert('I´m an alert!!');

SOAP vs REST (differences)

REST vs SOAP is not the right question to ask.

REST, unlike SOAP is not a protocol.

REST is an architectural style and a design for network-based software architectures.

REST concepts are referred to as resources. A representation of a resource must be stateless. It is represented via some media type. Some examples of media types include XML, JSON, and RDF. Resources are manipulated by components. Components request and manipulate resources via a standard uniform interface. In the case of HTTP, this interface consists of standard HTTP ops e.g. GET, PUT, POST, DELETE.

@Abdulaziz's question does illuminate the fact that REST and HTTP are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.

Fundamental REST Principles

Client-Server Communication

Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in principle.

Stateless

Each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client.

Cacheable

Cache constraints may be used, thus enabling response data to be marked as cacheable or not-cacheable. Any data marked as cacheable may be reused as the response to the same subsequent request.

Uniform Interface

All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!

The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.

See this blog post on REST Design Principles for more details on REST and the above stated bullets.

EDIT: update content based on comments

Difference between adjustResize and adjustPan in android?

From the Android Developer Site link

"adjustResize"

The activity's main window is always resized to make room for the soft keyboard on screen.

"adjustPan"

The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

according to your comment, use following in your activity manifest

<activity android:windowSoftInputMode="adjustResize"> </activity>

Transfer data between iOS and Android via Bluetooth?

You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.

Pointer-to-pointer dynamic two-dimensional array

This code works well with very few requirements on external libraries and shows a basic use of int **array.

This answer shows that each array is dynamically sized, as well as how to assign a dynamically sized leaf array into the dynamically sized branch array.

This program takes arguments from STDIN in the following format:

2 2   
3 1 5 4
5 1 2 8 9 3
0 1
1 3

Code for program below...

#include <iostream>

int main()
{
    int **array_of_arrays;

    int num_arrays, num_queries;
    num_arrays = num_queries = 0;
    std::cin >> num_arrays >> num_queries;
    //std::cout << num_arrays << " " << num_queries;

    //Process the Arrays
    array_of_arrays = new int*[num_arrays];
    int size_current_array = 0;

    for (int i = 0; i < num_arrays; i++)
    {
        std::cin >> size_current_array;
        int *tmp_array = new int[size_current_array];
        for (int j = 0; j < size_current_array; j++)
        {
            int tmp = 0;
            std::cin >> tmp;
            tmp_array[j] = tmp;
        }
        array_of_arrays[i] = tmp_array;
    }


    //Process the Queries
    int x, y;
    x = y = 0;
    for (int q = 0; q < num_queries; q++)
    {
        std::cin >> x >> y;
        //std::cout << "Current x & y: " << x << ", " << y << "\n";
        std::cout << array_of_arrays[x][y] << "\n";
    }

    return 0;
}

It's a very simple implementation of int main and relies solely on std::cin and std::cout. Barebones, but good enough to show how to work with simple multidimensional arrays.

Can a html button perform a POST request?

You can do that with a little help of JS. In the example below, a POST request is being submitted on a button click using the fetch method:

_x000D_
_x000D_
const button = document.getElementById('post-btn');_x000D_
_x000D_
button.addEventListener('click', async _ => {_x000D_
  try {     _x000D_
    const response = await fetch('yourUrl', {_x000D_
      method: 'post',_x000D_
      body: {_x000D_
        // Your body_x000D_
      }_x000D_
    });_x000D_
    console.log('Completed!', response);_x000D_
  } catch(err) {_x000D_
    console.error(`Error: ${err}`);_x000D_
  }_x000D_
});
_x000D_
<button id="post-btn">I'm a button</button>
_x000D_
_x000D_
_x000D_

How to create an integer-for-loop in Ruby?

Try Below Simple Ruby Magics :)

(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

How do I check if file exists in jQuery or pure JavaScript?

With jQuery:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

EDIT:

Here is the code for checking 404 status, without using jQuery

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

Small changes and it could check for status HTTP status code 200 (success), instead.

EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:

function executeIfFileExist(src, callback) {
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function() {
        if (this.readyState === this.DONE) {
            callback()
        }
    }
    xhr.open('HEAD', src)
}

Hidden Features of C#?

InternalsVisibleTo attribute is one that is not that well known, but can come in increadibly handy in certain circumstances. It basically allows another assembly to be able to access "internal" elements of the defining assembly.

Best approach to converting Boolean object to string in java

public class Sandbox {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Boolean b = true;
        boolean z = false;
        echo (b);
        echo (z);
        echo ("Value of b= " + b +"\nValue of z= " + z);
    }

    public static void echo(Object obj){
        System.out.println(obj);
    } 

}
Result
--------------
true
false
Value of b= true
Value of z= false
--------------

WebDriver - wait for element using Java

This is how I do it in my code.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.

See also:

Git - Undo pushed commits

What I do in these cases is:

  • In the server, move the cursor back to the last known good commit:

    git push -f origin <last_known_good_commit>:<branch_name>
    
  • Locally, do the same:

    git reset --hard <last_known_good_commit>
    #         ^^^^^^
    #         optional
    



See a full example on a branch my_new_branch that I created for this purpose:

$ git branch
my_new_branch

This is the recent history after adding some stuff to myfile.py:

$ git log
commit 80143bcaaca77963a47c211a9cbe664d5448d546
Author: me
Date:   Wed Mar 23 12:48:03 2016 +0100

    Adding new stuff in myfile.py

commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit

I want to get rid of the last commit, which was already pushed, so I run:

$ git push -f origin b4zad078237fa48746a4feb6517fa409f6bf238e:my_new_branch
Total 0 (delta 0), reused 0 (delta 0)
To [email protected]:me/myrepo.git
 + 80143bc...b4zad07 b4zad078237fa48746a4feb6517fa409f6bf238e -> my_new_branch (forced update)

Nice! Now I see the file that was changed on that commit (myfile.py) shows in "not staged for commit":

$ git status
On branch my_new_branch
Your branch is up-to-date with 'origin/my_new_branch'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   myfile.py

no changes added to commit (use "git add" and/or "git commit -a")

Since I don't want these changes, I just move the cursor back locally as well:

$ git reset --hard b4zad078237fa48746a4feb6517fa409f6bf238e
HEAD is now at b4zad07 Initial commit

So now HEAD is in the previous commit, both in local and remote:

$ git log
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit

How to override the properties of a CSS class using another CSS class

There are different ways in which properties can be overridden. Assuming you have

.left { background: blue }

e.g. any of the following would override it:

a.background-none { background: none; }
body .background-none { background: none; }
.background-none { background: none !important; }

The first two “win” by selector specificity; the third one wins by !important, a blunt instrument.

You could also organize your style sheets so that e.g. the rule

.background-none { background: none; }

wins simply by order, i.e. by being after an otherwise equally “powerful” rule. But this imposes restrictions and requires you to be careful in any reorganization of style sheets.

These are all examples of the CSS Cascade, a crucial but widely misunderstood concept. It defines the exact rules for resolving conflicts between style sheet rules.

P.S. I used left and background-none as they were used in the question. They are examples of class names that should not be used, since they reflect specific rendering and not structural or semantic roles.

Run C++ in command prompt - Windows

This is what I used on MAC.

Use your preferred compiler.

Compile with gcc.

gcc -lstdc++ filename.cpp -o outputName

Or Compile with clang.

clang++ filename.cpp -o outputName

After done compiling. You can run it with.

./outputFile

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

How to workaround 'FB is not defined'?

Assuming FB is a variable containing the Facebook object, I'd try something like this:

if (typeof(FB) != 'undefined'
     && FB != null ) {
    // run the app
} else {
    // alert the user
}

In order to test that something is undefined in plain old JavaScript, you should use the "typeof" operator. The sample you show where you just compare it to the string 'undefined' will evaluate to false unless your FB object really does contain the string 'undefined'!

As an aside, you may wish to use various tools like Firebug (in Firefox) to see if you can work out why the Facebook file is not loading.

How to call a REST web service API from JavaScript?

I think add if (this.readyState == 4 && this.status == 200) to wait is better:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
        var response = xhttp.responseText;
        console.log("ok"+response);
    }
};
xhttp.open("GET", "your url", true);

xhttp.send();

npm WARN package.json: No repository field

use npm install -g angular-cli instead of
npm install -g@nagular/cli to install Angular

How to add an Access-Control-Allow-Origin header

For Java based Application add this to your web.xml file:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.ttf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.otf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.eot</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.woff</url-pattern>
</servlet-mapping>

endforeach in loops?

How about that?

<?php
    while($items = array_pop($lists)){
        echo "<ul>";
        foreach($items as $item){
            echo "<li>$item</li>";
        }
        echo "</ul>";
    }
?>

CSS to make table 100% of max-width

I had the same issue it was due to that I had the bootstrap class "hidden-lg" on the table which caused it to stupidly become display: block !important;

I wonder how Bootstrap never considered to just instead do this:

@media (min-width: 1200px) {
    .hidden-lg {
         display: none;
    }
}

And then just leave the element whatever display it had before for other screensizes.. Perhaps it is too advanced for them to figure out..

Anyway so:

table {
    display: table; /* check so these really applies */
    width: 100%;
}

should work

How can I get a first element from a sorted list?

If your collection is not a List (and thus you can't use get(int index)), then you can use the iterator:

Iterator iter = collection.iterator();
if (iter.hasNext()) {
    Object first = iter.next();
}

Sorting Python list based on the length of the string

Write a function lensort to sort a list of strings based on length.

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

Sql Query to list all views in an SQL Server 2005 database

Some time you need to access with schema name,as an example you are using AdventureWorks Database you need to access with schemas.

 SELECT s.name +'.'+v.name FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id 

How to determine the encoding of text?

Some encoding strategies, please uncomment to taste :

#!/bin/bash
#
tmpfile=$1
echo '-- info about file file ........'
file -i $tmpfile
enca -g $tmpfile
echo 'recoding ........'
#iconv -f iso-8859-2 -t utf-8 back_test.xml > $tmpfile
#enca -x utf-8 $tmpfile
#enca -g $tmpfile
recode CP1250..UTF-8 $tmpfile

You might like to check the encoding by opening and reading the file in a form of a loop... but you might need to check the filesize first :

#PYTHON
encodings = ['utf-8', 'windows-1250', 'windows-1252'] # add more
            for e in encodings:
                try:
                    fh = codecs.open('file.txt', 'r', encoding=e)
                    fh.readlines()
                    fh.seek(0)
                except UnicodeDecodeError:
                    print('got unicode error with %s , trying different encoding' % e)
                else:
                    print('opening the file with encoding:  %s ' % e)
                    break              

How to randomly select rows in SQL?

I have found this to work best for big data.

SELECT TOP 1 Column_Name FROM dbo.Table TABLESAMPLE(1 PERCENT);

TABLESAMPLE(n ROWS) or TABLESAMPLE(n PERCENT) is random but need to add the TOP n to get the correct sample size.

Using NEWID() is very slow on large tables.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

Unfortunately the link in the exception text, http://go.microsoft.com/fwlink/?LinkId=70353, is broken. However, it used to lead to http://msdn.microsoft.com/en-us/library/ms733768.aspx which explains how to set the permissions.

It basically informs you to use the following command:

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

You can get more help on the details using the help of netsh

For example: netsh http add ?

Gives help on the http add command.

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

Installed SSL certificate in certificate store, but it's not in IIS certificate list

I had the same in IIS 10.

I fixed it by importing the .pfx file using IIS manager.

Select server root (above the sites-node), click 'Server Certificates' in the right hand pane and import pfx there. Then I could select it from the dropdown when creating ssl binding for a website under sites

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Inserting a blank table row with a smaller height

I couldn't get anything to work until I tried this simple line:

<p style="margin-top:0; margin-bottom:0; line-height:.5"><br /></p>

which allows you to vary a filler line height to your hearts content (I was [probably MISusing Table to get three columns (boxes) of text which I then wanted to line up along the bottom)

I'm an amateur so would appreciate comments

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

What are the situations where "yield from" is useful?

Every situation where you have a loop like this:

for x in subgenerator:
  yield x

As the PEP describes, this is a rather naive attempt at using the subgenerator, it's missing several aspects, especially the proper handling of the .throw()/.send()/.close() mechanisms introduced by PEP 342. To do this properly, rather complicated code is necessary.

What is the classic use case?

Consider that you want to extract information from a recursive data structure. Let's say we want to get all leaf nodes in a tree:

def traverse_tree(node):
  if not node.children:
    yield node
  for child in node.children:
    yield from traverse_tree(child)

Even more important is the fact that until the yield from, there was no simple method of refactoring the generator code. Suppose you have a (senseless) generator like this:

def get_list_values(lst):
  for item in lst:
    yield int(item)
  for item in lst:
    yield str(item)
  for item in lst:
    yield float(item)

Now you decide to factor out these loops into separate generators. Without yield from, this is ugly, up to the point where you will think twice whether you actually want to do it. With yield from, it's actually nice to look at:

def get_list_values(lst):
  for sub in [get_list_values_as_int, 
              get_list_values_as_str, 
              get_list_values_as_float]:
    yield from sub(lst)

Why is it compared to micro-threads?

I think what this section in the PEP is talking about is that every generator does have its own isolated execution context. Together with the fact that execution is switched between the generator-iterator and the caller using yield and __next__(), respectively, this is similar to threads, where the operating system switches the executing thread from time to time, along with the execution context (stack, registers, ...).

The effect of this is also comparable: Both the generator-iterator and the caller progress in their execution state at the same time, their executions are interleaved. For example, if the generator does some kind of computation and the caller prints out the results, you'll see the results as soon as they're available. This is a form of concurrency.

That analogy isn't anything specific to yield from, though - it's rather a general property of generators in Python.

In Windows cmd, how do I prompt for user input and use the result in another command?

There are two possibilities.

  1. You forgot to put the %id% in the jstack call.

    jstack %id% > jstack.txt
    

So the whole correct batch file should be:

@echo off
set /p id=Enter ID: 
echo %id%
jstack %id% > jstack.txt

And/Or 2. You did put it in the code (and forgot to tell us in the question) but when you ran the batch file you hit the Enter key instead of typing an ID (say 1234).

What's happening is the result of these two mistakes: jstack is supposed to be called with the id that you supply it.

But in your case (according to the code you supplied in the question) you called it without any variable. You wrote:

jstack > jstack.txt

So when you run jstack with no variable it outputs the following:

Terminate batch file Y/N? 

Your second mistake is that you pressed Enter instead of giving a value when the program asked you: Enter ID:. If you would have put in an ID at this point, say 1234, the %id% variable would become that value, in our case 1234. But you did NOT supply a value and instead pressed Enter. When you don't give the variable any value, and if that variable was not set to anything else before, then the variable %id% is set to the prompt of the set command!! So now %id% is set to Enter ID: which was echoed on your screen as requested in the batch file BEFORE you called the jstack.

But I suspect you DID have the jstack %id% > jstack.txt in your batch file code with the %id (and omitted it by mistake from the question), and that you hit enter without typing in an id. The batch program then echoed the id, which is now "Enter ID:", and then ran jstack Enter ID: > jstack.txt

Jstack itself echoed the input, encountered a mistake and asked to terminate.
And all this was written into the jstack.txt file.

Class has no objects member

I've tried all possible solutions offered but unluckly my vscode settings won't changed its linter path. So, I tride to explore vscode settings in settings > User Settings > python. Find Linting: Pylint Path and change it to "pylint_django". Don't forget to change the linter to "pylint_django" at settings > User Settings > python configuration from "pyLint" to "pylint_django".

Linter Path Edit

Free tool to Create/Edit PNG Images?

ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?

Java equivalent of unsigned long long?

Depending on the operations you intend to perform, the outcome is much the same, signed or unsigned. However, unless you are using trivial operations you will end up using BigInteger.

What is LDAP used for?

That's a rather large question.

LDAP is a protocol for accessing a directory. A directory contains objects; generally those related to users, groups, computers, printers and so on; company structure information (although frankly you can extend it and store anything in there).

LDAP gives you query methods to add, update and remove objects within a directory (and a bunch more, but those are the central ones).

What LDAP does not do is provide a database; a database provides LDAP access to itself, not the other way around. It is much more than signup.

What's the difference between emulation and simulation?

I was confused between the two processes. I found this simple explaination about the difference between Emulators and Simulators

  1. Simulator:
    Suppose you have written assembly program in a file and corresponding exe file is ready. The simulator is the pc software which reads the instructions from the exe and 'minmics' the operation of the processor.

  2. Emulator:
    Emulator is a (PC software + a processor). The Processor can be plugged into the TARGET BOARD when you want to test the developed software in real time to check run time bugs. When not in use it can be unplugged. The Processor will have a parallel or JTAG interface with the PC for downloading the exe file for execution.

Hence, whereas the Simulator is slow in execution, Emulator will be able to give real time verification of the developed code. Generally you will test your developed code on simulator first and then go for checking on emulator.

source : http://www.dsprelated.com/groups/c6x/show/148.php

Combine two tables that have no common fields

This is a very strange request, and almost certainly something you'd never want to do in a real-world application, but from a purely academic standpoint it's an interesting challenge. With SQL Server 2005 you could use common table expressions and the row_number() functions and join on that:

with OrderedFoos as (
    select row_number() over (order by FooName) RowNum, *
    from Foos (nolock)
),
OrderedBars as (
    select row_number() over (order by BarName) RowNum, *
    from Bars (nolock)
)
select * 
from OrderedFoos f
    full outer join OrderedBars u on u.RowNum = f.RowNum

This works, but it's supremely silly and I offer it only as a "community wiki" answer because I really wouldn't recommend it.

Error: No default engine was specified and no extension was provided

Error: No default engine was specified and no extension was provided

I got the same problem(for doing a mean stack project)..the problem is i didn't mentioned the formate to install npm i.e; pug or jade,ejs etc. so to solve this goto npm and enter express --view=pug foldername. This will load necessary pug files(index.pug,layout.pug etc..) in ur given folder .

Push to GitHub without a password using ssh-key

As usual, create an SSH key and paste the public key to GitHub. Add the private key to ssh-agent. (I assume this is what you have done.)

To check everything is correct, use ssh -T [email protected]

Next, don't forget to modify the remote point as follows:

git remote set-url origin [email protected]:username/your-repository.git

How to convert 1 to true or 0 to false upon model fetch

All you need is convert string to int with + and convert the result to boolean with !!:

var response = {"isChecked":"1"};
response.isChecked = !!+response.isChecked

You can do this manipulation in the parse method:

parse: function (response) {
  response.isChecked = !!+response.isChecked;
  return response;
}

UPDATE: 7 years later, I find Number(string) conversion more elegant. Also mutating an object is not the best idea. That being said:

parse: function (response) {
  return Object.assign({}, response, {
    isChecked: !!Number(response.isChecked), // OR
    isChecked: Boolean(Number(response.isChecked))
  });
}

Pushing from local repository to GitHub hosted remote

open the command prompt Go to project directory

type git remote add origin your git hub repository location with.git

Convert interface{} to int

You need to do type assertion for converting your interface{} to int value.

iAreaId := val.(int)
iAreaId, ok := val.(int)

More information is available.

How to fix java.net.SocketException: Broken pipe?

JavaDoc:

The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused.

You should increase "backlog" parameter of your ServerSocket, for example

int backlogSize = 50 ;
new ServerSocket(port, backlogSize);

What is the Java ?: operator called and what does it do?

This construct is called Ternary Operator in Computer Science and Programing techniques.
And Wikipedia suggest the following explanation:

In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.

Not only in Java, this syntax is available within PHP, Objective-C too.

In the following link it gives the following explanation, which is quiet good to understand it:

A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

In Perl/PHP it works as:
boolean_condition ? true_value : false_value

In C/C++ it works as:
logical expression ? action for true : action for false

This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.

We can simplify the If-Else blocks with this Ternary operator for one code statement line.
For Example:

if ( car.isStarted() ) {
     car.goForward();
} else {
     car.startTheEngine();
}

Might be equal to the following:

( car.isStarted() ) ? car.goForward() : car.startTheEngine();

So if we refer to your statement:

int count = isHere ? getHereCount(index) : getAwayCount(index);

It is actually the 100% equivalent of the following If-Else block:

int count;
if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}

That's it!
Hope this was helpful to somebody!
Cheers!

Recyclerview and handling different type of row inflation

We can achieve multiple view on single RecyclerView from below way :-

Dependencies on Gradle so add below code:-

compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'

RecyclerView in XML

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Activity Code

private RecyclerView mRecyclerView;
private CustomAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String[] mDataset = {“Data - one ”, “Data - two”,
    “Showing data three”, “Showing data four”};
private int mDatasetTypes[] = {DataOne, DataTwo, DataThree}; //view types
 
...
 
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
//Adapter is created in the last step
mAdapter = new CustomAdapter(mDataset, mDataSetTypes);
mRecyclerView.setAdapter(mAdapter);

First XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/ten"
    android:elevation="@dimen/hundered”
    card_view:cardBackgroundColor=“@color/black“>
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding=“@dimen/ten">
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=“Fisrt”
            android:textColor=“@color/white“ />
 
        <TextView
            android:id="@+id/temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/ten"
            android:textColor="@color/white"
            android:textSize="30sp" />
    </LinearLayout>
 
</android.support.v7.widget.CardView>

Second XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/ten"
    android:elevation="100dp"
    card_view:cardBackgroundColor="#00bcd4">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="@dimen/ten">
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=“DataTwo”
            android:textColor="@color/white" />
 
        <TextView
            android:id="@+id/score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/ten"
            android:textColor="#ffffff"
            android:textSize="30sp" />
    </LinearLayout>
 
</android.support.v7.widget.CardView>

Third XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/ten"
    android:elevation="100dp"
    card_view:cardBackgroundColor="@color/white">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="@dimen/ten">
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=“DataThree” />
 
        <TextView
            android:id="@+id/headline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/ten"
            android:textSize="25sp" />
 
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/ten"
            android:id="@+id/read_more"
            android:background="@color/white"
            android:text=“Show More” />
    </LinearLayout>
 
</android.support.v7.widget.CardView>

Now time to make adapter and this is main for showing different -2 view on same recycler view so please check this code focus fully :-

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
    private static final String TAG = "CustomAdapter";
 
    private String[] mDataSet;
    private int[] mDataSetTypes;
 
    public static final int dataOne = 0;
    public static final int dataTwo = 1;
    public static final int dataThree = 2;
 
 
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View v) {
            super(v);
        }
    }
 
    public class DataOne extends ViewHolder {
        TextView temp;
 
        public DataOne(View v) {
            super(v);
            this.temp = (TextView) v.findViewById(R.id.temp);
        }
    }
 
    public class DataTwo extends ViewHolder {
        TextView score;
 
        public DataTwo(View v) {
            super(v);
            this.score = (TextView) v.findViewById(R.id.score);
        }
    }
 
    public class DataThree extends ViewHolder {
        TextView headline;
        Button read_more;
 
        public DataThree(View v) {
            super(v);
            this.headline = (TextView) v.findViewById(R.id.headline);
            this.read_more = (Button) v.findViewById(R.id.read_more);
        }
    }
 
 
    public CustomAdapter(String[] dataSet, int[] dataSetTypes) {
        mDataSet = dataSet;
        mDataSetTypes = dataSetTypes;
    }
 
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v;
        if (viewType == dataOne) {
            v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.weather_card, viewGroup, false);
 
            return new DataOne(v);
        } else if (viewType == dataTwo) {
            v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.news_card, viewGroup, false);
            return new DataThree(v);
        } else {
            v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.score_card, viewGroup, false);
            return new DataTwo(v);
        }
    }
 
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        if (viewHolder.getItemViewType() == dataOne) {
            DataOne holder = (DataOne) viewHolder;
            holder.temp.setText(mDataSet[position]);
        }
        else if (viewHolder.getItemViewType() == dataTwo) {
            DataThree holder = (DataTwo) viewHolder;
            holder.headline.setText(mDataSet[position]);
        }
        else {
            DataTwo holder = (DataTwo) viewHolder;
            holder.score.setText(mDataSet[position]);
        }
    }
 
    @Override
    public int getItemCount() {
        return mDataSet.length;
    }
 
   @Override
    public int getItemViewType(int position) {
        return mDataSetTypes[position];
    }
}

You can check also this link for more information.

How do you get the list of targets in a makefile?

As mklement0 points out, a feature for listing all Makefile targets is missing from GNU-make, and his answer and others provides ways to do this.

However, the original post also mentions rake, whose tasks switch does something slightly different than just listing all tasks in the rakefile. Rake will only give you a list of tasks that have associated descriptions. Tasks without descriptions will not be listed. This gives the author the ability to both provide customized help descriptions and also omit help for certain targets.

If you want to emulate rake's behavior, where you provide descriptions for each target, there is a simple technique for doing this: embed descriptions in comments for each target you want listed.

You can either put the description next to the target or, as I often do, next to a PHONY specification above the target, like this:

.PHONY: target1 # Target 1 help text
target1: deps
    [... target 1 build commands]

.PHONY: target2 # Target 2 help text
target2:
    [... target 2 build commands]

...                                                                                                         

.PHONY: help # Generate list of targets with descriptions                                                                
help:                                                                                                                    
    @grep '^.PHONY: .* #' Makefile | sed 's/\.PHONY: \(.*\) # \(.*\)/\1 \2/' | expand -t20

Which will yield

$ make help
target1             Target 1 help text
target2             Target 2 help text

...
help                Generate list of targets with descriptions

You can also find a short code example in this gist and here too.

Again, this does not solve the problem of listing all the targets in a Makefile. For example, if you have a big Makefile that was maybe generated or that someone else wrote, and you want a quick way to list its targets without digging through it, this won't help.

However, if you are writing a Makefile, and you want a way to generate help text in a consistent, self-documenting way, this technique may be useful.

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

CSS3 transition doesn't work with display property

I faced the problem with display:none

I have several horizontal bars with transition effects but I wanted to show only part of that container and fold the rest while maintaining the effects. I reproduced a small demo here

The obvious was to wrap those hidden animated bars in a div then toggle that element's height and opacity

.hide{
  opacity: 0;
  height: 0;
}
.bars-wrapper.expanded > .hide{
 opacity: 1;
 height: auto;
}

The animation works well but the issue was that these hidden bars were still consuming space on my page and overlapping other elements

enter image description here

so adding display:none to the hidden wrapper .hide solves the margin issue but not the transition, neither applying display:none or height:0;opacity:0 works on the children elements.

So my final workaround was to give those hidden bars a negative and absolute position and it worked well with CSS transitions.

Jsfiddle

C/C++ switch case with string

There is no good solution to your problem, so here is an okey solution ;-)

It keeps your efficiency when assertions are disabled and when assertions are enabled it will raise an assertion error when the hash value is wrong.

I suspect that the D programming language could compute the hash value during compile time, thus removing the need to explicitly write down the hash value.

template <std::size_t h>
struct prehash
{
    const your_string_type str;

    static const std::size_t hash_value = h;

    pre_hash(const your_string_type& s) : str(s)
    {
        assert(_myhash(s) == hash_value);
    }
};

/* ... */

std::size_t h = _myhash(mystring);

static prehash<66452> first_label = "label1";

switch (h) {
case first_label.hash_value:
    // ...
    ;
}

By the way, consider removing the initial underscore from the declaration of _ myhash() (sorry but stackoverflow forces me to insert a space between _ and myhash). A C++ implementation is free to implement macros with names starting with underscore and an uppercase letter (Item 36 of "Exceptional C++ Style" by Herb Sutter), so if you get into the habit of giving things names that start underscore, then a beautiful day could come when you give a symbol a name that starts with underscore and an uppercase letter, where the implementation has defined a macro with the same name.

How to view AndroidManifest.xml from APK file?

In this thread, Dianne Hackborn tells us we can get info out of the AndroidManifest using aapt.

I whipped up this quick unix command to grab the version info:

aapt dump badging my.apk | sed -n "s/.*versionName='\([^']*\).*/\1/p"

select rows in sql with latest date for each ID repeated multiple times

This question has been asked before. Please see this question.

Using the accepted answer and adapting it to your problem you get:

SELECT tt.*
FROM myTable tt
INNER JOIN
    (SELECT ID, MAX(Date) AS MaxDateTime
    FROM myTable
    GROUP BY ID) groupedtt 
ON tt.ID = groupedtt.ID 
AND tt.Date = groupedtt.MaxDateTime

Creating a jQuery object from a big HTML-string

the reason why $(string) is not working is because jquery is not finding html content between $(). Therefore you need to first parse it to html. once you have a variable in which you have parsed the html. you can then use $(string) and use all functions available on the object

Find Item in ObservableCollection without using a loop

Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.

How to stop app that node.js express 'npm start'

If you've already tried ctrl + c and it still doesn't work, you might want to try this. This has worked for me.

  1. Run command-line as an Administrator. Then run the command below to find the processID (PID) you want to kill. Type your port number in <yourPortNumber>

    netstat -ano | findstr :<yourPortNumber>

enter image description here

  1. Then you execute this command after you have identified the PID.

    taskkill /PID <typeYourPIDhere> /F

enter image description here

Kudos to @mit $ingh from http://www.callstack.in/tech/blog/windows-kill-process-by-port-number-157

Printing pointers in C

Yes, your compiler is expecting void *. Just cast them to void *.

/* for instance... */
printf("The value of s is: %p\n", (void *) s);
printf("The direction of s is: %p\n", (void *) &s);

Get filename and path from URI from mediastore

try this get image file path from Uri

public void getImageFilePath(Context context, Uri uri) {

    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String image_id = cursor.getString(0);
    image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
    cursor.close();
    cursor = context.getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();
    upLoadImageOrLogo(path);
}

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

Please be aware that the accepted answer is a bit incomplete. Yes, at the most basic level Collation handles sorting. BUT, the comparison rules defined by the chosen Collation are used in many places outside of user queries against user data.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does the COLLATE clause of CREATE DATABASE do?", then:

The COLLATE {collation_name} clause of the CREATE DATABASE statement specifies the default Collation of the Database, and not the Server; Database-level and Server-level default Collations control different things.

Server (i.e. Instance)-level controls:

  • Database-level Collation for system Databases: master, model, msdb, and tempdb.
  • Due to controlling the DB-level Collation of tempdb, it is then the default Collation for string columns in temporary tables (global and local), but not table variables.
  • Due to controlling the DB-level Collation of master, it is then the Collation used for Server-level data, such as Database names (i.e. name column in sys.databases), Login names, etc.
  • Handling of parameter / variable names
  • Handling of cursor names
  • Handling of GOTO labels
  • Default Collation used for newly created Databases when the COLLATE clause is missing

Database-level controls:

  • Default Collation used for newly created string columns (CHAR, VARCHAR, NCHAR, NVARCHAR, TEXT, and NTEXT -- but don't use TEXT or NTEXT) when the COLLATE clause is missing from the column definition. This goes for both CREATE TABLE and ALTER TABLE ... ADD statements.
  • Default Collation used for string literals (i.e. 'some text') and string variables (i.e. @StringVariable). This Collation is only ever used when comparing strings and variables to other strings and variables. When comparing strings / variables to columns, then the Collation of the column will be used.
  • The Collation used for Database-level meta-data, such as object names (i.e. sys.objects), column names (i.e. sys.columns), index names (i.e. sys.indexes), etc.
  • The Collation used for Database-level objects: tables, columns, indexes, etc.

Also:

  • ASCII is an encoding which is 8-bit (for common usage; technically "ASCII" is 7-bit with character values 0 - 127, and "ASCII Extended" is 8-bit with character values 0 - 255). This group is the same across cultures.
  • The Code Page is the "extended" part of Extended ASCII, and controls which characters are used for values 128 - 255. This group varies between each culture.
  • Latin1 does not mean "ASCII" since standard ASCII only covers values 0 - 127, and all code pages (that can be represented in SQL Server, and even NVARCHAR) map those same 128 values to the same characters.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does this particular collation do?", then:

  • Because the name start with SQL_, this is a SQL Server collation, not a Windows collation. These are definitely obsolete, even if not officially deprecated, and are mainly for pre-SQL Server 2000 compatibility. Although, quite unfortunately SQL_Latin1_General_CP1_CI_AS is very common due to it being the default when installing on an OS using US English as its language. These collations should be avoided if at all possible.

    Windows collations (those with names not starting with SQL_) are newer, more functional, have consistent sorting between VARCHAR and NVARCHAR for the same values, and are being updated with additional / corrected sort weights and uppercase/lowercase mappings. These collations also don't have the potential performance problem that the SQL Server collations have: Impact on Indexes When Mixing VARCHAR and NVARCHAR Types.

  • Latin1_General is the culture / locale.
    • For NCHAR, NVARCHAR, and NTEXT data this determines the linguistic rules used for sorting and comparison.
    • For CHAR, VARCHAR, and TEXT data (columns, literals, and variables) this determines the:
      • linguistic rules used for sorting and comparison.
      • code page used to encode the characters. For example, Latin1_General collations use code page 1252, Hebrew collations use code page 1255, and so on.
  • CP{code_page} or {version}

    • For SQL Server collations: CP{code_page}, is the 8-bit code page that determines what characters map to values 128 - 255. While there are four code pages for Double-Byte Character Sets (DBCS) that can use 2-byte combinations to create more than 256 characters, these are not available for the SQL Server collations.
    • For Windows collations: {version}, while not present in all collation names, refers to the SQL Server version in which the collation was introduced (for the most part). Windows collations with no version number in the name are version 80 (meaning SQL Server 2000 as that is version 8.0). Not all versions of SQL Server come with new collations, so there are gaps in the version numbers. There are some that are 90 (for SQL Server 2005, which is version 9.0), most are 100 (for SQL Server 2008, version 10.0), and a small set has 140 (for SQL Server 2017, version 14.0).

      I said "for the most part" because the collations ending in _SC were introduced in SQL Server 2012 (version 11.0), but the underlying data wasn't new, they merely added support for supplementary characters for the built-in functions. So, those endings exist for version 90 and 100 collations, but only starting in SQL Server 2012.

  • Next you have the sensitivities, that can be in any combination of the following, but always specified in this order:
    • CS = case-sensitive or CI = case-insensitive
    • AS = accent-sensitive or AI = accent-insensitive
    • KS = Kana type-sensitive or missing = Kana type-insensitive
    • WS = width-sensitive or missing = width insensitive
    • VSS = variation selector sensitive (only available in the version 140 collations) or missing = variation selector insensitive
  • Optional last piece:

    • _SC at the end means "Supplementary Character support". The "support" only affects how the built-in functions interpret surrogate pairs (which are how supplementary characters are encoded in UTF-16). Without _SC at the end (or _140_ in the middle), built-in functions don't see a single supplementary character, but instead see two meaningless code points that make up the surrogate pair. This ending can be added to any non-binary, version 90 or 100 collation.
    • _BIN or _BIN2 at the end means "binary" sorting and comparison. Data is still stored the same, but there are no linguistic rules. This ending is never combined with any of the 5 sensitivities or _SC. _BIN is the older style, and _BIN2 is the newer, more accurate style. If using SQL Server 2005 or newer, use _BIN2. For details on the differences between _BIN and _BIN2, please see: Differences Between the Various Binary Collations (Cultures, Versions, and BIN vs BIN2).
    • _UTF8 is a new option as of SQL Server 2019. It's an 8-bit encoding that allows for Unicode data to be stored in VARCHAR and CHAR datatypes (but not the deprecated TEXT datatype). This option can only be used on collations that support supplementary characters (i.e. version 90 or 100 collations with _SC in their name, and version 140 collations). There is also a single binary _UTF8 collation (_BIN2, not _BIN).

      PLEASE NOTE: UTF-8 was designed / created for compatibility with environments / code that are set up for 8-bit encodings yet want to support Unicode. Even though there are a few scenarios where UTF-8 can provide up to 50% space savings as compared to NVARCHAR, that is a side-effect and has a cost of a slight hit to performance in many / most operations. If you need this for compatibility, then the cost is acceptable. If you want this for space-savings, you had better test, and TEST AGAIN. Testing includes all functionality, and more than just a few rows of data. Be warned that UTF-8 collations work best when ALL columns, and the database itself, are using VARCHAR data (columns, variables, string literals) with a _UTF8 collation. This is the natural state for anyone using this for compatibility, but not for those hoping to use it for space-savings. Be careful when mixing VARCHAR data using a _UTF8 collation with either VARCHAR data using non-_UTF8 collations or NVARCHAR data, as you might experience odd behavior / data loss. For more details on the new UTF-8 collations, please see: Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?

What is the difference between "screen" and "only screen" in media queries?

Let's break down your examples one by one.

@media (max-width:632px)

This one is saying for a window with a max-width of 632px that you want to apply these styles. At that size you would be talking about anything smaller than a desktop screen in most cases.

@media screen and (max-width:632px)

This one is saying for a device with a screen and a window with max-width of 632px apply the style. This is almost identical to the above except you are specifying screen as opposed to the other available media types the most common other one being print.

@media only screen and (max-width:632px)

Here is a quote straight from W3C to explain this one.

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

As there is no such media type as "only", the style sheet should be ignored by older browsers.

Here's the link to that quote that is shown in example 9 on that page.

Hopefully this sheds some light on media queries.

EDIT:

Be sure to check out @hybrids excellent answer on how the only keyword is really handled.

Database development mistakes made by application developers

Well, I would have to say that the biggest mistake application developers make is not properly normalizing the database.

As an application developer myself, I realize the importance of proper database structure, normalization, and maintenance; I have spent countless hours educating myself on database structure and administration. In my experience, whenever I start working with a different developer, I usually have to restructure the entire database and update the app to suit because it is usually malformed and defective.

For example, I started working with a new project where the developer asked me to implement Facebook Connect on the site. I cracked open the database to see what I had to work with and saw that every little bit of information about any given user was crammed into one table. It took me six hours to write a script that would organize the table into four or five separate tables and another two to get the app to use those tables. Please, normalize your databases! It will make everything else less of a headache.

Change content of div - jQuery

There are 2 jQuery functions that you'll want to use here.

1) click. This will take an anonymous function as it's sole parameter, and will execute it when the element is clicked.

2) html. This will take an html string as it's sole parameter, and will replace the contents of your element with the html provided.

So, in your case, you'll want to do the following:

$('#content-container a').click(function(e){
    $(this).parent().html('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

If you only want to add content to your div, rather than replacing everything in it, you should use append:

$('#content-container a').click(function(e){
    $(this).parent().append('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

If you want the new added links to also add new content when clicked, you should use event delegation:

$('#content-container').on('click', 'a', function(e){
    $(this).parent().append('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

Identify duplicate values in a list in Python

The following list comprehension will yield the duplicate values:

[x for x in mylist if mylist.count(x) >= 2]

ZIP file content type for HTTP request

.zip    application/zip, application/octet-stream

Resetting MySQL Root Password with XAMPP on Localhost

For me much better way is to do it using terminal rather then PhpMyAdmin UI.

The answer is copied from "https://gist.github.com/susanBuck/39d1a384779f3d596afb19fcad6b598c" which I have tried and it works always, try it out..

  • Open C:\xampp\mysql\bin\my.ini (MySQL config file)
  • Find the line [mysqld] and right below it add skip-grant-tables. Example:

    [mysqld] skip-grant-tables port= 3306 socket = "C:/xampp/mysql/mysql.sock" basedir = "C:/xampp/mysql" tmpdir = "C:/xampp/tmp" [...etc...]

  • This should allow you to access MySQL if you don't know your password.

  • Stop and start MySQL from XAMPP to make this change take effect.
  • Next, in command line, connect to MySQL:

C:\xampp\mysql\bin\mysql.exe --user=root

  • Once in MySQL command line "select" the mysql database:

USE mysql;

  • Then, the following command will list all your MySQL users:

SELECT * FROM user \G;

  • You can scan through the rows to see what the root user's password is set to. There will be a few root users listed, with different hosts.
  • To set root user's to have a password of your choice, run this command:

UPDATE user SET password = PASSWORD('secret_pass') WHERE user = 'root';

  • -OR- To set all root user's to have a blank password, run this command:

UPDATE user SET password = '' WHERE user = 'root';

When you're done, run exit; to exit the MySQL command line.

Next, re-enable password checking by removing skip-grant-tables from C:\xampp\mysql\bin\my.ini.

Save changes, restart MySQL from XAMPP.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Why does npm install say I have unmet dependencies?

Take care about your angular version, if you work under angular 2.x.x so maybe you need to upgrade to angular 4.x.x

Some dependencies needs angular 4

Here is a tutorial for how to install angular 4 or update your project.

Get visible items in RecyclerView

for those who have a logic to be implemented inside the RecyclerView adapter you can still use @ernesto approach combined with an on scrollListener to get what you want as the RecyclerView is consulted. Inside the adapter you will have something like this:

@Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if(manager instanceof LinearLayoutManager && getItemCount() > 0) {
            LinearLayoutManager llm = (LinearLayoutManager) manager;
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                        int visiblePosition = llm.findFirstCompletelyVisibleItemPosition();
                        if(visiblePosition > -1) {
                            View v = llm.findViewByPosition(visiblePosition);
                            //do something
                            v.setBackgroundColor(Color.parseColor("#777777"));
                        }
                }
            });
        }
    }

Mobile website "WhatsApp" button to send message to a specific number

To send a Whatsapp message from a website, use the below URL.

URL: https://api.whatsapp.com/send?phone=XXXXX&text=dummy

Here the phone and text are parameters were one of them is required.

  • phone: To whom we need to send the message
  • text: The text needs to share.

This URL is also can be used. It displays a blank screen if there is no application found!

URL: whatsapp://send?text=The text to share!

Note: All the above will work in web, only if WhatsApp desktop app is installed

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

Despite not fully answering the original question, this is probably what most people googling this wanted to see.

For GCC:

$ cat test.cpp 
#include <iostream>

int main(int argc, char **argv)
{
    std::cout << __func__ << std::endl
              << __FUNCTION__ << std::endl
              << __PRETTY_FUNCTION__ << std::endl;
}
$ g++ test.cpp 
$ ./a.out 
main
main
int main(int, char**)

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

How do I get the position selected in a RecyclerView?

onBindViewHolder() is called for each and every item and setting the click listener inside onBindVieHolder() is an unnecessary option to repeat when you can call it once in your ViewHolder constructor.

public class MyViewHolder extends RecyclerView.ViewHolder 
      implements View.OnClickListener{
   public final TextView textView; 

   public MyViewHolder(View view){
      textView = (TextView) view.findViewById(R.id.text_view);
      view.setOnClickListener(this);
      // getAdapterPosition() retrieves the position here.
   } 

   @Override
   public void onClick(View v){
      // Clicked on item 
      Toast.makeText(mContext, "Clicked on position: " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
   }
}

How do you use global variables or constant values in Ruby?

Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $ are global, variables with @ are instance variables, @@ means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.

I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:

  1. Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo and create a constant Offset, so then all the classes could access Foo::Offset.

  2. Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.

How to get twitter bootstrap modal to close (after initial launch)

I had the same problem in the iphone or desktop, didnt manage to close the dialog when pressing the close button.

i found out that The <button> tag defines a clickable button and is needed to specify the type attribute for a element as follow:

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

check the example code for bootstrap modals at : BootStrap javascript Page

WCF, Service attribute value in the ServiceHost directive could not be found

I had the same problem, found this thread, tried all but nogo.

Then I spend another 4 hours wasted time.

Then I found that the compilation settings had changed from 64bits to x86. When I changed it back to 64bits it worked. Don't know exactly why but could be that the IIS application pool was not set to allow 32 bit applications.

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

How different is Scrum practice from Agile Practice?

As is mentioned, Agile is a methodology, and there are various ways to define what agile is. To a large extent, if it involves constant unit testing and the ability to quickly adapt when the business needs change then it is probably agile. The opposite is the waterfall method.

There are various implementations that are codified by consultants, such as Xtremem Programming, Scrum and RUP (Rational Unified Process).

So, if you are using Scrum then you can switch between agile and scrum depending on if you are talking about the methodology or your implementation. You will want to see if the terms are being used correctly, by the context.

For example, if I am talking about the 15 min standup as part of my agile process, that is not necessarily needed to be agile, but scrum almost requires it, so when you interchange the terms, it is important to differentiate between the two concepts.

How to get a product's image in Magento?

echo $_product->getImageUrl();

This method of the Product class should do the trick for you.

Store List to session

Yes. Which platform are you writing for? ASP.NET C#?

List<string> myList = new List<string>();
Session["var"] = myList;

Then, to retrieve:

myList = (List<string>)Session["var"];

Entity framework code-first null foreign key

I prefer this (below):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

How do I add PHP code/file to HTML(.html) files?

Add this line

AddHandler application/x-httpd-php .html

to httpd.conf file for what you want to do. But remember, if you do this then your web server will be very slow, because it will be parsing even static code which will not contain php code. So the better way will be to make the file extension .phtml instead of just .html.

UIAlertView first deprecated IOS 9

//Calling     
[self showMessage:@"There is no internet connection for this device"
                    withTitle:@"Error"];

//Method

-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{

 UIAlertController * alert=   [UIAlertController
                                  alertControllerWithTitle:title
                                  message:message
                                  preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

        //do something when click button
    }];
    [alert addAction:okAction];
    UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    [vc presentViewController:alert animated:YES completion:nil];
}

If you want to use this alert in NSObject class you should use like:

-(void)showMessage:(NSString*)message withTitle:(NSString *)title{
dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }]];

    [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
    }];
});
}

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

R command for setting working directory to source file location in Rstudio

Here is another way to do it:

set2 <- function(name=NULL) {
  wd <- rstudioapi::getSourceEditorContext()$path
  if (!is.null(name)) {
    if (substr(name, nchar(name) - 1, nchar(name)) != '.R') 
      name <- paste0(name, '.R')
  }
  else {
    name <- stringr::word(wd, -1, sep='/')
  }
  wd <- gsub(wd, pattern=paste0('/', name), replacement = '')
  no_print <- eval(expr=setwd(wd), envir = .GlobalEnv)
}
set2()

Advantages of SQL Server 2008 over SQL Server 2005?

The new features are really great and its meets the very important factors of current age. For .net people it’s always be a boon to use SQL Server, I hope using the latest version we will have better security and better performance as well as the introduction of compression the size of the database. The backup encryption utility is also phenomenon.

Once again thanks to Microsoft for their great thoughts in form of software :)

How to display a loading screen while site content loads

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.

Convert array of indices to 1-hot encoded numpy array

I am adding for completion a simple function, using only numpy operators:

   def probs_to_onehot(output_probabilities):
        argmax_indices_array = np.argmax(output_probabilities, axis=1)
        onehot_output_array = np.eye(np.unique(argmax_indices_array).shape[0])[argmax_indices_array.reshape(-1)]
        return onehot_output_array

It takes as input a probability matrix: e.g.:

[[0.03038822 0.65810204 0.16549407 0.3797123 ] ... [0.02771272 0.2760752 0.3280924 0.33458805]]

And it will return

[[0 1 0 0] ... [0 0 0 1]]

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Look in HTML output for actual client ID

You need to look in the generated HTML output to find out the right client ID. Open the page in browser, do a rightclick and View Source. Locate the HTML representation of the JSF component of interest and take its id as client ID. You can use it in an absolute or relative way depending on the current naming container. See following chapter.

Note: if it happens to contain iteration index like :0:, :1:, etc (because it's inside an iterating component), then you need to realize that updating a specific iteration round is not always supported. See bottom of answer for more detail on that.

Memorize NamingContainer components and always give them a fixed ID

If a component which you'd like to reference by ajax process/execute/update/render is inside the same NamingContainer parent, then just reference its own ID.

<h:form id="form">
    <p:commandLink update="result"> <!-- OK! -->
    <h:panelGroup id="result" />
</h:form>

If it's not inside the same NamingContainer, then you need to reference it using an absolute client ID. An absolute client ID starts with the NamingContainer separator character, which is by default :.

<h:form id="form">
    <p:commandLink update="result"> <!-- FAIL! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- OK! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- FAIL! -->
</h:form>
<h:form id="otherform">
    <h:panelGroup id="result" />
</h:form>
<h:form id="form">
    <p:commandLink update=":otherform:result"> <!-- OK! -->
</h:form>
<h:form id="otherform">
    <h:panelGroup id="result" />
</h:form>

NamingContainer components are for example <h:form>, <h:dataTable>, <p:tabView>, <cc:implementation> (thus, all composite components), etc. You recognize them easily by looking at the generated HTML output, their ID will be prepended to the generated client ID of all child components. Note that when they don't have a fixed ID, then JSF will use an autogenerated ID in j_idXXX format. You should absolutely avoid that by giving them a fixed ID. The OmniFaces NoAutoGeneratedIdViewHandler may be helpful in this during development.

If you know to find the javadoc of the UIComponent in question, then you can also just check in there whether it implements the NamingContainer interface or not. For example, the HtmlForm (the UIComponent behind <h:form> tag) shows it implements NamingContainer, but the HtmlPanelGroup (the UIComponent behind <h:panelGroup> tag) does not show it, so it does not implement NamingContainer. Here is the javadoc of all standard components and here is the javadoc of PrimeFaces.

Solving your problem

So in your case of:

<p:tabView id="tabs"><!-- This is a NamingContainer -->
    <p:tab id="search"><!-- This is NOT a NamingContainer -->
        <h:form id="insTable"><!-- This is a NamingContainer -->
            <p:dialog id="dlg"><!-- This is NOT a NamingContainer -->
                <h:panelGrid id="display">

The generated HTML output of <h:panelGrid id="display"> looks like this:

<table id="tabs:insTable:display">

You need to take exactly that id as client ID and then prefix with : for usage in update:

<p:commandLink update=":tabs:insTable:display">

Referencing outside include/tagfile/composite

If this command link is inside an include/tagfile, and the target is outside it, and thus you don't necessarily know the ID of the naming container parent of the current naming container, then you can dynamically reference it via UIComponent#getNamingContainer() like so:

<p:commandLink update=":#{component.namingContainer.parent.namingContainer.clientId}:display">

Or, if this command link is inside a composite component and the target is outside it:

<p:commandLink update=":#{cc.parent.namingContainer.clientId}:display">

Or, if both the command link and target are inside same composite component:

<p:commandLink update=":#{cc.clientId}:display">

See also Get id of parent naming container in template for in render / update attribute

How does it work under the covers

This all is specified as "search expression" in the UIComponent#findComponent() javadoc:

A search expression consists of either an identifier (which is matched exactly against the id property of a UIComponent, or a series of such identifiers linked by the UINamingContainer#getSeparatorChar character value. The search algorithm should operates as follows, though alternate alogrithms may be used as long as the end result is the same:

  • Identify the UIComponent that will be the base for searching, by stopping as soon as one of the following conditions is met:
    • If the search expression begins with the the separator character (called an "absolute" search expression), the base will be the root UIComponent of the component tree. The leading separator character will be stripped off, and the remainder of the search expression will be treated as a "relative" search expression as described below.
    • Otherwise, if this UIComponent is a NamingContainer it will serve as the basis.
    • Otherwise, search up the parents of this component. If a NamingContainer is encountered, it will be the base.
    • Otherwise (if no NamingContainer is encountered) the root UIComponent will be the base.
  • The search expression (possibly modified in the previous step) is now a "relative" search expression that will be used to locate the component (if any) that has an id that matches, within the scope of the base component. The match is performed as follows:
    • If the search expression is a simple identifier, this value is compared to the id property, and then recursively through the facets and children of the base UIComponent (except that if a descendant NamingContainer is found, its own facets and children are not searched).
    • If the search expression includes more than one identifier separated by the separator character, the first identifier is used to locate a NamingContainer by the rules in the previous bullet point. Then, the findComponent() method of this NamingContainer will be called, passing the remainder of the search expression.

Note that PrimeFaces also adheres the JSF spec, but RichFaces uses "some additional exceptions".

"reRender" uses UIComponent.findComponent() algorithm (with some additional exceptions) to find the component in the component tree.

Those additional exceptions are nowhere in detail described, but it's known that relative component IDs (i.e. those not starting with :) are not only searched in the context of the closest parent NamingContainer, but also in all other NamingContainer components in the same view (which is a relatively expensive job by the way).

Never use prependId="false"

If this all still doesn't work, then verify if you aren't using <h:form prependId="false">. This will fail during processing the ajax submit and render. See also this related question: UIForm with prependId="false" breaks <f:ajax render>.

Referencing specific iteration round of iterating components

It was for long time not possible to reference a specific iterated item in iterating components like <ui:repeat> and <h:dataTable> like so:

<h:form id="form">
    <ui:repeat id="list" value="#{['one','two','three']}" var="item">
        <h:outputText id="item" value="#{item}" /><br/>
    </ui:repeat>

    <h:commandButton value="Update second item">
        <f:ajax render=":form:list:1:item" />
    </h:commandButton>
</h:form>

However, since Mojarra 2.2.5 the <f:ajax> started to support it (it simply stopped validating it; thus you would never face the in the question mentioned exception anymore; another enhancement fix is planned for that later).

This only doesn't work yet in current MyFaces 2.2.7 and PrimeFaces 5.2 versions. The support might come in the future versions. In the meanwhile, your best bet is to update the iterating component itself, or a parent in case it doesn't render HTML, like <ui:repeat>.

When using PrimeFaces, consider Search Expressions or Selectors

PrimeFaces Search Expressions allows you to reference components via JSF component tree search expressions. JSF has several builtin:

  • @this: current component
  • @form: parent UIForm
  • @all: entire document
  • @none: nothing

PrimeFaces has enhanced this with new keywords and composite expression support:

  • @parent: parent component
  • @namingcontainer: parent UINamingContainer
  • @widgetVar(name): component as identified by given widgetVar

You can also mix those keywords in composite expressions such as @form:@parent, @this:@parent:@parent, etc.

PrimeFaces Selectors (PFS) as in @(.someclass) allows you to reference components via jQuery CSS selector syntax. E.g. referencing components having all a common style class in the HTML output. This is particularly helpful in case you need to reference "a lot of" components. This only prerequires that the target components have all a client ID in the HTML output (fixed or autogenerated, doesn't matter). See also How do PrimeFaces Selectors as in update="@(.myClass)" work?

How to allow only integers in a textbox?

step by step

given you have a textbox as following,

<asp:TextBox ID="TextBox13" runat="server" 
  onkeypress="return functionx(event)" >
</asp:TextBox>

you create a JavaScript function like this:

     <script type = "text/javascript">
         function functionx(evt) 
         {
            if (evt.charCode > 31 && (evt.charCode < 48 || evt.charCode > 57))
                  {
                    alert("Allow Only Numbers");
                    return false;
                  }
          }
     </script>

the first part of the if-statement excludes the ASCII control chars, the or statements exclued anything, that is not a number

Get current language in CultureInfo

Current system language is retrieved using :

  CultureInfo.InstalledUICulture

"Gets the CultureInfo that represents the culture installed with the operating system."

InstalledUICulture

To set it as default language for thread use :

   System.Globalization.CultureInfo.DefaultThreadCurrentCulture=CultureInfo.InstalledUICulture;

Can't find AVD or SDK manager in Eclipse

I have solved this as follows:

  1. Window > Customize Perspective... (you will see Android and AVD Manager are disabled)

  2. Command Groups Availability > Android and AVD Manager > check

  3. Tool Bar Visibility > Android and AVD Manager > check

Launch Image does not show up in my iOS App

* (Xcode 7.2 / Deployment Target 7.0 / Landscape Orientation Only) *

I know is an old question but with Xcode 7.2 I'm still getting the message and I fixed with this:

1) Select PORTRAIT and both landscapes. Add "Launch Images Source" and "Launch Screen File"

enter image description here

2) In your Launch Image select iPhone "8.0 and Later" and "7.0 and Later".

enter image description here

3) Add this code in your appDelegate:

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
#else
- (UIInterfaceOrientationMask)application:(UIApplication *)application     supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return (UIInterfaceOrientationMaskLandscape);
}
#endif

4) Add this on your ViewController

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
     return UIInterfaceOrientationMaskLandscape;
}

I hope help to somebody else.

Iterate over values of object

You could use underscore.js and the each function:

_.each({key1: "value1", key2: "value2"}, function(value) {
  console.log(value);
});

How to run a method every X seconds

You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().

Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds.  One second = 1000 milliseconds.


@Override
protected void onResume() {
   //start handler as activity become visible

    handler.postDelayed( runnable = new Runnable() {
        public void run() {
            //do something

            handler.postDelayed(runnable, delay);
        }
    }, delay);

    super.onResume();
}

// If onPause() is not included the threads will double up when you 
// reload the activity 

@Override
protected void onPause() {
    handler.removeCallbacks(runnable); //stop handler when activity not visible
    super.onPause();
}

Get first day of week in SQL Server

This works wonderfully for me:

CREATE FUNCTION [dbo].[StartOfWeek]
(
  @INPUTDATE DATETIME
)
RETURNS DATETIME

AS
BEGIN
  -- THIS does not work in function.
  -- SET DATEFIRST 1 -- set monday to be the first day of week.

  DECLARE @DOW INT -- to store day of week
  SET @INPUTDATE = CONVERT(VARCHAR(10), @INPUTDATE, 111)
  SET @DOW = DATEPART(DW, @INPUTDATE)

  -- Magic convertion of monday to 1, tuesday to 2, etc.
  -- irrespect what SQL server thinks about start of the week.
  -- But here we have sunday marked as 0, but we fix this later.
  SET @DOW = (@DOW + @@DATEFIRST - 1) %7
  IF @DOW = 0 SET @DOW = 7 -- fix for sunday

  RETURN DATEADD(DD, 1 - @DOW,@INPUTDATE)

END

WaitAll vs WhenAll

While JonSkeet's answer explains the difference in a typically excellent way there is another difference: exception handling.

Task.WaitAll throws an AggregateException when any of the tasks throws and you can examine all thrown exceptions. The await in await Task.WhenAll unwraps the AggregateException and 'returns' only the first exception.

When the program below executes with await Task.WhenAll(taskArray) the output is as follows.

19/11/2016 12:18:37 AM: Task 1 started
19/11/2016 12:18:37 AM: Task 3 started
19/11/2016 12:18:37 AM: Task 2 started
Caught Exception in Main at 19/11/2016 12:18:40 AM: Task 1 throwing at 19/11/2016 12:18:38 AM
Done.

When the program below is executed with Task.WaitAll(taskArray) the output is as follows.

19/11/2016 12:19:29 AM: Task 1 started
19/11/2016 12:19:29 AM: Task 2 started
19/11/2016 12:19:29 AM: Task 3 started
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 1 throwing at 19/11/2016 12:19:30 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 2 throwing at 19/11/2016 12:19:31 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 3 throwing at 19/11/2016 12:19:32 AM
Done.

The program:

class MyAmazingProgram
{
    public class CustomException : Exception
    {
        public CustomException(String message) : base(message)
        { }
    }

    static void WaitAndThrow(int id, int waitInMs)
    {
        Console.WriteLine($"{DateTime.UtcNow}: Task {id} started");

        Thread.Sleep(waitInMs);
        throw new CustomException($"Task {id} throwing at {DateTime.UtcNow}");
    }

    static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            await MyAmazingMethodAsync();
        }).Wait();

    }

    static async Task MyAmazingMethodAsync()
    {
        try
        {
            Task[] taskArray = { Task.Factory.StartNew(() => WaitAndThrow(1, 1000)),
                                 Task.Factory.StartNew(() => WaitAndThrow(2, 2000)),
                                 Task.Factory.StartNew(() => WaitAndThrow(3, 3000)) };

            Task.WaitAll(taskArray);
            //await Task.WhenAll(taskArray);
            Console.WriteLine("This isn't going to happen");
        }
        catch (AggregateException ex)
        {
            foreach (var inner in ex.InnerExceptions)
            {
                Console.WriteLine($"Caught AggregateException in Main at {DateTime.UtcNow}: " + inner.Message);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Caught Exception in Main at {DateTime.UtcNow}: " + ex.Message);
        }
        Console.WriteLine("Done.");
        Console.ReadLine();
    }
}

Jquery, checking if a value exists in array or not

    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Android. WebView and loadData

The safest way to load htmlContent in a Web view is to:

  1. use base64 encoding (official recommendation)
  2. specify UFT-8 for html content type, i.e., "text/html; charset=utf-8" instead of "text/html" (personal advice)

"Base64 encoding" is an official recommendation that has been written again (already present in Javadoc) in the latest 01/2019 bug in Chrominium (present in WebView M72 (72.0.3626.76)):

https://bugs.chromium.org/p/chromium/issues/detail?id=929083

Official statement from Chromium team:

"Recommended fix:
Our team recommends you encode data with Base64. We've provided examples for how to do so:

This fix is backwards compatible (it works on earlier WebView versions), and should also be future-proof (you won't hit future compatibility problems with respect to content encoding)."

Code sample:

webView.loadData(
    Base64.encodeToString(
        htmlContent.getBytes(StandardCharsets.UTF_8),
        Base64.DEFAULT), // encode in Base64 encoded 
    "text/html; charset=utf-8", // utf-8 html content (personal recommendation)
    "base64"); // always use Base64 encoded data: NEVER PUT "utf-8" here (using base64 or not): This is wrong! 

APK signing error : Failed to read key from keystore

Removing double-quotes solve my problem, now its:

DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug

How do you get a directory listing in C?

The most similar method to readdir is probably using the little-known _find family of functions.

Can't include C++ headers like vector in Android NDK

If you are using Android studio and you are still seeing the message "error: vector: No such file or directory" (or other stl related errors) when you're compiling using ndk, then this might help you.

In your project, open the module's build.gradle file (not your project's build.grade, but the one that is for your module) and add 'stl "stlport_shared"' within the ndk element in defaultConfig.

For eg:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.domain.app"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"

        ndk {
            moduleName "myModuleName"
            stl "stlport_shared"
        }
    }
}

How do I link to part of a page? (hash?)

If there is any tag with an id (e.g., <div id="foo">), then you can simply append #foo to the URL. Otherwise, you can't arbitrarily link to portions of a page.

Here's a complete example: <a href="http://example.com/page.html#foo">Jump to #foo on page.html</a>

Linking content on the same page example: <a href="#foo">Jump to #foo on same page</a>

It is called a URI fragment.

Oracle client and networking components were not found

Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.

Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec executable, SSIS will not be able to find the Oracle client. The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.