text:
Q: Why are the pads different for THT / SMT components in Eagle? I am learning Cadsoft Eagle and have noticed that the pads for SMT devices are on the 'top'/'bottom' display layer, whereas the pads for THT components are on the 'pads' layer. Why is this?
I have enlarged the pads for the SMT device so that I don't commit Seppuku with my iron during hand production. Looking at the soldermask 'stop' layer, it appears that all is well, as the SMT pads are not covered. I just want to check that this difference between SMT/THT pads is correct before making my first batch of coffee coasters.

A: The features in the PADS layer goes on all layers of the PCB (with actually some additional modifications when you're using more than 2 layers, such as having a smaller copper ring in the inner layers instead of the large pad). SMD components, though, exist only on one side of the PCB. So their pads go on TOP or BOTTOM depending on which side the component is on.
As an aside, be careful when enlarging pads. Go with lengthening the pads and not widening them, since that could reduce the space available between adjacent pads and make soldering it harder, even if it still clears the rules for the fabricator. Also, it become counterproductive to leave more than one or two millimeters beyond how far the IC pin is expected to go. The extra exposed copper makes soldering by hand slightly more tricky.


text:
Q: wordpress if is taxonomy show class of active I have a nav which I would like to detect if it should an li should have a class of active or not.
I usually do this for a normal page like so:
    <li <?php if ( is_page('about')) { echo ' class="active"'; } ?>>
                            <a href="<?php bloginfo('url'); ?>/about">About

However im doing this on a taxonomy page and I would like to detect the name of the taxonomy term. So I have 4 terms, design,illustration,motion photography. How would I go about adding a class to the li of the active taxonomy term?
Here is what I have so far but its wrong:
<li <?php if ( is_taxonomy('illustration')) { echo ' class="active"'; } ?>><a href="<?php echo site_url(); ?> /talcat/illustration">Illustration

A: is_taxonomy() is deprecated since version 3.0. Instead try is_tax(). You'd use it like this:
if ( is_tax( 'taxonomy-slug-here', 'illustration' ) ) {
    // Do something.
}

Ref: http://codex.wordpress.org/Function_Reference/is_tax

redpajama_set_name: RedPajamaStackExchange


text:
Q: while getting locale value in java on window server always return en_US I have changed my operating system language to French. When i have run java file on spring tool suite framework on my local machine then it return correct locale value.But when i create a war file and deploy it on server then it always return locale value as "en_US".
I have used java function as bellow :-
String locale = Locale.getDefault();

I have also used
system.getproperties("user.language");

but get the same result.


text:
Q: c++ namespace and class hierarchy This is a question that troubles me a for a while, but could not find a the best way to deal with it. I am trying to show this through an example.
I am developing a graphics library with many classes. Some of the classes are "part of" relationship with each other, like these 3 classes:
namespace MyGraphicsLibrary
{

class MatrixStack
{

};

class Transform
{
    MatrixStack mMatrixStack;
};

class Renderer
{
    Transform mTransform;
};

}

The Renderer class is for users to use, but i did not want them to see Transform, MatrixStack classes when they lookup the MyGraphicsLibrary. The last two classes are only for Renderer class and not for users to use.
Here i am trying to do two things:

*

*Hiding the Transform, MatrixStack classes from users.

*Reflect the "part-of" hierarchy of the classes.
I tried the followings to solve this:

*

*The best solution for me would be the private nested-classes, as it would show the user that the nested class is private and also reflects the hierarchy if you simply look at the Renderer class declaration. The following post actually makes me uncertain that is good solution: Pros and cons of using nested C++ classes and enumerations?

*I tried to put Transform, MatrixStack into another namespace called Private. So user looking up MyGraphicsLibrary namespace would see Private namespace only covering all classes which are not for the users.
That's good, but there are lot of other classes with the same issue, and i quickly fill the Private namespace with classes which has nothing to do with each other.
Here I could only come up with ugly solutions, like introducing nested namespaces:
namespace MyGraphicsLibrary
{
    //private classes belonging to Renderer class
    namespace PrivateRenderer
    {
    class MatrixStack
    {
    };

        class Transform
        {
            MatrixStack mMatrixStack;
        };
    }

    //public classes for users
    class Renderer
    {
    Transform mTransform;
    };
}

Maybe I miss something here, but what do you think which one is the way to go.
Does anybody has a 3rd way?

A: you can use the PIMPL- (also called opaque pointer) idiom.
with hat you can entirely hide the classes from user the following way:
In your public header (in your include folder):
Renderer.h
class RendererImpl; // forward declaration of internal render structure

//public classes for users
class Renderer
{
  public:
    Renderer();
    ~Renderer();
    // public interface comes here and delegates all calls to RendererImpl (have to be implemented in cpp)

  RendererImpl* renderer; // better use something like QScopedPointer here
};

the cpp:
#include "RendererImpl.h" // your actual renderer that

Renderer::Renderer()
:renderer(new RendererImpl)
{}
Renderer::~Renderer()
{
  delete renderer;
}

The implementations may be completely hidden from the API. The headers have to be separated from the real interfaces.

A: If you want to store Transform as a plain (non-pointer/reference) member, then for the compilation of your public header, its definition should also be visible, because it affects the layout of the container class.
Consequently, the type will be visible wherever you want to use the container class.
You have the following options:

*

*Signal that they are not for public use through naming. Either by putting into a namespace (like detail in boost), or prefixing/suffixing its name.

*Use a technique that prevents clients from using that class. Make every member functions private and declare the container class friend. The attorney-client idiom is a more sophisticated way of fine-grained access control.

*Store Transform indirectly (pointer or reference), so you do not need its definition in the public header. This is pimpl. A variant of this if the public type is an interface, a base class of the actual Transform implementation.

Unnamed namespace: definitely a bad idea in a header. Unnamed namespaces are like C static: they get a compiler-generated identifier that is guaranteed to be unique to the given translation unit. You will end up with as many distinct Transform types as many places you included its definition.

A: Use an anonymous namespace:
namespace MyGraphicsLibrary
{
    namespace
    {
        class MatrixStack
        {

        };

        class Transform
        {
            MatrixStack mMatrixStack;
        };
    }

    class Renderer
    {
        Transform mTransform;
    };

}


text:
Q: rails bootstrap x-editable emptytext I'm using Bootstrap X-editable in a Rails app. I would like to replace the word empty in a table cell with the name of the field.
The X-editable documentation says the emptytext will replace it.
But, the following doesn't work - I still get empty.
<a href="#" class="answer" data-type="textarea" emptytext="Description" data-pk="1" data-resource="task" data-source="/tasks" data-name="longdesc" data-url="/tasks/<%= task.id %> ">

This is the javascript:
  $(".answer").editable
    placement: 'bottom'

Thanks for the help.

A: it's not emptytext="Description" but data-emptytext="Description".
<a href="#" class="answer" data-type="textarea" data-emptytext="Description" data-pk="1" data-resource="task" data-source="/tasks" data-name="longdesc" data-url="/tasks/<%= task.id %> ">

You can also do it in javascript instead of inline html.
$('.answer.description').editable({
    placement: 'bottom',
    emptytext: 'Description'
});

EDIT about HTML5
Look here about HTML5 data-attribute. This is why all the x-editable's settings start with data-*.
EDIT Answering your comment
You can do like in the official demo Look at the sex select with the prepend data (and display tweak):
$('#sex').editable({
    prepend: "not selected",
    source: [
        {value: 1, text: 'Male'},
        {value: 2, text: 'Female'}
    ],
    display: function(value, sourceData) {
        var colors = {"": "gray", 1: "green", 2: "blue"},
        elem = $.grep(sourceData, function(o){return o.value == value;});
        if(elem.length) {
            $(this).text(elem[0].text).css("color", colors[value]);
        } else {
            $(this).empty();
        }
    }
});

Or you can directly add a sourceData with {value: 0, text: 'Null'}

A: or you can use
$('.answer').editable({
placement: 'bottom',
defaultValue: 'Description' // for default value
});


text:
Q: problem with GZIP CKEditor i want to gzip ckeditor.js  and i changed extension from js to php and added this line to ckeditor.js.php file
<?php
ob_start ("ob_gzhandler");
header("Content-type: text/javascript; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 ;
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
?>

this code work for other .js files but this error appear for ckeditor.js.php page:
Error: CKEditor not found.This sample assumes that CKEditor (not included with CKFinder) is installed inthe "/ckeditor/" path. If you have it installed in a different place, just editthis file, changing the wrong paths in the <head> (line 5) and the "BasePath"value (line 32).

i found ckeditor_php5.php and change
* $CKEditor->basePath = '/ckeditor/'; to  $CKEditor->basePath = '/ckeditor/ckeditor.js.php'; but it doesnt work.

A: If you want to compress static resources it's better to do it via apache mod_deflate. PHP is slow and shouldn't be used for compressing static resources because processing will keep happening no matter how many times the file is requested. Also mod_deflate will handle cases where the client does not support gzip.
In addition in your example you have to modify possibly more than one place in the original code. That means than upgrading ckeditor will be harder later on.


text:
Q: SNMP commands from a Linux server I want to probe a device in SNMP from a Linux server. I need to know all the commands that are valid from the server(SNMP Manager). Can anyone provide me with the link where I can study all the commands? I have searched a lot but I am able to find only few commands that can used to probe the device.
Thank You!

A: Refer to SNMP rfc section 4.1.1 on-wards to see the basic SNMP Request PDU's. https://www.rfc-editor.org/rfc/rfc1157#section-4.1.1
There are multiple tools free and licensed that you could use to probe SNMP Agent(server). One such command line tool is net-snmp based. Refer the following link for the same.
http://manpages.ubuntu.com/manpages/hardy/man1/snmpcmd.1.html
The above reference has man pages related to snmpget/snmpwalk to get you started.
Hope it helps!


text:
Q: regex getting number from tags I am trying get this number which is between tags << >>
333333

from
string = "my subject <<my-support-id=333333>>"

Can you give any advise as I am not getting anywhere
I am trying to get this using preg_match function in php.

A: How about the regex
/<<[^\d]+(\d+)>>/

*

*[^\d]+ Negated character class. would match anything other than digits, \d

*(\d+) Capture group 1 will contain the digits within the << >>
Regex Demo
Test
preg_match("/<<[^\d]+(\d+)>>/", "my subject <<my-support-id=333333>>",$matches);
print_r($matches[1]);
=> 333333

OR
/<<[^=]+=(\d+)>>/

Test
preg_match ( "/<<[^=]+=(\d+)>>/", "my subject <<my-support-id=333333>>",$matches);
print_r($matches[1]);
=> 333333

A: Try this:
preg_match_all('/\=([0-9]+)>/','my subject <<my-support-id=333333>>', $out, PREG_PATTERN_ORDER);
echo $out[1][0];

A: You could do this -
$string = "my subject <<my-support-id=333333>>";
$pattern = '/\d+/';
preg_match($pattern, $string, $matches);
print_r($matches);

And the output would be Array ( [0] => 333333 )
EXAMPLE


text:
Q: How print files with certain names inside a folder I have a folder with many files that have similar names. This is my code so far.
directory = r"C:\Users\matth\Downloads\AMSRE"
for root, dirs, filenames in os.walk(directory):
    for f in filenames:
        if f == "AMSR_E_L3_DailyLand_V06_201001?":
            log = open(os.path.join(root, f), 'r')
            file_name = (("C:\\Users\\matth\\Downloads\\AMSRE\\") + f)
            print(file_name)

However, nothing is printing. I used this line if f == "AMSR_E_L3_DailyLand_V06_201001?": because I have many files with similar names:

*

*AMSR_E_L3_DailyLand_V06_20100101.hdf,

*AMSR_E_L3_DailyLand_V06_20100102.hdf,

*AMSR_E_L3_DailyLand_V06_20100103.hdf,

*and so on.

I'm  not completely sure if I am using the question mark right. Does anyone know what's wrong?

A: Python doesn't support wildcards or placeholders like * or ? in normal comparisons. As @inspectorG4dget pointed out in the comments you could just check if it starts with a specific string (str.startswith):
if f.startswith("AMSR_E_L3_DailyLand_V06_201001"):

instead of:
if f == "AMSR_E_L3_DailyLand_V06_201001?":


text:
Q: How can I prevent spaces in file names from causing the file name from appearing in the output when using graphicx? I keep getting the file name of my images next to the image. For example:

*

*The full path of the file is \\Shared Folders\courses\acce\14\exams\mtndfa.png. From reading other tex.stackexchange questions, I found that the problem is almost certainly the space between "Shared" and "Folders". Unfortunately, as I'm using VMWare, I don't think there is much I can do about that name; that's the name VMWare gives it. (The files are on my Mac disk, but TeX is running under Windows on a VM.)

*I know I could compile on the Mac, but my editor (Scientific Workplace) is on Windows, so that's not very convenient.

*I also learned that using grffile might help; it didn't.

*Finally I learned that using quotes around the file name might help, but as the file name is relative, not absolute, the problem is not with the name as it is in my TeX file, but as it is after being made absolute.  Perhaps this is why griffle didn't help.

Here is the start of my file:
\documentclass{article}%
\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{grffile}%
\setcounter{MaxMatrixCols}{30}%
\usepackage{amssymb}

EDIT: I found out that SWP is rewriting the \includegraphics command. I've updated the code below.
And, here is the \includgraphics command
\begin{figure}[ptb]%
\centering
\includegraphics[
natheight=0.866500in,
natwidth=1.886200in,
height=0.8994in,
width=1.9242in
]%
{//vmware-host/Shared Folders/courses/acce/14/exams/mtndfa.png}%
\end{figure}

How can I prevent spaces in file names from causing the file name from appearing in the output when using  graphicx?


text:
Q: What is the best way to fit classification variables in linear regression? I'm trying to build a model for a dataset that looks like this:

I builded one using just the non-classification variables (age, bmi and child), but the predictions are not accurate. How can i fit the classification variables (sex, smoker and region) into the model? I tryied to just convert them and normalize but it doesn't seems to work


text:
Q: Should closed questions have discussion in comments? I just noticed this question where the question was closed, then exploded into discussion in the comments (even with some people who closed it).  If a question needs a response, shouldn't it be left open (especially if it gets marked community wiki), or is closing and commenting the right thing to do?
Note: The question has been re-opened, and re-closed again.

A: I voted to close it as Subjective and Argumentative... which it is. Then I took some time to demonstrate that it was subjective and argumentative.
Too subtle?

A: The discussion in the comments seemed to have been about community wikiizing the question because of its open-ended nature. It was closed, then community wikified, then reopened. That's a fairly normal lifecycle for open-ended questions that users try to milk for Internet dollars.

A: The biggest problem with this question is that it is truly subjective and argumentative. Some subjectivity is OK, but this question reeks of one designed to spark controversy and extended discussion.
From the FAQ:

Avoid asking questions that are
subjective, argumentative, or require
extended discussion. This is not a
discussion board, this is a place for
questions that can be answered!

There have always been some subjective questions around; subjectivity is not the issue. It's the argumentative stance that this question takes:

Are frameworks too vulnerable to exploits? ...
Do the benefits of frameworks outweigh the fact that they basically make your website an open book? ...
Maybe frameworks aren't all they're cracked up to be and they were instead simply a push in order to get more web developers to use best practices and design patterns?

Is there anything shown above which isn't argumentative?
Three of the five reopen votes were folks at the lower end of the close/reopen vote rep spectrum, and one was the OP (who just barely has enough to do so on his own questions). This implies to me some misunderstanding as to why there were five votes to close (all but one from 7,000+ users) in the first place. Interestingly, one of the people who voted to close initially also voted to reopen -- I guess he figured that if it was CW, it was OK.
Ultimately: SO is not a discussion board. SO is not a social network. SO is a Q&A board, with an emphasis on the A -- and there is no true A to this question.

A: Just making a question CW is no justification for keeping it open, why don't people understand that?

A: It's the natural order of things on SO.
If a question is closed, those that oppose the closing may give their 'answer' in the comments to show that even if the question is bad, a good answer might make the whole thing worthwhile.
This has the effect of convincing others to support opening the question, and is simply part of the tug of war as the community decides collectively whether the question is valuable or not.


text:
Q: Django: How to make Boto work with CachedStaticFilesStorage Using Django 1.5rc (tried 1.4 too) I am trying to make the CachedStaticFilesStorage work with Boto.
When I use CachedStaticFilesStorage without Boto it works just fine:
DEFAULT_FILE_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'

STATICFILES_S3_OPTIONS = {
    "bucket": "bucket-name"
}

python manage.py collectstatic

Copying '/user/project/static/css/min/styles.min.css'
Copying '/user/project/static/js/min/scripts.min.js'
Post-processed 'styles.min.css' as 'styles.min.694c8cd7e18b.css
Post-processed 'scripts.min.js' as 'scripts.min.1111e876b4f7.js

However, when I change the storage backend this is what happens:
DEFAULT_FILE_STORAGE = "storages.backends.s3boto.S3BotoStorage"
STATICFILES_STORAGE = "project.storage.CachedStaticS3BotoStorage"

python manage.py collectstatic

Copying '/user/project/static/css/min/styles.min.css'
Copying '/user/project/static/js/min/scripts.min.js'

File "/user/.virtualenvs/project/lib/python2.7/site-packages/boto/s3/bucket.py", line 461, in new_key
    raise ValueError('Empty key names are not allowed')
ValueError: Empty key names are not allowed
ValueError: Empty key names are not allowed

Here is my storage.py
from django.conf import settings
from django.contrib.staticfiles.storage import CachedFilesMixin
from storages.backends.s3boto import S3BotoStorage

class CachedStaticS3BotoStorage(CachedFilesMixin, S3BotoStorage):
    def __init__(self, *args, **kwargs):
        kwargs.update(getattr(settings, "STATICFILES_S3_OPTIONS", {}))
        super(CachedStaticS3BotoStorage, self).__init__(*args, **kwargs)


text:
Q: How to get the list of values of different classes for a feature? I have a dataframe. I want to get the list of all values of different classes.
df = pd.DataFrame([(3, 1),
                    (4, 3),
                    (6, 2),
                    (7, 2),
                    (2, 3),
                    (4, 2),
                    (4, 1),
                    (1, 3),
                    (6, 3),
                    (8, 1)],
                    columns=['Feature', 'Class'])

In the above example, I have three classes, namely 1, 2, and 3. I would like to get the output of all different lists of values in a class. The output can be following:
Class 1: [3, 4, 8]
Class 2: [6, 7, 4]
Class 3: [4, 2, 1, 6]

A: You can do it simply:
classes = df.groupby('Class')['Feature'].apply(list)

Output:
>>> classes
Class
1       [3, 4, 8]
2       [6, 7, 4]
3    [4, 2, 1, 6]
Name: Feature, dtype: object

You can print them like this:
>>> for class_number, items in classes.items():
...     print(f'Class {class_number}: {items}')
...
Class 1: [3, 4, 8]
Class 2: [6, 7, 4]
Class 3: [4, 2, 1, 6]

If you want to get all unique values, try this:
unique = df.groupby('Class')['Feature'].unique()

A: As pointed out in this great answer, you can use the pandas.DataFrame.groupby() method along with the pandas.DataFrame.apply() method to achieve this:
import pandas as pd

df = pd.DataFrame([(3, 1),
                   (4, 3),
                   (6, 2),
                   (7, 2),
                   (2, 3),
                   (4, 2),
                   (4, 1),
                   (1, 3),
                   (6, 3),
                   (8, 1)],
                  columns=['Feature', 'Class'])

print(df.groupby('Class')['Feature'].apply(list))

Output:
Class
1       [3, 4, 8]
2       [6, 7, 4]
3    [4, 2, 1, 6]
Name: Feature, dtype: object

But if you want to loop through the class numbers one by one, a more intuitive way would be to use the pandas.DataFrame.loc property like so:
print(df.loc[df['Class'] == 1])

Output:
   Feature  Class
0        3      1
6        4      1
9        8      1

Or include the "Feature" column to get:
print(df.loc[df['Class'] == 1]["Feature"])

Output:
0    3
6    4
9    8
Name: Feature, dtype: int64


text:
Q: read json file and aggregate # value Read json file and count the unique # value as per User_Name.
I/P and O/P as per the below.
Input File :-
{
  "id": "0",
  "User_Name": "ANUP",
  "Tweet": "I love #BigData it is growing too fast #tech #spark #Hive"
}
{
  "id": "1",
  "User_Name": "ANUP",
  "Tweet": "I love #BigData it is growing too fast #tech #sqoop #HBASE"
}
{
  "id": "2",
  "User_Name": "Suraj",
  "Tweet": "My passion is #sport it help us to be #active #sport #fitness"
}
{
  "id": "3",
  "User_Name": "Gagan",
  "Tweet": "I love #BigData it is growing too fast #tech #spark #Hive"
}

o/p:-
user_name  Tweet
Anup         6
Suraj         4
Gagan         4

A: First part of your problem is reading from a JSON file which is pretty straight forward, just google it :)
About the second part, so the first thing you need is a regular expression that can recognize hashtags inside your strings, and extract them:
val getTagsPattern = "#(\\p{L}+)".r

Where L means any letter (not only English). Now let's use this regular expression inside a user defined function:
val getTags = udf[Set[String], String](tweet => {
  getTagsPattern.findAllMatchIn(tweet).map(_.group(1)).toSet
})

After extracting tags from tweets, you also need another aggregation function which can get tags of each row, and return a Set of all unique tags for a user:
val mergeUserTags = udf[Int, Array[Array[String]]](allTags => {
  allTags.foldLeft(Set.empty[String])(_ ++ _).size
})

What this UDF does is basically grab an input like [[Spark, Hive], [Sports, Hive]] and return Set[Spark, Hive, Sports] (eliminates non-unique tags). Now we have everything, just put them in the right order:
df.withColumn("Tags", getTags(col("Tweet")))
    .groupBy(col("User_Name"))
    .agg(mergeUserTags(collect_set(col("Tags"))) as "Tweet")

Results into:
+---------+-----+
|User_Name|Tweet|
+---------+-----+
|ANUP     |6    |
|Suraj    |3    |
|Gagan    |4    |
+---------+-----+


text:
Q: Mocha/Should 'undefined is not a function' I'm going off of this tutorial, trying to make tests with Mocha, Supertest, and Should.js.
I have the following basic test to create a user through a PUT endpoint that accepts it's data in headers.
describe('User Routes', function () {
    it('should allow me to make my user', function (done) {
        request(url)
        .put('/users')
        .set(myCreds)
        // end handles the response
        .end(function(err, res) {
              if (err) {
                throw err;
              }
              // this is should.js syntax, very clear
              res.should.have.status(201);
              done();
            });
        });

However, while the endpoint does trigger, and the user does get made, the code throws an error that should is undefined... Uncaught TypeError: undefined is not a function.
I have
var should = require('should');
var assert = require('assert');
var request = require('supertest');

At the top of the file, so why would it be undefined?

A: You are calling should incorrectly, try this:
res.should.have.property('status', 201)

or
res.status.should.be.equal(201)

or
should.equal(res.status, 201)

or install should-http.


text:
Q: Is there an existing PropertyGrid UITypeEditor for type "ChartColorPalette"? I'm trying to write a simple property grid to allow the users to modify the colours of a Chart. By default, a Chart has a "Palette" property, which is of the enumeration type "ChartColorPalette". If the object which underlies my property grid also has a "Palette" property of the same type, I get the drop-down list of possible values. What I don't get however, is the little stripey images to the left of the value names.
Now, I can write a UITypeEditor derived class and have the "PaintValue" draw little resource bitmaps which I have culled from the screen using "Paint" or somesuch, but this seems rather tedious.
Does anyone know if there is already a type editor for the "ChartColorPalette" enumeration which I can use to get the little bitmaps ?

A: as it happens, writing the UITypeEditor is not that tricky, and not that much code either.
Firstly I created a type editor that looked like this:
private class ChartColorPaletteEditor : UITypeEditor
{
    public override bool GetPaintValueSupported(ITypeDescriptorContext context)
    {
        return true;
    }

    public override void PaintValue(PaintValueEventArgs e)
    {
        String paletteName = e.Value.ToString();
        String baseName = this.GetType().Namespace + ".MyChart";
        ResourceManager mgr = new ResourceManager(baseName, this.GetType().Assembly);
        Bitmap bmp = mgr.GetObject(paletteName) as Bitmap;
        if (bmp != null)
        {
            e.Graphics.DrawImage(bmp, e.Bounds);
            bmp.Dispose();
        }
    }
}

I attached this to my control property in the usual way:
[DefaultValue(typeof(ChartColorPalette), "BrightPastel")]
[Editor(typeof(ChartColorPaletteEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Category("Appearance")]
[Description("The named palette to use when choosing the colour scheme for the chart series lines.")]
public ChartColorPalette Palette { get; set; }

Then I added a small PNG resource for each of the little palette images. I had a derived control "MyChart" which inherited from "Chart" and I added the images to that as resources (making sure to set the "Persistance" property to "Embedded in .resx" to save having to keep the PNG files about). The names of the PNG files matched the names in the ChartColorPalette enumeration.
The only issue was where to get the little 20 x 14 images from. I originally just culled them using Paint.exe but didn't like that, so I wrote some code to generate them for me. That was fairly simple, once I had found the colour values that are used by the Charting control. One subtlety is that, where there are more than 12 colours in a palette, the little bitmap uses every other colour. That code looked like this:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Windows.Forms.DataVisualization.Charting;

namespace ConsoleApplication10
{
class Program
{
  static void Main(string[] args)
  {
     Enum.GetValues(typeof(ChartColorPalette)).OfType<ChartColorPalette>().ToList().ForEach(GeneratePNG);
  }

  static void GeneratePNG(ChartColorPalette palette)
  {
     if (palette == ChartColorPalette.None) return;

     Color[] colours = palette.GetColors();

     if (colours.Length >= 12)
     {
        colours = new Color[] { colours[0], colours[2], colours[4], colours[6], colours[8], colours[10] };
     }
     else
     {
        colours = new Color[] { colours[0], colours[1], colours[2], colours[3], colours[4], colours[5] };
     }

     using (Bitmap bmp = new Bitmap(20, 14))
     {
        using (Graphics gr = Graphics.FromImage(bmp))
        {
           using (SolidBrush b1 = new SolidBrush(colours[0]),
                             b2 = new SolidBrush(colours[1]),
                             b3 = new SolidBrush(colours[2]),
                             b4 = new SolidBrush(colours[3]),
                             b5 = new SolidBrush(colours[4]),
                             b6 = new SolidBrush(colours[5]))
           {
              int height = bmp.Height - 2;
              gr.DrawRectangle(Pens.Black, 0, 0, bmp.Width - 1, bmp.Height - 1);
              gr.FillRectangle(b1, new Rectangle(1, 1, 3, height));
              gr.FillRectangle(b2, new Rectangle(4, 1, 3, height));
              gr.FillRectangle(b3, new Rectangle(7, 1, 3, height));
              gr.FillRectangle(b4, new Rectangle(10, 1, 3, height));
              gr.FillRectangle(b5, new Rectangle(13, 1, 3, height));
              gr.FillRectangle(b6, new Rectangle(16, 1, 3, height));
           }
        }

        String path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        path = Path.Combine(path, @"Visual Studio 2010\Projects\DataVisualization.Charting\Palette Bitmaps");

        String filename = palette.ToString() + ".png";
        bmp.Save(Path.Combine(path, filename), ImageFormat.Png);
     }
  }
}

public static class Extensions
{
  public static Color[] GetColors(this ChartColorPalette value)
  {
     switch (value)
     {
        case ChartColorPalette.Berry:
           return GetColors(0x8a2be2, 0xba55d3, 0x4169e1, 0xc71585, 0x0000ff, 0x8a2be2, 0xda70d6, 0x7b68ee, 0xc000c0, 0x0000cd, 0x800080);
        case ChartColorPalette.Bright:
           return GetColors(0x008000, 0x0000ff, 0x800080, 0x00ff00, 0xff00ff, 0x008080, 0xffff00, 0x808080, 0x00ffff, 0x000080, 0x800000, 0xff0000, 0x808000, 0xc0c0c0, 0xff6347, 0xffe4b5);
        case ChartColorPalette.BrightPastel:
           return GetColors(0x418cf0, 0xfcb441, 0xe0400a, 0x056492, 0xbfbfbf, 0x1a3b69, 0xffe382, 0x129cdd, 0xca6b4b, 0x005cdb, 0xf3d288, 0x506381, 0xf1b9a8, 0xe0830a, 0x7893be);
        case ChartColorPalette.Chocolate:
           return GetColors(0xa0522d, 0xd2691e, 0x8b0000, 0xcd853f, 0xa52a2a, 0xf4a460, 0x8b4513, 0xc04000, 0xb22222, 0xb65c3a);
        case ChartColorPalette.EarthTones:
           return GetColors(0xff8000, 0xb8860b, 0xc04000, 0x6b8e23, 0xcd853f, 0xc0c000, 0x228b22, 0xd2691e, 0x808000, 0x20b2aa, 0xf4a460, 0x00c000, 0x8fbc8b, 0xb22222, 0x8b4513, 0xc00000);
        case ChartColorPalette.Excel:
           return GetColors(0x9999ff, 0x993366, 0xffffcc, 0xccffff, 0x660066, 0xff8080, 0x0066cc, 0xccccff, 0x000080, 0xff00ff, 0xffff00, 0x00ffff, 0x800080, 0x800000, 0x008080, 0x0000ff);
        case ChartColorPalette.Fire:
           return GetColors(0xffd700, 0xff0000, 0xff1493, 0xdc143c, 0xff8c00, 0xff00ff, 0xffff00, 0xff4500, 0xc71585, 0xdde221);
        case ChartColorPalette.Grayscale:
           return GetColors(0xc8c8c8, 0xbdbdbd, 0xb2b2b2, 0xa7a7a7, 0x9c9c9c, 0x919191, 0x868686, 0x7b7b7b, 0x707070, 0x656565, 0x5a5a5a, 0x4f4f4f, 0x444444, 0x393939, 0x2e2e2e, 0x232323);
        case ChartColorPalette.Light:
           return GetColors(0xe6e6fa, 0xfff0f5, 0xffdab9, 0xfffacd, 0xffe4e1, 0xf0fff0, 0xf0f8ff, 0xf5f5f5, 0xfaebd7, 0xe0ffff);
        case ChartColorPalette.Pastel:
           return GetColors(0x87ceeb, 0x32cd32, 0xba55d3, 0xf08080, 0x4682b4, 0x9acd32, 0x40e0d0, 0xff69b4, 0xf0e68c, 0xd2b48c, 0x8fbc8b, 0x6495ed, 0xdda0dd, 0x5f9ea0, 0xffdab9, 0xffa07a);
        case ChartColorPalette.SeaGreen:
           return GetColors(0x2e8b57, 0x66cdaa, 0x4682b4, 0x008b8b, 0x5f9ea0, 0x3cb371, 0x48d1cc, 0xb0c4de, 0xffffff, 0x87ceeb);
        case ChartColorPalette.SemiTransparent:
           return GetColors(0xff6969, 0x69ff69, 0x6969ff, 0xffff69, 0x69ffff, 0xff69ff, 0xcdb075, 0xffafaf, 0xafffaf, 0xafafff, 0xffffaf, 0xafffff, 0xffafff, 0xe4d5b5, 0xa4b086, 0x819ec1);
        case ChartColorPalette.None:
        default:
           return GetColors(0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000);
     }
  }

  private static Color[] GetColors(params Int32[] values)
  {
     return values.Select(value => Color.FromArgb(255, Color.FromArgb(value))).ToArray(); // alpha channel of 255 for fully opaque
  }
 }
}

Hope this is useful to someone out there...


text:
Q: Watir webdriver not working as expected I tried to execute a simple browser test
require 'rubygems'
require 'watir-webdriver'
b = Watir::Browser.new :firefox
b.goto 'http://www.google.com/'

The browser launched and closed immediately throwing the following error
c:/ruby22/lib/ruby/2.2.0/net/http/generic_request.rb:25:in `initialize': HTTP request path is empty (ArgumentError)
    from c:/ruby22/lib/ruby/2.2.0/net/http/request.rb:14:in `initialize'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/default.rb:95:in `new'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/default.rb:95:in `new_request_for'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/default.rb:57:in `request'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/default.rb:88:in `request'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/http/common.rb:59:in `call'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:649:in `raw_execute'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:123:in `create_session'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/remote/bridge.rb:87:in `initialize'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/firefox/bridge.rb:55:in `initialize'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:53:in `new'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:53:in `for'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver.rb:84:in `for'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/browser.rb:46:in `initialize'
    from test.rb:3:in `new'
    from test.rb:3:in `<main>'

HTTP request path is empty means what? is the calling parameters changed in new versions of watir?
Anyone faced similar problem?
My System is Windows 7 64 bit, I am running behind a proxy, the browser already configured with a proxy
---EDIT---
I have introduced a trailing slash, but I am getting a new error now and also getting the previous error, every time I have to change the code and save it to get this error
c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/firefox/launcher.rb:90:in `connect_until_stable': unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) (Selenium::WebDriver::Error::WebDriverError)
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/firefox/launcher.rb:55:in `block in launch'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/socket_lock.rb:43:in `locked'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/firefox/launcher.rb:51:in `launch'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/firefox/bridge.rb:43:in `initialize'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:53:in `new'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver/common/driver.rb:53:in `for'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/selenium-webdriver-2.53.4/lib/selenium/webdriver.rb:84:in `for'
    from c:/ruby22/lib/ruby/gems/2.2.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/browser.rb:46:in `initialize'
    from test.rb:8:in `new'
    from test.rb:8:in `<main>'

---EDIT---
I have downloaded the geckodriver v0.10.0 from https://github.com/mozilla/geckodriver/releases and copy pasted the geckodriver.exe in to the firefox folder and also added the firefox folder to the PATH
I installed the selenium-webdriver beta version 3.0.0.beta2.1
But still I am getting the same error
c:/ruby22/lib/ruby/2.2.0/net/http/generic_request.rb:25:in `initialize': HTTP request path is empty (ArgumentError)

I have also tried installing the Firefox ESR version and added to PATH which is also not working
---EDIT---
I opened the file c:/ruby22/lib/ruby/2.2.0/net/http/generic_request.rb
and introduced print statement as follows
print "\n"
print uri_or_path

if URI === uri_or_path then
  print "\ncoming to if part\n"
  @uri = uri_or_path.dup
  host = @uri.hostname.dup
  host << ":".freeze << @uri.port.to_s if @uri.port != @uri.default_port
  @path = uri_or_path.request_uri
  raise ArgumentError, "no HTTP request path given" unless @path
else
  print "\ncoming to else part\n"
  @uri = nil
  host = nil
  raise ArgumentError, "no HTTP request path given" unless uri_or_path
  raise ArgumentError, "HTTP request path is empty" if uri_or_path.empty?
  @path = uri_or_path.dup
end

And I got the below output
/session
coming to else part

coming to else part

/shutdown
coming to else part
c:/ruby22/lib/ruby/2.2.0/net/http/generic_request.rb:29:in `initialize': HTTP request path is empty (ArgumentError)

A: Try entering those commands in IRB, a line at a time.  that will make it clearer where the failure is occuring
Your initial error indicated it was failing on line 3,which in your code above is where it tries to create a new instance of a browser object (which also launches firefox, and then tries to connect the browser object to the actual browser).   If that's not working it's usually because you are not using a version of webdriver that supports your browser.   Perhaps you have a brand new firefox, and need to update webdriver.
Sometimes there is a brief window after a new FF comes out (every 6 weeks) that introduced a breaking change, where we don't have an updated webdriver gem that supports that version.

A: Most likely you were seeing this due to a bug in Firefox 47.0. You need to update to Firefox 47.0.1 for it to work with Selenium 2.53.4.


text:
Q: Kendo UI Grid in MVC - How to return selected row Item to Controller I have an MVC 4 application with a Kendo UI grid that I am using for user management. I display the users information in the grid and have a custom command button that when clicked opens a new page to edit the users information. For various reasons (one being there is too much information to be edited to display in the grid) I need to edit the users on a new page and not with inline or popup or incell editing. My grid looks like this... very simple
@(Html.Kendo().Grid<WebSiteNew.Models.ManageUsersViewModel>()
.Name("grid")
.HtmlAttributes(new { style = "margin-top: 5px" })
.Columns(c =>
{
    c.Bound(model => model.UserName);
    c.Bound(model => model.FirstName);
    c.Bound(model => model.LastName);
    c.Bound(model => model.Email);
    c.Bound(model => model.Phone);
    c.Bound(model => model.Extension);
    c.Bound(model => model.JobTitle);
    c.Command(com => { com.Custom("Edit").Click("edit"); com.Destroy(); });
})
.Pageable()
.Sortable()
.Selectable()
.DataSource(d => d
    .Ajax()
    .PageSize(20)
    .Model(m => m.Id(i => i.UserName))
    .Read(r => r.Action("ManageUsers_Read", "ManageUsers"))
    .Destroy(o => o.Action("ManageUsers_Destroy", "ManageUsers"))
))

The issue I have here is that I need to pass the ID of the user that the edit button has been clicked on to the edit screen so that I can bring up the information for the selected user. The only way I know of to get this information is through javascript, something like this in my command button click function...
function edit() {
    var grid = $("#grid").data("kendoGrid");
    var row = grid.select();
    var dataItem = grid.dataItem(row);
    var id = dataItem.UserId;

    location = "@Url.Action("EditUser")";
}

This gives me the id that I need but I have no way (that I know of) to pass this back to my controller. So my question is... how do I get this information back to the server side? Is there another way to get the information I need or is this just something that is not possible in Kendo UI MVC?
To make this a more general question.. when I look at the Kendo UI documentation and it tells me how to get a value in javascript... how, in general, does one go about using this value in an MVC application when it is needed on the server side? I can't seem to find an alternative "MVC" way to do this in their documentation.

A: You should form additional parameters to url string:
location = "@Url.Action("EditUser")" + "?id="+id;


text:
Q: What's causing iTunes to randomly display a 4002 error? Once every day or two, iTunes seemingly randomly displays a 4002 error:

This is particularly puzzling to me, as the majority of the time (if not always) iTunes is in the background, and has been for a while. What exactly does the error signify, and how can I fix it?

A: I got rid of this pesky error by

*

*turning iTunes Match off

*quit iTunes

*launch iTunes

*turn iTunes Match on

The first time iTunes complained with error 5002 during Match startup, but then it worked.

A: Google seems to think it's an iTunes Genius error.  Try turning off Genius from Store -> Turn off Genius.
If that doesn't resolve your issue, if Genius is not on, or if it's too important to turn off, post more info about your system and we'll try to help.

A: I have been importing quite a few songs into iTunes v 10.7 (21) on OS X 10.8.2 and this error is popping up when the upload process has a hiccup. Even if you are not currently in a state when you would expect uploading to the iTunes Match cloud, the software can run a sync and throw this error.
There's nothing you can normally do on your end other than disconnect from the internet and wait for the servers to clear up. In my case, no action was needed to resume uploads. The iTunes process was patient and resumed once a short timeout passed.


text:
Q: System.UnauthorizedAccessException Access to the path 'Google.Apis.Auth' is denied with Gmail Api I have implemented Gmail Api for email management..but on my local IIS , it's giving below error
System.UnauthorizedAccessException Access to the path 'Google.Apis.Auth' is denied.
I have given permission to "EveryOne" on the Project Folder and also on the "~\AppData\Roaming\Google.Apis.Auth" as  i have read somewhere that Gmail Api access this folder for token/details..
Following code i am using :
UserCredential credential;
            using (var stream = new FileStream(Server.MapPath("/") + "client_secrets_desktop.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                    new[] { GmailService.Scope.GmailReadonly },
                    "user", CancellationToken.None);
            }
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Gmail Test",
        });

        try
        {
            ListLabelsResponse response = service.Users.Labels.List("me").Execute();
            //foreach (Label label in response.Labels.OrderBy(p => p.Name))
            //{
            //    Console.WriteLine(label.Id + " - " + label.Name);
            //}
        }

Thanks in advance...

A: Had same problem and solved it adding the dataStore parameter to
GoogleWebAuthorizationBroker.AuthorizeAsync()

the call that generates the credentials. That is adding FileDataStore(storage)
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            createdByUser,
            CancellationToken.None,
            new FileDataStore(storage)).Result;

where 'storage' is a local folder (ex. /App_Data/folder) where ASP.NET user should have read/write permissions.


text:
Q: How To Read Data Into A List Structure in C#? I am writing a program that uses a StudentStruct (structure) that consists of: studentID, studentName, and grades (which is a separate List). The program is supposed to read in a sequential text file and contains methods that allow the user to: Add Student, Add Grades (to a particular student), Change Student Name, and Delete Student. At the end of the program it is supposed to overwrite the previous file with the new changes made from the current program session.
My question is how do I read in data from the text file into the separate structure variables within the lists?
My text file looks like this:
00000,Mimzi Dagger,100,50,75,70,45,10,98,83
00001,Alexander Druaga,89,45,80,90,15,73,99,100,61
00002,Nicholas Zarcoffsky,100,50,80,50,75,100,100
00003,Kantmiss Evershot,50,100

Once the structure variables within the list are filled, how do I overwrite the file with the contents of the List structure in the same format as the above file?
Since I have multiple and varying amounts of grades, how would I achieve looping through and adding each grade to the grades list?
As you can maybe already tell, I am very new to c# and this is my first project. Any help would be greatly appreciated!
    class Program
    {
        static string pathSource = @"C:\schoolfiles\StudentGrades.txt";

        struct StudentStruct
        {
            public string studentID;
            public string studentName;
            public List<string> grades;
        }

        static void Main(string[] args)
        {
            StudentStruct student = new StudentStruct();
            List<StudentStruct> myList = new List<StudentStruct>();
            student.grades = new List<string>();
        }

UPDATE: Here is what I have come up with so far:
for (int i = 0; i < fileLines.Length; i++)
{
    output = fileLines[i];
    string[] outputArray = output.Split(',');

    student.grades = new List<string>();
    student.studentID = outputArray[0];
    student.studentName = outputArray[1];

    for (int j = 2; j < outputArray.Length; j++)
    {
        student.grades.Add(outputArray[j]);
    }

    myList.Add(student);

UPDATE: The code above worked out wonderfully. Here is the top part of my code involving this question:
static void Main(string[] args)
    {
        //Declare variables
        string output;

        //Read the File into an array
        string[] fileLines = File.ReadAllLines(PathSource);

        StudentStruct student = new StudentStruct();
        List<StudentStruct> myList = new List<StudentStruct>();

        for (int i = 0; i < fileLines.Length; i++)
        {
            output = fileLines[i];
            string[] outputArray = output.Split(',');

            student.grades = new List<string>();
            student.studentID = outputArray[0];
            student.studentName = outputArray[1];

            for (int j = 2; j < outputArray.Length; j++)
            {
                student.grades.Add(outputArray[j]);
            }

            myList.Add(student);
        }

        MainMenu(myList);
    }

And then to add the list back to the file I did this:
static void ExitModule(List<StudentStruct> myList)
    {
        //Declare variables
        string inputChoice = null;
        string output = null;

        System.IO.StreamWriter file = new System.IO.StreamWriter(PathSource);

        Console.Clear();
        Console.WriteLine("Are You Sure You Want To Exit The Program? Y/N");
        inputChoice = Console.ReadLine();

        if (inputChoice == "Y" || inputChoice == "y")
        {
            for (int i = 0; i < myList.Count; i++)
            {
                output = (myList[i].studentID + "," + myList[i].studentName);

                for (int j = 0; j < myList[i].grades.Count; j++)
                {
                    output += ("," + myList[i].grades[j]);
                }

                file.WriteLine(output);
            }

            file.Close();
            Environment.Exit(0);

A: Since this is clearly homework, it may be a good time for you to learn about data structures. This will help you store the information you've read in from the text file efficiently, allowing you to write it out much more easily after modifying the records.
Here are a couple of other random pointers:

*

*The System.IO.File.ReadLines(pathSource) method would be a good place to start reading each line of a text file

*You should almost never be using a struct in C# (especially one that is mutable like in your example) unless you are well-versed in its semantics and purpose. Use a class instead

A: try this code. it's working for me
class Program
    {
        static string pathSource = @"C:\schoolfiles\StudentGrades.txt";

        struct StudentStruct
        {
            public string studentID;
            public string studentName;
            public List<string> grades;
        }

        static void Main(string[] args)
        {
            StudentStruct student = new StudentStruct();
            List<StudentStruct> myList = new List<StudentStruct>();
            student.grades = new List<string>();

            // get all lines from text file
            string[] allLinesFromFile = File.ReadAllLines(pathSource);

            // iterate through each line and process it
            foreach(string line in allLinesFromFile)
            {
                // split each line on ','
                string[] sections = line.Split(',');
                student.studentID = sections[0];
                student.studentName = sections[1];

                // use this loop to add numbers to list of grades
                for(int i =2; i < sections.Length; i++)
                {
                    student.grades.Add(sections[i]);
                }

                // add this student to list
                myList.Add(student);

                // create new object of student
                student = new StudentStruct();
                student.grades = new List<string>();
            }
        }

A: A few things.
(1) I am not sure why your teacher/professor would have you use a struct here. A class is much more appropriate. I actually cringed when I first saw the code
(2) having something as a const also implies that it is static "pathSource"
(3) Properties should be capitalized "pathSource" -> "PathSource"
(4) You should separate responsibilities... Try not to put everything in Main
(5) You shouldn't have to create an instance of grades outside of StudentStruct, this can lead to errors. i.e. NullPointerException... basically the struct should be self containing.
(6) Everything should compile. I haven't tested it. If you have any issues. let me know.
Program {
    private const string PathSource = @"C:\schoolfiles\StudentGrades.txt";

    private struct StudentStruct
    {
        public string StudentID;
        public string StudentName;

        private List<string> _gradeList;

        public List<string> GradeList
        {
            // if _gradeList is null create a new instance
            get { return _gradeList ?? (_gradeList = new List<string>()); }
            private set { _gradeList = value; }
        }
    }

    private static void Main( string[] args )
    {
        var studentFile = File.ReadAllLines( PathSource );
        // If you haven't learned about delegates or extensions methods...
        // You can just change it to a foreach statement
        var myList = studentFile.Select( GetStudent ).ToList();

        // make sure we have everything
        foreach (var studentStruct in myList)
        {
            Console.WriteLine( "{0}  {1}", studentStruct.studentName, studentStruct.studentID );
            foreach (var grade in studentStruct.GradeList) { Console.Write( grade + " " ); }
            Console.WriteLine();
        }
    }

    private static StudentStruct GetStudent( string line )
    {
        var student = new StudentStruct();
        var studentDelimited = line.Split( ',' );

        student.studentID = studentDelimited[ 0 ];
        student.studentName = studentDelimited[ 1 ];

        for ( int i = 2; i < studentDelimited.Length; i++ ) { student.GradeList.Add( studentDelimited[ i ] ); }

        return student;
    }
}


text:
Q: PostgreSQL function call I have PostgreSQL function named test(integer) taking an integer parameter and an overloaded function of the same name test(character varying).
When calling this function with a null value, Postgres always executes the function taking an integer parameter. Why does this happen? Why doesn't Postgres chose the function with a varchar parameter?
Function call example:
select test(null);

A: That's decided by the rules of Function Type Resolution. Detailed explanation in the manual. Related:

*

*Is there a way to disable function overloading in Postgres
NULL without explicit type cast starts out as type "unknown":
SELECT pg_typeof(NULL)

 pg_typeof
-----------
 unknown

Actually, I got suspicious and ran a quick test, just to find different results in Postgres 9.3 and 9.4. varchar is picked over integer (which oddly contradicts your findings):
SQL Fiddle.
I would think the according rule is point 4e in the list (none of the earlier points decide the match):

At each position, select the string category if any candidate accepts
  that category. (This bias towards string is appropriate since an
  unknown-type literal looks like a string.)

If you added another function with input type text to the overloaded mix, text would be picked over varchar.
Personally I almost always use text instead of varchar. While being binary compatible (so almost but not quite the same), text is closer to the heart of Postgres in every respect.
I added that to the fiddle, as well as another example where Postgres cannot decide and throws a tantrum.
If you want to pick a particular function, add an explicit type cast (that's the way to go here!):
select test(null::int)     AS func_int
     , test(null::varchar) AS func_vc;


text:
Q: Filter rows on inequality, case-insensitively I have the following:
did_not_match = df[(df.old!=df.new)]

I am getting values that are still matching:
old     new
itest   iTest

How do update the code to account for capitalization, and get were itest and iTest are considered !=?

A: Normalise your strings, make them all uppercase, or all lowercase, all titlecase or capitalise them all, with the .str.upper(), .str.lower(), .str.title() or .str.capitalize() methods, before comparing:
did_not_match = df[df.old.str.upper() != df.new.str.upper()]

Pick one normalisation, and stick with it.
For more information on the string methods, see Working with Text Data.


text:
Q: MongoDB C# 2.4 driver's Replace method seems to ignore bson id attributes In my import function, i am replacing existing documents or adding new ones using the Upsert option:
  var builder = Builders<FacilityDocument>.Filter;
  var filter = builder.Eq(x => x.Language.LCID, lcid)
               & builder.Eq(x => x.Name, facility.Name)
               & builder.Eq(x => x.NameDetailed, facility.NameDetailed)
               & builder.Gte(x => x.ImportedDate, new DateTime(DateTime.Now.Year, 1, 1));

  collection.ReplaceOne(filter, facility, new UpdateOptions { IsUpsert = upsert });

Now in my POCO class, i have it configured to use GUID instead of an ObjectID, like this:
[BsonId]
[BsonIgnoreIfDefault]
public Guid ID { get; set; }

The problem is that in the database, instead of generating a GUID, its defaulting back to ObjectId:

And what it should be doing, is this (which works when using the regular Insert method):

Much appreciated if anyone have a solution for this.
Update
This is my entire facilitydocument class:
[BsonId]
[BsonIgnoreIfDefault]
public Guid ID { get; set; }
public string Name { get; set; }
public string NameDetailed { get; set; }
public CommuneDocument Commune { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Homepage { get; set; }
public FacilityTypeDocument FacilityType { get; set; }
public FacilityPlacement FacilityPlacement { get; set; }
public int CoursesCount { get; set; }
public CoursesData[] CoursesData { get; set; }
public OwnershipDocument Ownership { get; set; }
public OperationDocument Operation { get; set; }
public string ExternalRemarks { get; set; }
public GisLocationData GisLocationData { get; set; }
public string ContactPersonName { get; set; }
public string ContactPersonEmail { get; set; }
public string InternalRemarks { get; set; }
public bool Active { get; set; }
public LanguageDocument Language { get; set; }
public DateTime ImportedDate { get; set; }
public string ImportedBy { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
public List<ChangeLog> ChangeLog { get; set; }

Update 2
If i set my ID before the replace method, i get an error like this:
A write operation resulted in an error. The _id field cannot be changed from {_id: BinData(3, BF515DEF5743F547BD3EABB1A89DAC4D)} to {_id: BinData(3, 6364DF16640A4346B62E6B866BF76069)}

This is how i set it:
    facilityDocument.ID = Guid.NewGuid();


text:
Q: When is using a struct more reasonable than using a class in C++? I have been reading Qt Creator's source code.
When is using a struct more appropriate than using a class in C++?

A: It is purely a matter of personal preference or coding conventions. struct and class are essentially the same in C++, with the difference being the default access specifiers and base classes being public for a struct and private for a class.
For example, here two definitions of Bar are equivalent:
class Foo {};
struct Bar : Foo {};
class Bar : public Foo {};

Here too:
class Foo {};
struct Bar : private Foo {};
class Bar : Foo {};

and here too:
class Bar
{
  int n;     // private
 public:
  double x;  // public
};

struct Bar
{
 private:
  int n;
 public:
  double x;
};

Furthermore, you could forward declare Bar as class Bar or struct Bar interchangeably.

A: There's no difference aside from default access (struct => public, class => private). For readability, I prefer using struct when I'm defining a plain-old C struct (just data), or when the majority of my members/methods are public.

A: I think of struct as a record. They bundle together variables and you want to access and modify struct members without indirection, such as a function call. For example, when you want to write together groups of data items to dump them into a file or send them over network then using class may even make the code harder to read and understand.

A: It might be more suitable when it's Plain Old Data without any functionality on it. In C++, the only difference between class and struct is that struct members are public by default, as opposed to private for class.


text:
Q: Using CSS to have marquee effect i needed to use CSS3 animation to have a marquee effect with images as the html marquee tag is deprecated(but was very easy to use).The html code is as below:

The CSS3 animation effect i am using is as below:
.marquee{
display:block;
position:relative;
width:1800px;
height:160px;
animation:scroll 25s ease-in-out infinite;
}

@keyframes scroll{
0% {left:0;}
100% {left:-260px;}
}

But the problem with this solution is that if i have more number of images then the animation effect completes early and therefore the latter images are never displayed.Also,on increasing the animation duration,the images slide very slowly thereby destroying the marquee effect itself.Any help??

A: Try this plugins that will help you
http://wmh.github.io/jquery-scrollbox/
http://technicalpixel.com/continous-horizontal-jquery-image-marquee/


text:
Q: Eclipse che - volume mount error while launching workspace by 5 users at same time Configuration:

*

*Google Kubernete Engine (GKE) version - 1.18.12-gke.1210

*Nodes count - 2

*Node Configuration - 2 core 8 GB memory Machine with 30 GB hardisk

*AutoScale is enabaled

Eclipse che Advanced configuration:
server:
  CHE_WORKSPACE_POOL_EXACT__SIZE: "60"
  CHE_WORKSPACE_STORAGE_PREFERRED__TYPE: ephemeral
  allowUserDefinedWorkspaceNamespaces: false
  cheDebug: "false"
  cheFlavor: che
  cheHost: che-eclipse-che.domain.com
  cheLogLevel: INFO
  cheServerIngress: {}
  cheServerRoute: {}
  devfileRegistryIngress: {}
  devfileRegistryRoute: {}
  externalDevfileRegistry: false
  externalPluginRegistry: false
  gitSelfSignedCert: false
  pluginRegistryIngress: {}
  pluginRegistryRoute: {}
  selfSignedCert: true
  tlsSupport: true
  useInternalClusterSVCNames: true
  workspaceNamespaceDefault: all-che-workspace
storage:
  preCreateSubPaths: true
  pvcClaimSize: 128Gi
  pvcStrategy: common
  preferred_type: persistent

Bug Description :
Logged in 10 different users at the same time and launched 10 workspaces of each users at a time. 3 - 5 users are able to launch the workspace successfully, for remaining users getting time out error in mount volume, some users keep on loading the workspace and nothing is initialised in log window.
Error Screenshots :

*

*Error for User 1:

Failed to run the workspace: "Unrecoverable event occurred: 'FailedMount', 'Unable to attach or mount volumes: unmounted volumes=[claim-che-workspace], unattached volumes=[gitconfigvolume remote-endpoint che-workspace-token-dmn68 workspacep72ony0ucs0pqa5c-sshprivatekeys che-ca-certs broker-config-volume5iwa24 ssshkeyconfigvolume claim-che-workspace che-jwtproxy-config-volume]: timed out waiting for the condition', 'workspacep72ony0ucs0pqa5c.maven-d5476444f-6tcgg'"

*

*Error for User 2:

Failed to run the workspace: "Waiting for Kubernetes environment 'default' of the workspace'workspaceo6i4zoqzs1xym88w' reached timeout"

A: Try to run Che Workspace in debug mode.
See https://www.eclipse.org/che/docs/che-7/end-user-guide/investigating-failures-at-a-workspace-start-using-the-verbose-mode/
It might give you some inputs about what is going wrong.

A: The most probable cause of the issues in the question (which I've managed to reproduce) could be related to the storage configuration used.
Citing the documentation:

When the common PVC strategy is in use, user-defined PVCs are ignored and volumes that refer to these user-defined PVCs are replaced with a volume that refers to the common PVC. In this strategy, all Che workspaces use the same PVC. When the user runs one workspace, it only binds to one node in the cluster at a time.
-- Eclipse.org: Che: Docs: Configuring storage strategies: The common PVC strategy

By default when you create a PVC with GKE you are in fact creating a Persistent Disk which can be mounted in RWO access mode to a single node. If the workspace is scheduled onto a node that the PVC is not mounted to, the creation process will fail and you will get following message:
Unable to attach or mount volumes: unmounted volumes=[claim-che-workspace], unattached volumes=[che-ca-certs che-workspace-token-5tb9b broker-config-volumeavmw4x claim-che-workspace workspacebgnsca7mkryv3s3m-sshprivatekeys ssshkeyconfigvolume gitconfigvolume]: timed out waiting for the condition
Failed to run the workspace: "Plugins installation process failed. Error: Unrecoverable event occurred: 'FailedMount', 'Unable to attach or mount volumes: unmounted volumes=[claim-che-workspace], unattached volumes=[che-ca-certs che-workspace-token-5tb9b broker-config-volumeavmw4x claim-che-workspace workspacebgnsca7mkryv3s3m-sshprivatekeys ssshkeyconfigvolume gitconfigvolume]: timed out waiting for the condition', 'workspacebgnsca7mkryv3s3m.che-plugin-broker'"

I'd reckon to avoid this issue you could either (not tested):

*

*Use RWX storage solution.

*Change the storage configuration for unique.

*Use a single node.  <-- not great idea but it should work

To have more insight on the issue, you can monitor the state of Pods when creating workspace. It could tell you more about the process:

*

*$ kubectl get pods -n kruk-che:

NAMESPACE       NAME                                                        READY   STATUS              RESTARTS   AGE    IP            NODE                 NOMINATED NODE   READINESS GATES
kruk-che        workspace4pfd7goxamv8vvs4.maven-5d9c59746f-swfdd            5/5     Running             0          29m    10.4.0.58     gke-name-pool-9530   <none>           <none>
kruk-che        workspacebgnsca7mkryv3s3m.che-plugin-broker                 0/1     ContainerCreating   0          105s   <none>        gke-name-pool-qhns   <none>           <none>
kruk-che        workspacezo0l50kaa2zvm4lv.maven-8644fbf959-45xjd            5/5     Running             0          12m    10.4.0.62     gke-name-pool-9530   <none>           <none>

In above example you can see Pods in the ContainerCreating state. You can inspect them for more information about their state like:
$ kubectl describe pod -n kruk-che workspacebgnsca7mkryv3s3m.che-plugin-broker
Events:
  Type     Reason              Age   From                     Message
  ----     ------              ----  ----                     -------
  Normal   Scheduled           83s   default-scheduler        Successfully assigned kruk-che/workspacebgnsca7mkryv3s3m.che-plugin-broker to gke-name-pool-qhns
  Warning  FailedAttachVolume  83s   attachdetach-controller  Multi-Attach error for volume "pvc-869bc565-4dd1-4362-8d63-f3b1fde6f246" Volume is already used by pod(s) workspacezo0l50kaa2zvm4lv.maven-8644fbf959-45xjd, workspace4pfd7goxamv8vvs4.maven-5d9c59746f-swfdd
  Warning  FailedMount         10s   kubelet                  Unable to attach or mount volumes: unmounted volumes=[claim-che-workspace], unattached volumes=[che-ca-certs che-workspace-token-5tb9b broker-config-volumeavmw4x claim-che-workspace workspacebgnsca7mkryv3s3m-sshprivatekeys ssshkeyconfigvolume gitconfigvolume]: timed out waiting for the condition

Additional resources:

*

*Eclipse.org: Che: Installation guide: Advanced configuration options for the che server component

*Cloud.google.com: Kubernetes Engine: Docs: Concepts: Persistent Volumes


text:
Q: getComputedStyle does not include margins I am trying to freeze all elements on a page so that when the viewport changes height, all elements remain at the same position. I am after a general solution. My approach is to get the computed style for height, width and some fringe ones and set it as !important. This is the code that works on many occasions:
enabledProperties = ["height", "width"];
let allElements = window.document.getElementsByTagName("*");
for (const element of allElements) {
    for (const property of enabledProperties) {
        let elementProperty = window.getComputedStyle(element)[property];
        if (elementProperty.endsWith("px")) {
            element.style.setProperty(property, elementProperty, "important");
        }
    }
}

Now I have come across html where window.getComputedStyle returns invalid results. Namely, it does not include margins. Moreover, elements have collapsed margins, so simply adding margins to the computed height is not fruitful.
Here is a minimal sample of the problem: https://jsfiddle.net/05aukwsL/5/
It appears the problem has something to do with how tables are rendered. It only happens if top element is table. Moreover, table needs to be wrapped in div
html:

         TOP DATA

Bottom element

css:
table {
    margin-top:0;
    margin-bottom:20px;
    border:1px solid green;

}
.bottom-element{
    border:1px solid red;
}

js:
let fixElements = ()=>{
   enabledProperties = ["height", "width"];
   let allElements = window.document.getElementsByTagName("*");
   for (const element of allElements) {
       for (const property of enabledProperties) {
           let elementProperty = window.getComputedStyle(element)[property];
           if (elementProperty.endsWith("px")) {
               element.style.setProperty(property, elementProperty, "important");
           }
       }
   }
}

setTimeout(fixElements,1000);

You can also view the problem in larger context here: https(colon)//allshop(dot)si/izdelek/lovkomar/ (open dev tools and paste the js code).
My question are why does getComputedStyle return invalid results? What function should I use instead? Is there a way to identify if margins were collapsed? If I knew which margin was collapsed (and to what value) I could just use that value for setting height. The end result is to fix all the elements on page, even though not all elements need fixing. The ones that usually cause the most problems are the ones that use vh units when specifying height. getComputedStyle does not differentiate between vh and px. It always returns px and because of that I override all elements. Thank you for your help.


text:
Q: How to pass Terraform variables to .yaml files? I have a terraform module and .yaml docker-compose with service configuration. Yaml have variables such as:
version: '3.2'
services:
  cadvisor:
    image: gcr.io/google-containers/cadvisor:${var.image_version}
    container_name: cadvisor
    volumes:
    - /:/rootfs:ro
    - /var/lib/docker:/var/lib/docker:ro
    mem_limit: ${var.limit}
    mem_reservation: ${var.reservation}
    ports:
    - 8080:8080

and my resource:
resource "local_file" "compose" {
  content = file("${var.compose_path}/docker-compose.yml")
  filename = "${path.module}/foo.bar"
}

The values is declared in my module. I'm going to use this docker-compose.yml in my project e.g. send to remote server and run there. How can I pass variable values from my module to yaml?
I tried to declare values and do some actions with my yaml such as resource "local_file"  to save as file, but .yaml remains without values.

A: You can achieve what you want by using the templatefile built-in function [1]:
resource "local_file" "compose" {
  content = templatefile("${var.compose_path}/docker-compose.yml", {
    image_version = var.image_version
    limit         = var.limit
    reservation   = var.reservation
  })
  filename = "${path.module}/docker-compose.yml"
}

This will also require a minor change to the docker-compose.yml file:
version: '3.2'
services:
  cadvisor:
    image: gcr.io/google-containers/cadvisor:${image_version}
    container_name: cadvisor
    volumes:
    - /:/rootfs:ro
    - /var/lib/docker:/var/lib/docker:ro
    mem_limit: ${limit}
    mem_reservation: ${reservation}
    ports:
    - 8080:8080

[1] https://www.terraform.io/language/functions/templatefile


text:
Q: How to set array value to a field in golang using reflect? I have a Struct with following fields
type Config struct {
        Address[]string
        Name string
}

I am reading the values for this Config from a file in JSON format
{
   "Address": ["xx.xx.xx.xx","xx.xx.xx.xx"],
   "Name":"Name"
}

I have used Reflect to identify the type and set its value to Config.I am able to set the value of Name field using
func (v Value) SetString(x string) which is an inbuilt method in reflect. Is there a way to set []string values directly to a field? Please help.

A: You can use the json package for that (it uses reflect internally):
package main

import (
    "encoding/json"
    "fmt"
)

type Config struct {
    Address []string
    Name    string
}

var someJson = []byte(`{
   "Address": ["xx.xx.xx.xx","xx.xx.xx.xx"],
   "Name":"Name"
}`)

func main() {
    var config Config
    err := json.Unmarshal(someJson, &config)
    if err != nil {
        fmt.Println("error: ", err)
    }
    fmt.Printf("%v", config)
}


text:
Q: Color heatmap in different colors by column in dataframe I have a dataframe which i'm trying to plot in a heatmap.
df = pd.DataFrame(np.random.randint(0,2,size=(10, 5)),
                  columns=['1', '2','3','4','5'])

cluster = [1,1,2,2,3,3,4,4,5,5]
df['cluster'] = cluster

x_axis_labels = []
for i in range(1, 6):
    x_axis_labels.append(i)

fig, ax = plt.subplots(figsize=(4, 10))
from scipy.ndimage import gaussian_filter
np_smooth = gaussian_filter(df, sigma=0.75)
sns.heatmap(np_smooth, cmap="YlGnBu",
            xticklabels=x_axis_labels,
            yticklabels=False, cbar=False)
plt.show()

And this is the output:
1
Each row of the heatmap represents a row in the df. I would like to color each cluster in a different color.
like in this photo:
2
I've added the following code but it gives me an error. Would be happy for some help!
The additional code:
cmaps = {'1': 'Blues_r', '2': 'Greens_r', '3': 'Blues_r', '4': 'Greens_r', '5': 'Blues_r', '6': 'Greens_r', '7': 'Blues_r','0': 'Greens_r'}

for clus, cmap in cmaps.items():
   mask = df.apply(lambda x: x if x['cluster'] == int(clus) else 0, result_type='broadcast',
   axis=1).eq(0)

   sns.heatmap(np_smooth, mask=mask, cmap=cmap, xticklabels=x_axis_labels, yticklabels=False,
   cbar=False, ax=ax)

plt.show()

The error:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\numexpr\necompiler.py in evaluate(ex, local_dict, global_dict, out, order, casting, **kwargs)
    826     try:
--> 827         compiled_ex = _numexpr_cache[numexpr_key]
    828     except KeyError:

KeyError: ('a_value | b_value', (('optimization', 'aggressive'), ('truediv', True)), (('a_value', <class 'numpy.float64'>), ('b_value', <class 'bool'>)))

During handling of the above exception, another exception occurred:

NotImplementedError                       Traceback (most recent call last)

<ipython-input-191-2f3e7e4bc9aa> in cluster_heatmap(df, plot_name, base_num)
     24         ).eq(0)
     25         # plot masked heatmap on reusable ax
---> 26         sns.heatmap(np_smooth, mask=mask, cmap=cmap, ax=ax, xticklabels=x_axis_labels, yticklabels=False, cbar=False)
     27
     28

~\Anaconda3\lib\site-packages\seaborn\_decorators.py in inner_f(*args, **kwargs)
     44             )
     45         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46         return f(**kwargs)
     47     return inner_f
     48

~\Anaconda3\lib\site-packages\seaborn\matrix.py in heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, xticklabels, yticklabels, mask, ax, **kwargs)
    540     plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt,
    541                           annot_kws, cbar, cbar_kws, xticklabels,
--> 542                           yticklabels, mask)
    543
    544     # Add the pcolormesh kwargs here

~\Anaconda3\lib\site-packages\seaborn\matrix.py in __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask)
    107
    108         # Validate the mask and convet to DataFrame
--> 109         mask = _matrix_mask(data, mask)
    110
    111         plot_data = np.ma.masked_where(np.asarray(mask), plot_data)

~\Anaconda3\lib\site-packages\seaborn\matrix.py in _matrix_mask(data, mask)
     86     # This works around an issue where `plt.pcolormesh` doesn't represent
     87     # missing data properly
---> 88     mask = mask | pd.isnull(data)
     89
     90     return mask

~\Anaconda3\lib\site-packages\pandas\core\ops.py in f(self, other, axis, level, fill_value)
   2021             # Another DataFrame
   2022             pass_op = op if should_series_dispatch(self, other, op) else na_op
-> 2023             return self._combine_frame(other, pass_op, fill_value, level)
   2024         elif isinstance(other, ABCSeries):
   2025             # For these values of `axis`, we end up dispatching to Series op,

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _combine_frame(self, other, func, fill_value, level)
   5086         if ops.should_series_dispatch(this, other, func):
   5087             # iterate over columns
-> 5088             return ops.dispatch_to_series(this, other, _arith_op)
   5089         else:
   5090             result = _arith_op(this.values, other.values)

~\Anaconda3\lib\site-packages\pandas\core\ops.py in dispatch_to_series(left, right, func, str_rep, axis)
   1155         raise NotImplementedError(right)
   1156
-> 1157     new_data = expressions.evaluate(column_op, str_rep, left, right)
   1158
   1159     result = left._constructor(new_data, index=left.index, copy=False)

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, use_numexpr, **eval_kwargs)
    206     use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
    207     if use_numexpr:
--> 208         return _evaluate(op, op_str, a, b, **eval_kwargs)
    209     return _evaluate_standard(op, op_str, a, b)
    210

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b, truediv, reversed, **eval_kwargs)
    121
    122     if result is None:
--> 123         result = _evaluate_standard(op, op_str, a, b)
    124
    125     return result

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b, **eval_kwargs)
     66         _store_test_result(False)
     67     with np.errstate(all='ignore'):
---> 68         return op(a, b)
     69
     70

~\Anaconda3\lib\site-packages\pandas\core\ops.py in column_op(a, b)
   1133         def column_op(a, b):
   1134             return {i: func(a.iloc[:, i], b.iloc[:, i])
-> 1135                     for i in range(len(a.columns))}
   1136
   1137     elif isinstance(right, ABCSeries) and axis == "columns":

~\Anaconda3\lib\site-packages\pandas\core\ops.py in <dictcomp>(.0)
   1133         def column_op(a, b):
   1134             return {i: func(a.iloc[:, i], b.iloc[:, i])
-> 1135                     for i in range(len(a.columns))}
   1136
   1137     elif isinstance(right, ABCSeries) and axis == "columns":

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _arith_op(left, right)
   5082             # left._binop(right, func, fill_value=fill_value)
   5083             left, right = ops.fill_binop(left, right, fill_value)
-> 5084             return func(left, right)
   5085
   5086         if ops.should_series_dispatch(this, other, func):

~\Anaconda3\lib\site-packages\pandas\core\ops.py in na_op(x, y)
   1999
   2000         try:
-> 2001             result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs)
   2002         except TypeError:
   2003             result = masked_arith_op(x, y, op)

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, use_numexpr, **eval_kwargs)
    206     use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
    207     if use_numexpr:
--> 208         return _evaluate(op, op_str, a, b, **eval_kwargs)
    209     return _evaluate_standard(op, op_str, a, b)
    210

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b, truediv, reversed, **eval_kwargs)
    112                                              'b_value': b_value},
    113                                  casting='safe', truediv=truediv,
--> 114                                  **eval_kwargs)
    115         except ValueError as detail:
    116             if 'unknown type object' in str(detail):

~\Anaconda3\lib\site-packages\numexpr\necompiler.py in evaluate(ex, local_dict, global_dict, out, order, casting, **kwargs)
    827         compiled_ex = _numexpr_cache[numexpr_key]
    828     except KeyError:
--> 829         compiled_ex = _numexpr_cache[numexpr_key] = NumExpr(ex, signature, **context)
    830     kwargs = {'out': out, 'order': order, 'casting': casting,
    831               'ex_uses_vml': ex_uses_vml}

~\Anaconda3\lib\site-packages\numexpr\necompiler.py in NumExpr(ex, signature, **kwargs)
    624
    625     context = getContext(kwargs, frame_depth=1)
--> 626     threeAddrProgram, inputsig, tempsig, constants, input_names = precompile(ex, signature, context)
    627     program = compileThreeAddrForm(threeAddrProgram)
    628     return interpreter.NumExpr(inputsig.encode('ascii'),

~\Anaconda3\lib\site-packages\numexpr\necompiler.py in precompile(ex, signature, context)
    569         ast = ASTNode('op', value='copy', astKind=ex.astKind, children=(ast,))
    570
--> 571     ast = typeCompileAst(ast)
    572
    573     aliases = collapseDuplicateSubtrees(ast)

~\Anaconda3\lib\site-packages\numexpr\necompiler.py in typeCompileAst(ast)
    212                 raise NotImplementedError(
    213                     "couldn't find matching opcode for '%s'"
--> 214                     % (ast.value + '_' + retsig + basesig))
    215         # First just cast constants, then cast variables if necessary:
    216         for i, (have, want) in enumerate(zip(basesig, sig)):

NotImplementedError: couldn't find matching opcode for 'or_bdb'

A: A dataframe as mask seems to give some errors. You could use mask.values to just grab the values.
The example code below makes the following changes:

*

*the columns of the dataframe are changed from integer to float

*the clusters column is left out for the gaussian_filter and for the mask

*the mask is calculated by repeating the mask value for the clusters column

*the directionary for the colormaps now uses numbers as keys

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, 2, size=(10, 5)).astype(float),
                  columns=['1', '2', '3', '4', '5'])
cluster = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
df['cluster'] = cluster

x_axis_labels = range(1, 6)

fig, ax = plt.subplots(figsize=(4, 10))
from scipy.ndimage import gaussian_filter

np_smooth = gaussian_filter(df[df.columns[:-1]], sigma=0.75)

cmaps = {1: 'Reds_r', 2: 'Greys_r', 3: 'Blues_r', 4: 'Greens_r', 5: 'Purples_r', 6: 'Greens_r', 7: 'Blues_r',
         0: 'Greens_r'}
for clus, cmap in cmaps.items():
     mask = np.repeat((df['cluster'] != int(clus)).values.reshape(-1, 1), len(df.columns) - 1, 1)
     if not mask.all():
          sns.heatmap(np_smooth, mask=mask, cmap=cmap, xticklabels=x_axis_labels, yticklabels=False,
                      cbar=False, ax=ax)
plt.tight_layout()
plt.show()

PS: To have consistent color ranges, you might use vmin=np_smooth.min(), vmax=np_smooth.max() in the calls to  sns.heatmap().


text:
Q: Cast pointer to reference_wrapper to pointer to underlying? Here's my situation:
I'm given data as a pointer say double*.
I want to wrap this in a vector to use a library, and to avoid messing around with pointers.
Not wanting to copy the entire array, I use a vector of reference wrappers. If I then want to get the double* back from said vector after using the library, can I get this by casting the vector.data() function?
For example:
double* arr = new double[10];
vector<reference_wrapper<const double> > vec(arr,arr+10);

//use library in some manner.

//is this allowed? is there a more appropriate way?
//or should I forget using reference_wrappers in this way.
double* res = (double*) vec.data()

A: No, it is not possible.
double and reference_wrapper<const double> are completely unrelated types, there is no way to do this cast.
If you really need to manipulate C-style arrays, you should stick with std::vector<double>, and access the underlying array with the data() member function when needed.

A: No, you can't do that.
You can do this (but it's ugly):
double* arr = new double[10];
std::vector<std::reference_wrapper<double>> vec(arr, arr + 10);

//use library in some manner.

//is this allowed? is there a more appropriate way?
//or should I forget using reference_wrappers in this way.
double* res = &vec[0].operator double &();
assert(res == arr);

I would forget using reference_wrapper like this and instead look at boost range:
http://www.boost.org/doc/libs/1_55_0/libs/range/doc/html/range/reference/utilities/iterator_range.html


text:
Q: TypeError: argument of type 'NoneType' is notiterable I am write a python code to list all the words in a file.
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
word = list()
for line in fh:
    lst = line.split()
    for w in lst :
        if not w in word :
            word = word.append(w)
word = word.sort()
print(word)

Why does it show
> if not w in word :
> TypeError: argument of type 'NoneType' is notiterable

Thanks,
Michael

A: You are overwriting word into a None, as word.append(w) returns None (or to be exact, it does not return anything).
Replace word = word.append(w) with word.append(w)
Edit -
Same issue will happen with your word = word.sort(), should replace it with word.sort().


text:
Q: Should Community's profile page say "Hi, I'm not really a person."? The first few words in Community's profile page are

Hi, I'm not really a person.

Should these be removed?
Arguments I can think of for removing.
It's redundant, the [bot] label is quite visible, and probably can't be easily missed (I don't think it would be affected by banner blindness, though it might be).
Arguments I can think of against removing

*

*Tradition

*The change is too unimportant

Tl;dr
Should the part of communities profile page saying it's a bot be removed, because of the new label that says community is a bot?

A: A mistake that folks make is they take "At Stack Exchange, we hate fun" a little too seriously. Folks want perfect, serious rigid order and that's... boring.
A little frivolity never hurt anyone. Much like how Community has a Not A Robot badge, things like this bring a little levity to the proceedings.
I do realise folks want everything nice and neat and serious... but there's space for things not so.

A: Why...

*

*I do think there are many people on SE that don't know English well, and "bot" could sound misleading for them...

*There is nothing wrong with feeding extra information to users...
One thing I do want to say is that the Community User has the Not A Robot badge, which is quite (very) misleading.


text:
Q: ¿Cómo ejecutar un Asyntask una por una? Busco una vez más de su ayuda,
tengo un determinado número de Asyntask para ejecutar,en este caso son dos diferentes tareas, una es para guardar y la otra para actualizar, el detalle que ocupo es que se ejecuten una por una.
Una muestra del código que utilizo es la siguiente:
    int id = 0;
    int id2 = 0;
    String  mqry = "select * from objeto where UpdateToServer = 1";
    Cursor crp = db.rawQuery(mqry,null);
    if(crp.getCount() > 0){
        while(crp.moveToNext()){
            id = crp.getInt(crp.getColumnIndex("_id"));
            id2 = crp.getInt(crp.getColumnIndex("id2"));
            if(id2 == 0){
                SaveObjeto sObj = new SaveObjetor();
                sObj.execute(id);
            }else {
                UpdateObjeto uProd = new UpdateObjeto();
                uObj.execute(id);
            }
        }
    }

Así es como ejecuto todas las que deseo, en este caso que un campo tenga 1 en base de datos.
Estuve leyendo e investigando un poco y encontré una clase que posiblemente haga lo que deseo pero no la entiendo muy bien
Clase Executor
¿Quien la ha utilizado????

A: En tu caso no serviría un Executor ya que tendrías que envolver cada iteración del loop dentro de una tarea en sí para poder ordenarlo.
Tu caso es en realidad mucho más simple, usando AsyncTask.get() se congela el hilo actual hasta que el AsyncTask devuelva el resultado.
Importante: no llamar esto desde el hilo principal(UI) de la app ya que esto puede bloquearse por varios segundo y causar un ANR.
EDIT: Agrego un ejemplo a pedido de @webserveis, en realidad es muy simple:
new DownloadFilesTask().get(5000, TimeUnit.MILLISECONDS);

va a llamar a mi Asyctask exactamente igual que si llamara
new DownloadFilesTask().execute()

Con la diferencia es que el get va a detener el hilo actual ( en este caso, con un tiempo limite de 5 segundos) hasta que el Task complete su ejecución, en esencia estas convirtiendo la tarea en sincrónica.

A: si buscas que tus Asynctask sean secuenciales lo creo que lo correcto sería usar un único Asynctas o Thread el cual realice las 2 tareas, estas se realizarian secuencialmente.
Comentare algo que puedes ver en la documentacion acerca de Asynctask, cuando se agrego esta clase al SDK inicialmente se ejecutaban en serie en un mismo thread, pero cuando se introdujo el sistema operativo 3.0 Honeycomb se permitia ya el ejecutarse en paralelo.
Este precisamente es un metodo que realizamos para dicha tarea, esto para obligar no importando el sistema operativo se ejecutaran en paralelo>
public static void runParallelAsyncTask(AsyncTask task){
    if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB){
        task.execute();
    }else{
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}

Si deseas que se realicen en serie puedes usar en lugar de THREAD_POOL_EXECUTOR usar SERIAL_EXECUTOR
Para lo que deseas puedes usar el metodo .get() para obligar a detener tu programa hasta que termine la ejecucion del Asynctask, pero esto provocara que se detenga la UI seguramente, considero que seria mejor opcion para lograr que sean secuenciales, tener un unico Asynctask y agregar la ejecucion de las tareas dentro del mismo.


text:
Q: Помогите скрыть элемент

$(document).ready(function() {
  var counts = $('#grid li a').size();
  $('.col-lg-9 p').text('at the moment their ' + counts);
});

$('.col-lg-3 p').click(function(e) {
  e.preventDefault();
  var a = $(this).attr('data-id');
  a = a.substr(1);
  $('#grid li a').each(function() {
    if (!$(this).hasClass(a) && a != 'all')
      $(this).addClass('hide');
    else
      $(this).removeClass('hide');
  });
});

Hello, my works below

<button type="button" class="btn btn-blue">optam</button>

<button type="button" class="btn btn-blue">math</button>

<button type="button" class="btn btn-blue">all</button>

Practical 5

Practical 5

Когда я нажимаю в классе col-lg-3 кнопку math или optam, то пикча не подходящая под фильтр пропадает, но
Practical 5
 остается. Подскажите в чем проблема?

A: К коду, конечно, очень много вопросов - начиная, от использования устаревшего jQuery API (метод size(), например) до не совсем верного кода (например, в e.preventDefault() нет необходимости, когда в данном случае обрабатываешь событие click на элементе p: какое у параграфа поведение по умолчанию для того, чтобы его превентить?)

Но, если отвечать на вопрос, то элемент

Practical 5

не исчезает, потому что он находится не в  элементе, а ты здесь присваиваешь класс a элементу (линке)
$('#grid li a').each(function() {
    if (!$(this).hasClass(a) && a != 'all')
        $(this).addClass('hide');
    else
        $(this).removeClass('hide');
});

Вот изображение исчезает, потому что находится в  элементе

Practical 5

A: Вариант 1:
$('#grid li a').each(function() {
    if (!$(this).hasClass(a) && a != 'all') {
      $(this).addClass('hide').closest("li").find("h2").addClass('hide');
    } else {
      $(this).removeClass('hide').closest("li").find("h2").removeClass('hide');
    }
});

Вариант 2:  используем element + next

при помощи element + next получаем следующий элемент

if(a != 'all')
{
  $('#grid li a, #grid li a + h2').addClass("hide");
  $('#grid li a[class*="'+a+'"], #grid li a[class*="'+a+'"] + h2').removeClass("hide");
}
else{
  $('#grid li a, #grid li a + h2').removeClass("hide");
}

Вариант 3:  используем siblings()

при помощи siblings() получаем всех братьев и сестер в наборе DOM (в родителе).

! Если У Вас будут сторонние строки в
 к которым не должен применяться класс .hide, данное решение не подойдет
if(a != 'all')
{
  $('#grid li a').addClass("hide").siblings().addClass("hide");
  $('#grid li a[class*="'+a+'"').removeClass("hide").siblings().removeClass("hide");
}
else{
  $('#grid li a').removeClass("hide").siblings().removeClass("hide");
}


text:
Q: Apache creates file: how to control permissions My Django app via Apache creates log files: log.txt
The Owner and group of this file is "www-data"
owner rwx
group r
all r

My python app has no read/write permissions to this log file. But I need the python app to have this permissions.
Now it is easy to manually change permissions, but I need the file to have the correct permissions when it is created. How can I do that?
my goal:
add python user to group www-date  (what is the name of the python user?)
and then:
Owner rwx
Group rwx
all r

A: You may use os.chmod() to control the permissions of a given file, after creating the file you can execute:
os.chmod("/path/to/file", 0o775)

The first argument being the path and the second argument is the flag for permission to be granted, you may also access the flags from stat module.