text:
Q: How to realize derived response (XSD)? I am searching for the best solution of my XML schema (XSD).
I have a response:
<xs:element name="exampleCatalogResponse">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="meta" type="tns:metaType" />
            <xs:element name="data" type="tns:defaultDataType" />
        </xs:sequence>
    </xs:complexType>
</xs:element>

...the defaultDatatype:
<xs:complexType name="defaultDataType">
    <xs:sequence>
        <xs:element name="catalog">
            <xs:complexType>
                <xs:sequence maxOccurs="unbounded">
                    <xs:element name="catalogItem" type="tns:catalogItem" />
                </xs:sequence>
            </xs:complexType>
            <xs:unique name="itemIdConstraint">
                <xs:selector xpath="tns:catalogItem" />
                <xs:field xpath="tns:id" />
            </xs:unique>
        </xs:element>
    </xs:sequence>
</xs:complexType>

...and the catalogItem:
<xs:complexType name="catalogItem">
    <xs:sequence>
        <xs:element name="id" type="xs:nonNegativeInteger" />
    </xs:sequence>
</xs:complexType>

...but now there is a special item which specialize catalogItem:
<xs:complexType name="specialItem">
    <xs:complexContent>
        <xs:extension base="tns:catalogItem">
            <xs:sequence>
                <xs:element name="code" type="xs:string" />
            </xs:sequence>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>

Now I need an specialized Response for my specialItem for answering the request which expects this specialItem.
How can I realise this, without writing another defaultDataType where only the type of catalogItem changes to tns:specialItem?

A: I don't think you can enforce co-occurance constraints like that in XSD. In the spirit of a puzzle solution, here's an awkward way to make copies with the change you want, without manually "writing another defaultDataType":

*

*define the above complexTypes in a schema document without a namespace.

*<include> it in a second schema document, that does have a namespace - this gives it that namespace.  We can do this in many schema documents, each time getting a copy in that distinct namespace.

*in each of these schema documents, extend catalogItem, so that every extension will be in its own namespace.

*in a final schema document, include all the above, and make them substitutable - so they can all be used as a response.  (alternatively, you could make them all extend some other Response element in yet-another-schema).

*NOTE: You'll need a different way to enforce the itemIdConstraint constraint, that goes across namespaces. Offhand, I don't know if this is possible.
This works by making a distinct copy of defaultDataType for each one, and so won't work if you actually want them to all use the same defaultDataType.   Like I said, it's awkward, but it's the only way I can see to do what you want. I offer it as a puzzle solution, rather than a practical one!

A: Thank you for your tipps 13ren,
I used the Subsumption Feature. So the default catalogItem is used everywhere also for the unique expression. And now if i use this in xml i can specify this via type.
  <tns:catalogItem xsi:type="tns:specialItem">
    <tns:id>0</tns:id>
    <tns:code>tns:code</tns:code>
  </tns:catalogItem>
  <tns:catalogItem xsi:type="tns:specialItem">
    <tns:id>1</tns:id>
    <tns:code>tns:code</tns:code>
  </tns:catalogItem>
  <tns:catalogItem>
    <tns:id>2</tns:id>
    <tns:code>tns:code</tns:code>
  </tns:catalogItem>

So the last item is the default, and the two above are specialized items. this works very well for me.


text:
Q: Dynamically grabbing Firebase data inside nested ng-repeat for whatever object I am on I am creating a blog feature on a website I am building, I created a basic template that the admin must use to create their posting. The issue I am having is I cannot figure out how to dynamically grab the list items inside each blog posting and display them inside of another ng-repeat. here is my sample JSON inside Firebase
JSON
"pPosts": {
        "2015Newsletter": {
            "title": "2015 Newsletter",
            "subTitle": "Bringing Hope to Families in Iquitos, Peru",
            "datePosted": "6/21/16",
            "paragraph1": "random text.",
            "listTitle1": "Other Highlights of 2015 Trip",
            "subListTitle1": "",
            "listItem1s": {
                "list1Item1": "Meen for 2016!",
                "list1Item2": "Buonsored children",
                "list1Item3": "Worector, Violeta",
                "list1Item4": "Gi needy families",
                "list1Item5": "Prfamily business",
                "list1Item6": "Pu a family bakery business",
                "list1Item7": "Suing party",
                "list1Item8": "Tehildren",
                "list1Item9": "Scd Animal Rescue Center.",
                "list1Item10": "Serusalen School.",
                "list1Item11": "Adren.",
                "list1Item12": "",
                "list1Item13": "",
                "list1Item14": "",
                "list1Item15": "",
                "list1Item16": "",
                "list1Item17": "",
                "list1Item18": "",
                "list1Item19": "",
                "list1Item20": ""
            },
            "listTitle2": "Be an active pa",

I am providing support for up to 20 list items, and don't want to have to specify the child("2015Newsletter") in my controller, as there will be multiple postings and I don't want to have to write code every time an admin creates a post. Here is my controller
Javascript Controller
bridgeTheGapControllers.controller('presidentsPageCtrl', function($scope, $firebaseArray, $firebaseObject) {
    var ref = new Firebase("firebaseUrl");
    //first layer post info
    $scope.postsNum = $firebaseArray(ref.child('pPosts'));
    //THIS DOES NOT WORK
    $scope.listItem1s = $firebaseArray(ref.child('pPosts').child('listItem1s'));

});

HTML

{{ post.title }}

{{ post.subTitle }}

                                 {{ post.postedBy }}
                                 {{ post.category1 }} {{ post.category2 }} {{ post.category3 }}
                                 {{ post.datePosted }}

{{ post.paragraph1 }}

{{ post.listTitle1 }}

{{ listItem.listItem}}

Maybe I am thinking of this completely wrong, but it seems there would be a way to do something in my controller like this $scope.listItem1s = $firebaseArray(ref.child('pPosts').child(INDEX FOR WHATEVER POST IM IN).child('listItem1s');

A: You won't need that additional $firebaseArray.
Just make sure you do the logic in your inner ng-repeat.

Controller
bridgeTheGapControllers.controller('presidentsPageCtrl', function($scope, $firebaseArray, $firebaseObject) {
    var ref = new Firebase("firebaseUrl");
    //first layer post info
    $scope.postsNum = $firebaseArray(ref.child('pPosts'));
});

HTML

{{ post.title }}

{{ post.subTitle }}

             {{ post.postedBy }}
             {{ post.category1 }} {{ post.category2 }} {{ post.category3 }}
             {{ post.datePosted }}

{{ post.paragraph1 }}

{{ post.listTitle1 }}

{{postsNum.post.listItem1s.listItem}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does c# Aggregate evaluate returns an incorrect value? List<decimal>scontiList = new List<decimal>();
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
scontiList.Add((decimal)50.0m);
decimal cento = (decimal)100.0d;
decimal ris = scontiList.Aggregate((decimal)0.0m, (a, b) =(decimal)((decimal)1 - ((decimal)a / (decimal)cento)) * (decimal)((decimal)1 - ((decimal)b / (decimal)cento)));

->    ris 0.4975125
Why is in that case ris = 0,4975125 ?
correct is 0.125

A: Aggregate starts with a seed value, runs the function you specify and stores the result back into the accumulator. It then moves on, repeating this loop
Your seed is 0 (the value given to current_value for the first iteration)
Your operation is (1 - current_value/100) * (1 - next_value/100)
Your values are all 50, hence your operation is really: curr = (1 - curr / 0.5) * 0.5
The progression is thus:
Seed: (1 - 0/100) * 0.5 = 0.5
Step 1: (1 - 0.5/100) * 0.5 = 0.4975
Step 2: (1 - 0.4975/100) * 0.5 = 0.4975125

As you can see it's settling on 0.4975. It will never get to 0.125. That decimal number will get longer and longer (more digits), but it'll always be about 0.4975


text:
Q: How many rows of data is too many rows of data? Is there some hard and fast rule about how big is too big for a SQL table?
We are storing SCORM tracking data in a name/value pair format and there could be anywhere from 4-12 rows per user per course, down the road is this going to be a bad thing since there are hundreds of courses and thousands of users?

A: 100 (courses) * 1000 (users) * 10 (records) is only a million.  That's the low end, but a decent database ought to handle it okay.
What sounds iffy are Name/Value pairs.  That will limit your ability to correctly index things, which will be critical to good performance.

A: No hard and fast rule, but there is a hard and fast way to get a number.
Write a program to populate your table with dummy data roughly approximating the expected form of the actual data (e.g. similar regularity, characters, patterns, etc.)  Run performance tests against it using actual queries with the dummy data, gradually increasing the number of rows in the table, perhaps by steps of 1000 or 10000 rows.
At the cusp of when the query performance (e.g. queries completed per second) becomes unacceptable, you'll have your "too big" number of rows.

A: I once worked on a web form system with over 300 million rows in their name/value pair table.  Many of the forms had over 300 rows per form submission.  Performance wasn't too bad actually, but it was a total PITA to query from!  My sql writing ability definitely improved over the life of this gig.
But IMHO, if you have any say get rid of it in favor of a standard normalized table.

A: Not really. It all depends on your business needs, and you'll have to buy the product that supports your estimated row count.

A: No, there isn't really any hard rule about how many rows you can have in a table, it depends a lot on how much data there is in the rows, and how well the data can be indexed.
A quick estimate on the figures that you stated gives something like tens of millions of rows. That's certainly not too much, but it's enough that it could be a problem if you aren't a bit careful.
Perhaps the table could be normalized? Does the same names occur a lot, so that you could put the names in a separate table and use the id in the table?

A: The magic number is billions.  Until you get to billions of rows of data, you're not talking about very much data at all.
Do the math.
4-12 rows per user per course,... hundreds of courses and thousands of users?
400,000 to 1,200,000 rows.  Let's assume 1000 bytes per row.
That's 400Mb to 1.2Gb of data.  You can buy 100Gb drives for $299 at the Apple store.  You can easily spend more than $299 of billable time sweating over details that don't much matter any more.
Until you get to 1Tb of data (1,000 Gb), you're not talking about much data at all.

A: I personally have had tables in production with 50 million rows, and this is small compared with I have heard. You might need to optimize your structure with partitioning but until you test your system in your environment you shouldn't waste time doing that. What you described is pretty small IMHO
I should add I was using SQL Server 2000 & 2005, each DBMS has its own sizing limitations.

A: I don't think there is really a limit here, but drive space. BUT PLEASE add good indexes while its small, becuase when the table is huge indexes will take a lot longer to add. Plus if you have bad indexes queries will slow down as it gorws and people will complain when there is really nothing wrong, but a crappy to no index.

A: I've worked on databases where we tried to create tables with 2B rows of data - that doesn't work, we got to 500M and re-designed. One of the biggest gotchas of working with such large table was the time taken to do deletions - I often see the approach where old records are archived and then deleted from the main table. If the table is big enough that deletion will run for many hours as the indexes are rebuilt.
Not sure where the cut off is but gut feel indicates a table > 10M rows is probably too big. Our approach was to partition data by date, so we ended up with a table for a week of data, and another summary table for months, and another summary for years - very common in DataWarehousing. BTW this was on SQL 7.0, interested to know if the DB's are better at this type of stuff yet?

A: Your question prompts more questions than answers.

*

*what database engine are you using?  Its hard to fashion you a good answer without this.

*what is the table structure?  Depending on your datatype, how your table will layout on disk will depend on this.

*why not store one record per user/course?  As you are storing SCORM data, I assume this means you are storing standard SCORM data like completion, success, attempts, totaltime, etc.  There's no need to create multiple rows for this.

I've built a few databases storing SCORM data, and I've never had to go with a tag/value system like you suggest.
One thing you want to remember though is its not the # of rows in the table, its the SIZE (in bytes) of the table.  Simply:
table size = row size (avg) * number of rows
The question to ask is, "how big a table is too big"?


text:
Q: Fast method of reading binary file contents not working correctly I'm creating an Android app that needs to read a ~5 mb binary file in order to use the part of speech tagger from Apache OpenNLP. I tried a fairly circuitous route to read the file quickly, using a ByteBuffer and a custom ByteBufferInputStream class. I thought I was doing it correctly, but when I checked the POSModel that is returned by the method it turns out to be 'null'. What is supposed to happen is that a ByteBuffer reads the info from the binary file, and then gives that as an InputStream to the POSModel constructor.
Here's the code for getting the part of speech model from the binary file:
public POSModel setupPOSModel() {
        ByteBufferInputStream modelIn = null;
        POSModel model = null;
        try {
            InputStream stream = getResources().openRawResource(R.raw.en_pos_maxent);
            byte[] b = IOUtils.toByteArray(stream);
            ByteBuffer buf = ByteBuffer.wrap(b);

            modelIn = new ByteBufferInputStream(buf);
            model = new POSModel(modelIn);
        } catch (IOException e) {
            // Model loading failed, handle the error
            e.printStackTrace();
        } finally {
            if (modelIn != null) {
                try {
                    modelIn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//at this point 'model' is null
        System.out.println("POS MODEL: " + model);
        return model;
    }

And here's the code for the ByteBufferInputStream, which I got from another Stack Overflow question:
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class ByteBufferInputStream extends InputStream {

    private int bbisInitPos;
    private int bbisLimit;
    private ByteBuffer bbisBuffer;

    public ByteBufferInputStream(ByteBuffer buffer) {
        this(buffer, buffer.limit() - buffer.position());
    }

    public ByteBufferInputStream(ByteBuffer buffer, int limit) {
        bbisBuffer = buffer;
        bbisLimit = limit;
        bbisInitPos = bbisBuffer.position();
    }

    @Override
    public int read() throws IOException {
        if (bbisBuffer.position() - bbisInitPos > bbisLimit)
            return -1;
        return bbisBuffer.get();
    }
}

Now, my final goal is simply to read "en_pos_maxent" binary file as fast as possible (currently, using a regular InputStream, it takes about 20 seconds), so if there is a better way than my roundabout way to get the file contents quickly using a ByteBuffer then that alternate method could work too.
Update:
Here's the stack trace for the exception thrown by the method:
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err: java.util.zip.ZipException: CRC mismatch
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at java.util.zip.ZipInputStream.readAndVerifyDataDescriptor(ZipInputStream.java:215)
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:164)
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at opennlp.tools.util.model.BaseModel.loadModel(BaseModel.java:245)
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:179)
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at opennlp.tools.postag.POSModel.<init>(POSModel.java:105)
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at com.newssummary.MainActivity$override.setupPOSModel(MainActivity.java:245)
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at com.newssummary.MainActivity$override.access$dispatch(MainActivity.java)
08-08 14:59:38.220 2735-3351/com.newssummary W/System.err:     at com.newssummary.MainActivity.setupPOSModel(MainActivity.java:0)
08-08 14:59:38.221 2735-3351/com.newssummary W/System.err:     at com.newssummary.MainActivity$4.doAsync(MainActivity.java:190)
08-08 14:59:38.221 2735-3351/com.newssummary W/System.err:     at com.newssummary.MainActivity$4.doAsync(MainActivity.java:182)
08-08 14:59:38.221 2735-3351/com.newssummary W/System.err:     at com.arasthel.asyncjob.AsyncJob$4.run(AsyncJob.java:91)
08-08 14:59:38.221 2735-3351/com.newssummary W/System.err:     at java.lang.Thread.run(Thread.java:818)

A: Without you going into greater detail about the exceptions thrown by the POSModel initialization, I can only suggest a bit of simplification here to avoid ByteBuffer entirely. Consider using a ByteArrayInputStream as follows:
import java.io.ByteArrayInputStream;

final byte[] data = IOUtils.toByteArray(stream);
final InputStream memstream = new ByteArrayInputStream(data);

model = new POSModel(memstream);

Alternatively, consider using a BufferedInputStream instead of manually reading the entire resource into a large buffer first.

The exception trace you've shared suggests there's some corruption occurring to the model data, either in the actual resource data or as a side effect of IOUtils.toByteArray or your ByteBufferInputStream implementation. Try using ByteArrayInputStream and let us know how it goes.


text:
Q: MVC 5 multiple file upload uploads same file several times I have built a website using asp.net 4.5 and MVC 5.
In one of my views I want to upload multiple files.
With my code below, the first fileis collected and saved, but it is saved as many times as the number of files I try to upload.
For example:
I choose the files pic1.jpg and pic2.jpg with the file uploader. This results in the file pic1.jpg being saved twice.
While debugging I see that the Request.Files[file]; code returns the same file each time. It seems that I get the same file uploader twice, and that only the first file is selected.
How do I alter my code to fetch all files selected via the uploader?
Controller
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ProductViewModel product)
        {
            ...

            foreach (string file in Request.Files)
            {
                var hpf = Request.Files[file];
                if (hpf != null && hpf.ContentLength > 0)
                {
                    var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName));
                    hpf.SaveAs(savedFileName);
                }
            }

            ...

            return RedirectToAction<ProductController>(x => x.Index());
        }

View
@model EVRY.OrderCapture.Administration.ViewModels.ProductViewModel

@Resources.Resources.Create

@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

        ...

            Filename:

                <input type="file" name="files" id="fileUpload" multiple />

                <input type="submit" value="@Resources.Resources.Create" class="btn btn-default" />

}

A: I found the answer to this myself.
I had to select on index instead of name.
for (var i = 0; i < Request.Files.Count; i++)
        {
            var hpf = Request.Files[i];
            if (hpf != null && hpf.ContentLength > 0)
            {
                var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName));
                hpf.SaveAs(savedFileName);
            }
        }


text:
Q: mysql select fetch from 2 tables TABLE USER

USERID  NAMES  EMAIL
1       J      TES@ADM.COM1
2       K      TES@ADM.COM2
3       L      TES@ADM.COM3
4       M      TES@ADM.COM4

TABLE COMUNITY

COMUNITY_ID  USERID  FAN_ID
1            1       TES@ADM.COM3
2            4       TES@ADM.COM2
3            3       TES@ADM.COM4
4            2       TES@ADM.COM1

my userid is 1 - (name = j). how can i select these emails where my userid equal is 1 and these who have my userid (1) to their fan_id column
its like i want to get these emails i have where my userid and these who have mine

A: well is pretty simple :
SELECT
      c.fan_Id
FROM
      USERS u
      INNER JOIN COMUNITY c on u.USERID = c.USERID
WHERE
      u.UserId = 1


text:
Q: How to replace the company name in the template headers in Xcode? When Xcode creates a new file, there's always something like this in the header:
//  Copyright 2009 __MyCompanyName__. All rights reserved.

How can I change that?

A: Xcode will try to pull this information from your entry in the system address book - if you can't modify it there, try using this command to override:
defaults write com.apple.xcode PBXCustomTemplateMacroDefinitions '{ ORGANIZATIONNAME = "ORGNAME";}'

A: As a follow-up to the answer above, for documentation of that and many other preferences see the Xcode defaults reference

A: You can change it in Xcode project File. This is my image for tutorial.

A: As of xcode 3, it will use the "company" field from your Address Book card if the "PBXCustomTemplateMacroDefinitions" key is missing from com.apple.Xcode.plist.

A: defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions ' { "ORGANIZATIONNAME" = "javacom"; } '
Entered in Terminal.


text:
Q: How to fix namespace issue causing fatal error in wordpress theme I am in the middle of a WP theme migration and running into this error.
Fatal error: Uncaught Error: Class 'Reach\App\Core\Init' not found in /chroot/home/ac963a12/fbf88a9b79.nxcli.net/html/wp-content/themes/reach.service-out-quick/functions.php:17
This is the code in that file:
<?php
/**
 * Functions and definitions
 *
 * @package Reach
 */

use Reach\App\Core\Init;
use Reach_Service_Out_Quick\App\Scripts;
use Reach_Service_Out_Quick\App\Fields\Groups\FieldGroupServices;
use Reach_Service_Out_Quick\App\Theme\ThemeStyles;

/**
 * Theme Setup
 */
add_action( 'after_setup_theme', function () {
    ( new Init() )
        ->add( new Scripts() )
        ->add( new FieldGroupServices() )
        ->add( new ThemeStyles() )
        ->initialize();
} );

It cannot find the Init class.  I am totally new to composer, am I missing a step?  The parent theme is another directory, I assume that is what is being referenced.


text:
Q: How to map identical items in two dictionaries and produce a list of values of their corresponding keys My goal is to map the small dictionary to the large one and return a list of values in the large dictionary that bears corresponding keys to the small dictionary.
x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13}
y={'red':2, 'blue':3, 'yellow':1}

My code keeps giving me a list of the full values of large dictionary.
for b in x.keys():
    if b in y.keys():
        k=y.values()
print k

output: [0.35, 0.22, 0.13, 0.05, 0.25]

Desired output:
[0.25,0.13,0.05]

Any suggestions?
Thanks.

A: Something like this? I assume that the order does not matter since these are dictionaries. Also, assuming that since you seem to be iterating over x.keys(), then, there may be some values in y that are not present in x and you don't want them mapped.
>>> x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13}
>>> y={'red':2, 'blue':3, 'yellow':1}
>>> [val for elem, val in x.items() if elem in y]
[0.13, 0.05, 0.25]

If there are no values in y that are not in x, then you could simply iterate over the y dictionary.
>>> [x[key] for key in y]
[0.13, 0.05, 0.25]

P.S. - The problem in your code is that everytime you find a match, you assign the whole list of y.values() to k, hence ending up with a complete list of values. You could modify your code to look something like this
>>> k = []
>>> for b in x.keys():
    if b in y.keys():
        k.append(x[b])

>>> k
[0.13, 0.05, 0.25]

Although, iterating over the dictionary gives a similar result, like follows
>>> for b in x:
    if b in y:
        k.append(x[b])

>>> k
[0.13, 0.05, 0.25]

A: k = [x[key] for key in y.keys()]

A: The issue with your code is, you are assigning y.values() to k. So your k is nothing but the list of values of dict y. You can modify your code like this to make it work:
k = []
for b in x.keys():
    if b in y.keys():
        k.append(x[b])
print k

You can also use List comprehension:
>>> x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13}
>>> y={'red':2, 'blue':3, 'yellow':1}

>>> [x[key] for key in y]
[0.13, 0.05, 0.25]

A: I would think about this as the intersection of two sets, then pass the subset to map all of the corresponding values. This way it would be much easier to understand than list comprehension.
>>> map(x.get, set(x) & set(y))
>>> [0.13, 0.05, 0.25]

Of course you can do the same with list comprehension:
>>> [x.get(i) for i in set(x) & set(y)]
>>> [0.13, 0.05, 0.25]


text:
Q: Get the mode and its frequency in a factor variable when there is a tie I am looking for the most frequent values (character strings) and its frequency.
The intended results is a dataframe with three columns:
char: the names of the original columns
mode: the most frequent value in each char
freq: the frequency of the modes

When there is a tie in frequencies, I want to put all of the qualified values in one cell, separated by a comma. -- Or is there any better representation?
Questions: I don't know how to deal with a tie.
I have used the table() function to get the frequency tables of each column.
clean <- read.xlsx("test.xlsx", sheet = "clean") %>% as_tibble()
freqtb <- apply(clean, 2, table)

Here is the second table I got in freqtb:
$休12
个 休 天 饿
1 33  2  1

Then I looped through the tables:
freq <- vector()
mode <- vector()
for (tb in freqtb) {

    max = max(tb)
    name = names(tb)[tb==max]

    freq <- append(freq, max)
    mode <- append(mode, name)
}
results <- data.frame(char = names(freqtb), freq = freq, mode=mode)

The mode has a greater length than other vectors, and it cannot attached to results. I bet it is due to ties.
How can can get the same length for this "mode" variable?

A: You can make some small modifications to the code here to get a Mode function. Then Map over your data frame and rbind the results together
options(stringsAsFactors = F)
set.seed(2)

df.in <-
  data.frame(
    a = sample(letters[1:3], 10, T),
    b = sample(1:3, 10, T),
    c = rep(1:2, 5))

Mode <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux))
  ind <- which(tab == max(tab))
  data.frame(char = ux[ind], freq = tab[ind])
}

do.call(rbind, lapply(df.in, Mode))
#     char freq
# a      c    4
# b      1    4
# c.1    1    5
# c.2    2    5


text:
Q: DeviceMotionEvent Request Permission with Typescript Implementing a gyroscope permission request, but i get a typescript error on requestPermission
My code:
if (typeof (DeviceMotionEvent) !== 'undefined' && typeof (DeviceMotionEvent.requestPermission) === 'function') {
        return DeviceMotionEvent.requestPermission()
            .then((response: string) => response === 'granted');
}

TS2339: Property 'requestPermission' does not exist on type '{ new (type: string, eventInitDict?:
DeviceMotionEventInit): DeviceMotionEvent; prototype: DeviceMotionEvent; }'.

Struggling a bit with this one. i tried casting request permission like this (DeviceMotionEvent.requestPermission() as any) but it stays the same. Since it's not a module i cannot just do yarn add @types/...

A: Please try to avoid casting types to any, since its bad and instead try to narrow the type.
Extend native Web API DeviceOrientationEvent event for iOS devices:
interface DeviceOrientationEventiOS extends DeviceOrientationEvent {
  requestPermission?: () => Promise<'granted' | 'denied'>;
}

const requestPermission = (DeviceOrientationEvent as unknown as DeviceOrientationEventiOS).requestPermission;
const iOS = typeof requestPermission === 'function';
if (iOS) {
    const response = await requestPermission();
    if (response === 'granted') {
      // execute
    }
}

A: You need to cast the Object, not the function, try this:
(DeviceMotionEvent as any).requestPermission()


text:
Q: Can we use class variable's value to a new variable using $this Can we use class variable's value to a new variable name using $this without assigning class variable's value in any other variable?
Example:
public $classVariable = 'thisIsValue';

$classVariableValue = $this->classVariable;
$$classVariableValue  = 'some value';
echo $thisIsValue; // output: some value

Is there any way to assign value from $this object directly?

A: Yes you can. Just use curly brackets (braces?) in this case
${$this->classVariable} = 'some value';

I've testet this with PHP 5.5.23


text:
Q: Prove that $\mathscr F$ and $\mathscr G$ are indp iff $E[X_G X_F] = E[X_G] E[X_F]$. Do we need boundedness?
Prove that $\mathscr F$ and $\mathscr G$ are independent iff $\forall$
   bounded $X_F \in m\mathscr F$ and $\forall$ bounded $X_G \in m\mathscr
 G$,
$E[X_G X_F] = E[X_G] E[X_F]$

(Hope my iff statement is right)

*

*Why is boundedness needed? Why not just integrability?

*What I tried:
'only if'
If $\mathscr F$ and $\mathscr G$ are independent, then $\sigma(X_F)$ and $\sigma(X_G)$ are independent. Then we have $E[X_G X_F] = E[X_G] E[X_F]$. I don't see how integrability doesn't work there. (*)
'if'
Choose $X_F = 1_F, X_G = 1_G \forall F \in \mathscr F, \forall G \in \mathscr G$. Then we have
$$P(F \cap G) = P(F)P(G), \forall F \in \mathscr F, \forall G \in \mathscr G \ QED$$
Afaik, $1_F$ and $1_G$ are integrable $\forall F \in \mathscr F, \forall G \in \mathscr G$
Is that right? If not, how else can I approach this?

(*) Class notes

A: Yeah, your proof is correct. Regarding your first question concerning integrability: If you prefer, you can restate the result as follows.

The following statements are equivalent:

*

*$\mathcal{F}$ and $\mathcal{G}$ are independent.

*For all bounded $X_F  \in m \mathcal{F}$ and bounded $X_G \in m \mathcal{G}$, it holds that $\mathbb{E}(X_G X_F ) = \mathbb{E}(X_G) \mathbb{E}(X_F)$.

*For all $X_F  \in L^1(\mathcal{F})$ and $X_G \in L^1(\mathcal{G})$ such that $X_F \cdot X_G \in L^1$ it holds that $\mathbb{E}(X_G X_F ) = \mathbb{E}(X_G) \mathbb{E}(X_F)$

The "only if" of your proof shows "(1) $\implies$ (3)" and the "if"-part proves  "$(2) \implies (1)$". The remaining implication, i.e. "$(3) \implies (2)$", is obvious (since any bounded random variable is integrable).


text:
Q: Multiple series from JSON Highstock I have a problem with my HighStock, I need another series from JSON.
My code in get_json.php
include('config.php');

$cp = $_REQUEST["c_prot"];

$r=("SELECT * FROM data WHERE cp='$cp'");
$result=mysql_query($r);

while($row = mysql_fetch_array($result)){
    $date= strtotime($row['cas'])*1000;  // timestamp
    $values=hexdec($row['data']);        // series1
    $val=hexdec($row['src']);            // series2

    $array[]=array($date, $values,$val);  //output array
}
echo json_encode($array);

JSON output is in correct format: [1364852734000, 557, 2884],....
But problem is, that I didn't find how to add second series from JSON to Highstock code
I would like to display in chart x-axis: timestamp
                                 y-axis:  series1->data
                                          series2->src
chart now displays only on x-axis timestamp and on y-axis data...but series2 doesn't work:/
High Stock code:

A: In you script:
$array = [];
while($row = mysql_fetch_array($result)){
    $date= strtotime($row['cas'])*1000;  // timestamp
    $values=hexdec($row['data']);        // series1
    $val=hexdec($row['src']);            // series2

    $array[0][]=array($date, $values);  //output array
    $array[1][]=array($date ,$val);
}

You need paste values to appropriate series index. In other words you can prepare your $array() and add point to one of series. To be honest I have no data so It is only concept.


text:
Q: Adding a vector to another vector without a loop I have two Javascript vectors, a and b, of the same length. I want to add b to a. The obvious way is:
for (i=0; i<a.length; ++i)
    a[i] += b[i]

but this requires a loop. I can do:
a.forEach(function(item,index) {
   a[index] += b[index]
})

but this is cumbersome - it requires an unneeded parameter "item". Is there a shorter option? Maybe using some external library?

A: There is no built-in JS function to do this without looping.  Further any library that implements this is going to use looping to do it also.
So, write yourself a short utility function and then just call that function whenever you want to do this.  There's going to be looping somewhere in order to implement this as it is not a native JS feature.  If you want to "hide" the looping, then just put it in a utility function and just call the function when you need it.
// returns a new array that is the sum of the two vector arrays
function addVectors(a, b) {
   return a.map(function(item, index) {
       return item += b[index];
   });
}

Or, if you want one array modified in place:
// add one vector to another, modifying the first one
function addToVector(a, b) {
    a.forEach(function(item, index) {
        a[index] += b[index];
    });
    return a;
}

Or, if the unused item argument bothers you for some reason:
// add one vector to another, modifying the first one
function addToVector(a, b) {
    for (var i = 0; i < a.length; i++) {
        a[i] += b[i];
    }
    return a;
}

Note, all of these functions assume a and b are the same length.  You would have to specify what you want the behavior to be if they end up not being the same length and you want to check for that.  You could throw an exception, just add the parts in common, etc...
For example:
// returns a new array that is the sum of the two vector arrays
function addVectors(a, b) {
   if (a.length !== b.length) {
       throw new Error("Vector arrays must be the same length to add them");
   }
   return a.map(function(item, index) {
       return item += b[index];
   });
}

A: Are you sure you want to do it without the loop? Ok well:
a.forEach(function(currentElement, Index){
    b[Index] += currentElement;
});


text:
Q: What does "lemon on" mean in this context? What does the phrase lemon on mean in this context? Is it an idiom? What is its correct usage?
Excerpt from where I read this phrase:

... Hold on, for this deal, one that does not exist anywhere outside a
  very fertile imagination, could actually be a lemon on at least five
  counts.  These are the lures that should alert you and beg a recheck before you book the deal.

Source: How to Avoid Common Travel Traps

A: The words lemon on don't really constitute a phrase. Here, the word lemon means something that is bad or defective. The prepositional phrase "on at least five counts" means that there are at least five reasons. This usage is from legalese where each individual charge against a person in called a count.
So the original statement

for this deal ... could actually be a lemon on at least five counts.

Can be restated as

for this deal ... could actually be defective for at least five reasons.

A: One of the possible meaning of lemon (noun) is:

(informal) a person or thing, esp. an automobile, regarded as unsatisfactory, disappointing, or feeble.

A: I don't think 'lemon on' is a phrase here. The sentence should read as:

could actually be a lemon / on at least five counts

and the meaning of 'lemon' here is as F'x has said.


text:
Q: CSS center display inline block? I have a working code here: http://jsfiddle.net/WVm5d/ (you might need to make the result window bigger to see the align center effect)
Question
The code works fine but I don't like to have display: table;. It's the only way I could make the wrap-class align center. I think it would be better if there was a way to use display: block; or display: inline-block;. Is it possible to solve the align center another way?
Adding a fixed with to the container is not an option for me.
I will also paste my code here if the JS Fiddle link gets broken in the future:

body {
    background: #bbb;
}

.wrap {
    background: #aaa;
    margin: 0 auto;
    display: table;
    overflow: hidden;
}

.sidebar {
    width: 200px;
    float: left;
    background: #eee;
}

.container {
    margin: 0 auto;
    background: #ddd;
    display: block;
    float: left;
    padding: 5px;
}

.box {
    background: #eee;
    border: 1px solid #ccc;
    padding: 10px;
    margin: 5px;
    float: left;
}

.box:nth-child(3n+1) {
    clear: left;
}

        Sidebar

            Height1

            Height2

            Height2

            Height3

            Height3

            Height3

            Height1

            Height2

            Height2

            Height3

            Height3

            Height3

        Sidebar

A: If you have a
 with text-align:center;, then any text inside it will be centered with respect to the width of that container element. inline-block elements are treated as text for this purpose, so they will also be centered.

A: Try this. I added text-align: center to body and display:inline-block to wrap, and then removed your display: table
body {
    background: #bbb;
    text-align: center;
}

.wrap {
    background: #aaa;
    margin: 0 auto;
    display: inline-block;
    overflow: hidden;
}

A: This will horizontally center an inline-block element without needing to modify its parent's styles:
  display: inline-block;
  position: relative;
  /* Move the element to the right by 50% of the container's width */
  left: 50%;
  /* Calculates 50% of the element's width, and moves it by that */
  /* amount across the X-axis to the left */
  transform: translateX(-50%);

A: You can also do this with positioning, set parent div to relative and child div to absolute.
.wrapper {
      position: relative;
  }
.childDiv {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
  }

A: The accepted solution wouldn't work for me as I need a child element with display: inline-block to be both horizontally and vertically centered within a 100% width parent.
I used Flexbox's justify-content and align-items properties, which respectively allow you to center elements horizontally and vertically. By setting both to center on the parent, the child element (or even multiple elements!) will be perfectly in the middle.
This solution does not require fixed width, which would have been unsuitable for me as my button's text will change.
Here is a CodePen demo and a snippet of the relevant code below:

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

  Button

A: You don't need to use "display: table". The reason your margin: 0 auto centering attempt doesn't work is because you didn't specify a width.
This will work just fine:
.wrap {
    background: #aaa;
    margin: 0 auto;
    width: some width in pixels since it's the container;
}

You don't need to specify display: block since that div will be block by default. You can also probably lose the overflow: hidden.

A: Great article i found what worked best for me was to add a % to the size
.wrap {
margin-top:5%;
margin-bottom:5%;
height:100%;
display:block;}

A: I just changed 2 parameters:
.wrap {
    display: block;
    width:661px;
}
Live Demo

A: Just use:
line-height:50px
Replace "50px" with the same height as your div.


text:
Q: Criar um Download de acordo com id do elemento eu criei um sistema que faz o upload de vários arquivos, porém esbarrei no seguinte problema: eu preciso criar uma forma de realizar o download de acordo com o id do elemento no banco. Gostaria de saber se alguém tem uma ideia que eu possa aproveitar para fazer essa função. Eu criei um metodo no meu controller, porem não funcionou como eu queria.
segue o metodo que eu criei:
@RequestMapping(value = "/download/{file_name}", method = RequestMethod.GET)
public ModelAndView downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response){

    Path arquivo = Paths.get(fileName + ".pdf");

    if(Files.exists(arquivo)){

        response.setHeader(" Content-Disposition","attachment, filename=\"" + fileName + ".pdf" + "\"");
        response.setContentType(" application/pdf");
        try {

            Files.copy(arquivo, response.getOutputStream());
            response.getOutputStream().flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return new ModelAndView(REQUEST_MAPPING_PAGE_PESQUISAR_ITO);
}

A: Você pode fazer assim:
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

public class Teste {

    @RequestMapping(value = "download/{id:.+}", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<InputStreamResource> downloadArquivo(@PathVariable(value = "id") String id) throws Exception {
        byte[] file = buscaArquivoPorId(id);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "document.pdf");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(file.length);

        return new ResponseEntity<>(new InputStreamResource(new ByteArrayInputStream(file)), headers, HttpStatus.OK);
    }

}

A: Opa, eis minha solução:
public static final Path uploadingdir = "caminho do arquivo";

@GetMapping("/{nome:.*}")
public void downloadPDFResource(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("nome") String fileName) {

    Path file = Paths.get(uploadingdir.toString(), fileName);
    if (Files.exists(file)) {
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        try {
            Files.copy(file, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException("Erro baixar arquivo", e);
        }
    }
}

Só tem que observar o caminho do arquivo que você está buscando.


text:
Q: What's the probability a rabbit will return to a (certain) forest? Let's assume we have a forest.
And there is a breed of rabbits that is visiting that forest all the time.
It is possible to distinguish every individual rabbit.
There are devices in that forest that count the visits of every individual rabbit on a daily basis; so there are not two or more visits for a specific rabbit on one day; a rabbit stay the whole day so to say.
The information I have is e.g.:

*

*rabbit #343 visited the forest on May 5th 2012 for the 12th time.

*rabbit #793 visited the forest on June 2nd 2012 for the 1st time.

now the CEO of the forest wants to measure if there is a tendency of rabbits not coming back.
and I am the CEO's data guy and have to figure that out.
My question is if this "problem type" is known under a specific label - I guess it is - and if there is something like an established formula to indicate the "back out rate" or the "loyalty rate" / "probability of another visit extrapolated for all rabbits".
What I will do is to chart for multi-day-time-periods (e.g. a week)

*

*the number of rabbits that visited for the first time

*and the number of rabbits that visited for the last time (e.g. hindsight knowledge for six month)

but I doubt that is the most efficient way to go about this question.

A:
In a business-analytic context, this is often referred to as churn
  modeling or churn prediction. It employs a wide variety of statistical
  ideas and methodologies including survival analysis, Markov-chain and
  stochastic-process theory, hierarchical Bayes models, etc.


text:
Q: NO DML after Test.Start() but still getting System.CalloutException: You have uncommitted work pending Basically, I'm getting the dreaded "System.CalloutException: You have uncommitted work pending." exception even though I'm 99.999% sure I'm not making any DML statements after running Test.startTest().
I've reduced my test to the simplest form and am still getting the error.
 @isTest static void test_WTFSALESFORCE() {

    abc__c abc = new abc__c(
            Name = 'test');
    insert abc;

    //set mock
    MockHttpResponseGenerator mock =
        new MockHttpResponseGenerator('http://google.com','Hello World');

    Test.startTest();

    Test.setMock(HttpCalloutMock.class, mock);

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://google.com');
    req.setMethod('GET');

    // Send the request, and return a response
    HttpResponse res = h.send(req);
    String resp = res.getBody();

    Test.stopTest();
}

It is embarrassing how long I've spent trying to debug this with no progress...
The object in question is a dummy object and not part of any workflows or triggers.
Am I missing something?
Also the test passes fine in a Full Copy Sandbox that was refreshed less than a month ago.

A: Change API Version to 35. Version 35 doesn't have this issue.

A: Turns out another reason this might be happening is if you have a workflow that with an Email Alert action.  You can easily see if this is happening by searching your debug log for an event of: WF_EMAIL_ALERT.
I had a project where I couldn't seem to test ANY callout, no matter how simple the setup.  Turns out the Account had a workflow on it that sent an email alert if a field was blank.  Of course my TestUtil method that was instantiating accounts wasn't setting this field.


text:
Q: Date and time of execution of a program How can date and time of execution of a program be loaded at middle of a program.
Every time I use exec date command it seems to ignore everything beneath it.

A: From help exec:
exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
    Replace the shell with the given command.

You don't want to replace the current shell (which will prevent script execution from reaching any subsequent commands): just use date
echo "HELLO"
date
echo "HI"


text:
Q: How to avoid Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 AuthorizedOnly" in MAC OS I am trying connecting with Slack API from my MAC using Eclipse and Java.
But the same code is working in Windows. In MAC OS it is throwing below error:

org.springframework.web.client.ResourceAccessException: I/O error on
  GET request for "https://slack.com/api/rtm.connect": Unable to tunnel
  through proxy. Proxy returns "HTTP/1.1 407 AuthorizedOnly"; nested
  exception is java.io.IOException: Unable to tunnel through proxy.
  Proxy returns "HTTP/1.1 407 AuthorizedOnly"


text:
Q: When UINavigationController is modally presented via Storyboards, it's rootViewController has no connection to it My storyboard looks like this:

The first part works prefect, the problem is that when I use the "Test Modal" button to modally show the second NavigationController, that is correctly set up to have a rootViewController - the connection is not being made.
Meaning, I know the UINavigationController is there (with querying all controllers starting from the UIWindow's rootViewController), and my controller is also loaded, but navigationController is nil, parentViewController is nil - there's no way I could access the UINavigationController (and thus no way to customize the top toolbar)
If I check the "Is Initial View Controller" on the second UINavigationController, it works (but obviously that's not what I want). I believe this might be a UIKit bug. Or am I doing it wrong?

A: Did implement your prepareForSegue method correctly?
This is how I implement my prepareForSegue method in my apps.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"yourConnectionName"]) {
UINavigationController *navController = segue.destinationController;
YourViewControllerClass *controller = (YourViewControllerClass *)navController.topViewController;
controller.delegate = self;
}
}

A: I've finally found this one out.
I WASN'T CALLING [super initWithCoder:decoder] in my init. This left some UIViewController variables uninitialized. After changing that it works like a charm.


text:
Q: Using different table alias with getCollection() I'm trying to build a subquery using Zend/Magento's way to build queries.
I'm getting the collection this way: $collection = Mage::getModel('sales/order_item')->getCollection();
This will generate the SQL similar to this one:
SELECT `main_table`.* FROM `sales_flat_order_item` AS `main_table`

It there any way to set a different table alias instead of main_table?
In other words, is there any way to specify the custom alias for the table in collection.

A: So this main_table section is added in the abstract collection Mage_Core_Model_Resource_Db_Collection_Abstract.
protected function _initSelect()
{
    $this->getSelect()->from(array('main_table' => $this->getMainTable()));
    return $this;
}

Sadly throughout magento it is assumed that the main table with have the alias main_table so I would say when dealing with a magento collection it would be tough/fruitless to change this. If you want to see how bad it gets simply grep for main_table :(
If you change this function to set the alias to your_alias then you will get and error as there is a filter added on store_id with the main_table alias so you do not get very far.
But if you are building your own sql then you can simply pass in the alais and table to the from function of the select.
$select = $adapter->select()->from(array('your_alias' => 'your_table'))


text:
Q: How to prevent Ubuntu 16.04 from freezing after login ( nvidia graphic card and uefi secureboot) I've been using Ubuntu for a year now without any major issue so I decided last month to install it onto my desktop.
It worked well for a month and then, on morning, It just stopped working.
Once I log in, it freezes. I searched on the internet and came to the conclusion that the problem was linked to my graphics card (nvidia) and secure boot. I managed to turn off secure boot and to install the new driver onto my computer and it worked again.
Then, I plugged a wifi dongle in, and it froze again.
I reinstalled Ubuntu.
On the first boot, I installed the nvidia drivers and started to reupload all my stuff onto it.
On the second boot... it froze again.
How can I fix this?


text:
Q: Inconsistent behavior when hover on inner element Consider this code (https://codepen.io/raelb/pen/KBEaXq):
HTML:

Notebook
    10

CSS:
a {
color: black;
text-decoration: none;
}

.block {
display: inline-block;
font-family: 'Roboto', sans-serif;
border: 1px silver solid;
margin-bottom: 4px;
padding: 2px;
padding-right: 4px;
padding-left: 4px;
font-size: 13px;
}

.block:hover {
background-color: gray;
color: white;
}

.count {
color: green;
display: inline-block;
margin-left: 2px;
padding-left: 4px;
border-left: 1px silver solid;
}

.count:hover{
  color: white;
}

If .count does not contain the color property, then when I hover over the block, the count text will go white (automatically). However, if color is defined, then when I hover over the block, the count text is unaffected, (and also, the .count:hover selector is not active).
So, this seems inconsistent. In one case a hover color is applied to the inner span, however in the other case no hover color is applied.
Why is this? And is there a way to get .count:hover to apply to the count, when I hover over the block div and have defined a color property for .count?

A: I believe you want the count to turn white whenever you hover over the block. This can simply be done by changing the properties of .count whenever the block element is hovered on. In your CSS, you change the color of the count whenever the count element is hovered on and the count's hover box is smaller than the box of the block. This can be fixed by implementing this code in place of your last definition in your CSS:
    .block:hover .count {
      color: white;
    }

Here's a working example.

a {
  color: black;
  text-decoration: none;
}

.block {
  display: inline-block;
  font-family: 'Roboto', sans-serif;
  border: 1px silver solid;
  margin-bottom: 4px;
  padding: 2px;
  padding-right: 4px;
  padding-left: 4px;
  font-size: 13px;
}

.block:hover {
  background-color: gray;
  color: white;
}

.count {
  color: green;
  display: inline-block;
  margin-left: 2px;
  padding-left: 4px;
  border-left: 1px silver solid;
}

.block:hover .count {
  color: white;
}

Notebook
      10

You can also find it on Codepen here.

A: The inconsistent behavior you are referring to is totally expected based on the CSS Specificity rules.
Quoting from here:

Specifity is not inherited. If you declare 27 values on a parent of a paragraph, and even add !important, but declare the paragraph separately, the property declared on the element will be applied. Inheritance does not trump such declarations.

That means that when hover on .block div, the rules specified for .count selector have bigger priority that rules for .block:hover selector, so the .count text remains green when hover on .block div, because the rule:
.count {
    color: green;
}

overrides the rule:
.block:hover {
    color: white;
}

That explains the fact that when you omit the color rule for .count (color: green), the color rule .block:hover is applied (color: white), but when you do have a color rule for .count then this rule is applied and the span.count remains green.
Given your css rules, you have to hover on .count for the color to become white.
TusharDevelops has already answered how to solve your practical problem I just explain the theory behind this.


text:
Q: Como deixar o menu selecionado ativo com jquery? Gostaria de saber como fazer para deixar o menu selecionado ativo.
Segue como está meu código html e js, acredito que não está funcionando pois quando redireciona para o link da tag , perde o js, quando eu uso preventDefault funciona como eu queria, porém não vai para o link do menu.
Alguém pode me ajudar?

 $('.item-menu').click(function (e)
 {
  $('.item-menu').removeClass('active');
  $(this).addClass('active');
 });

Link

Link 1

Link 2

Link 3

A: Podes fazer isso no PHP, adicionando a classe, ou fazer em JS verificando o location.search e procurando o link que lhe corresponde.

$('.item-menu').click(function(e) {
  $('.item-menu').removeClass('active');
  $(this).addClass('active');
});

// verificar via JS:
const href = [location.pathname, location.search].join('?');
$('.item-menu[href="' + href + '"]').addClass('active');

Link

Link 1

Link 2

Link 3

A: Cara Tenta Passar Isso por ID e não por Classe
E Você está tirando e colocando a mesma função que está contida.
$('#item-menu').click(function (e)
{
    $('#item-menu').removeClass('active');
    $(this).addClass('active');
});

A: Resolvi por php, ficou assim:

  <?php
   $link = strip_tags($_GET['p']);
  ?>
  <li class="item-menu <?php if ($link == 'link') echo 'active'; ?> " >Link

  <li class="item-menu <?php if ($link == 'link1') echo 'active'; ?> " >Link 1


text:
Q: Is there a way to position md-tooltip relative to mouse cursor? I want to position a md-tooltip element relative to where the mouse cursor is, similar to when you hover the progress bar in a YouTube video. I have the following simplified structure:

    <md-tooltip></md-tooltip>

A: Apparently yes there is:

    <md-tooltip id="slider-tooltip" style="-ms-transition: none; -o-transition: none; -webkit-transition: none; transition: none;"></md-tooltip>

And the AngularJS/jQuery function:
$scope.setTooltip = function (e) {
    $("#slider-tooltip").css("left", e.clientX - $("#slider-tooltip").width()/2);
}


text:
Q: Set up Numpy random seed to 150 to make sure you get the same results I am trying to add Numpy Random seed to 150 to get the same results.
I tried
simulations = np.random.seed(simulations)

But got me a float error
# Generate sales samples
simulations = 10000
sales_sims = np.random.normal(sales_mean, sales_std, simulations)

print(sales_sims)
print("mean:", np.mean(sales_sims))
print("std:", np.std(sales_sims))

My question: How to set up Numpy random seed to my 10,000 simulations

A: Here's a guide on setting the random state for numpy. What does numpy.random.seed(0) do?
np.random.seed(150) #set seed
sales_mean = 0 # replace with desired value
sales_std = 1 # replace with desired value

#Generate sales samples
simulations = 10000
sales_sims = np.random.normal(sales_mean, sales_std, simulations)
print(sales_sims)
print("mean:", np.mean(sales_sims))
print("std:", np.std(sales_sims))


text:
Q: com.jcraft.jsch.JSchException: UnknownHostKey I'm trying to use Jsch to establish an SSH connection in Java. My code produces the following exception:
com.jcraft.jsch.JSchException: UnknownHostKey: mywebsite.example.
RSA key fingerprint is 22:fb:ee:fe:18:cd:aa:9a:9c:78:89:9f:b4:78:75:b4

I cannot find how to verify the host key in the Jsch documentation. I have included my code below.
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class ssh {
    public static void main(String[] arg) {

        try {
            JSch jsch = new JSch();

            //create SSH connection
            String host = "mywebsite.example";
            String user = "username";
            String password = "123456";

            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.connect();

        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

A: You can also simply do
session.setConfig("StrictHostKeyChecking", "no");

It's not secure and it's a workaround not suitable for live environment as it will disable globally known host keys checking.

A: While the question has been answered in general, I've found myself that there's a case when even existing known_hosts entry doesn't help. This happens when an SSH server sends ECDSA fingerprint and as a result, you'll have an entry like this:
|1|+HASH=|HASH= ecdsa-sha2-nistp256 FINGERPRINT=

The problem is that JSch prefers SHA_RSA and while connecting it will try to compare SHA-RSA fingerprint, which will result with error about "unknown host".
To fix this simply run:
$ ssh-keyscan -H -t rsa example.org >> known_hosts

or complain to Jcraft about prefering SHA_RSA instead of using the local HostKeyAlgorithms setting, although they don't seem to be too eager to fix their bugs.

A: You can also execute the following code. It is tested and working.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class SFTPTest {

    public static void main(String[] args) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("username", "mywebsite.example", 22); //default port is 22
            UserInfo ui = new MyUserInfo();
            session.setUserInfo(ui);
            session.setPassword("123456".getBytes());
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("Connected");
        } catch (JSchException e) {
            e.printStackTrace(System.out);
        } catch (Exception e){
            e.printStackTrace(System.out);
        } finally{
            session.disconnect();
            System.out.println("Disconnected");
        }
    }

    public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {

        @Override
        public String getPassphrase() {
            return null;
        }
        @Override
        public String getPassword() {
            return null;
        }
        @Override
        public boolean promptPassphrase(String arg0) {
            return false;
        }
        @Override
        public boolean promptPassword(String arg0) {
            return false;
        }
        @Override
        public boolean promptYesNo(String arg0) {
            return false;
        }
        @Override
        public void showMessage(String arg0) {
        }
        @Override
        public String[] promptKeyboardInteractive(String arg0, String arg1,
                String arg2, String[] arg3, boolean[] arg4) {
            return null;
        }
    }
}

Please substitute the appropriate values.

A: It is a security risk to avoid host key checking.
JSch uses HostKeyRepository interface and its default implementation KnownHosts class to manage this. You can provide an alternate implementation that allows specific keys by implementing HostKeyRepository. Or you could keep the keys that you want to allow in a file in the known_hosts format and call
jsch.setKnownHosts(knownHostsFileName);

Or with a public key String as below.
String knownHostPublicKey = "mysite.example ecdsa-sha2-nistp256 AAAAE............/3vplY";
jsch.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

see Javadoc for more details.
This would be a more secure solution.
Jsch is open source and you can download the source from here. In the examples folder, look for KnownHosts.java to know more details.

A: I would either:

*

*Try to ssh from the command line and accept the public key (the host will be added to ~/.ssh/known_hosts and everything should then work fine from Jsch) -OR-

*Configure JSch to not use "StrictHostKeyChecking" (this introduces insecurities and should only be used for testing purposes), using the following code:
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);

Option #1 (adding the host to the ~/.ssh/known_hosts file) has my preference.

A: I lost a lot of time on this stupid issue, and i think the message is quite right "there is not the host in the file i'm accessing" but you can have more than a know_host file around on your system (as example i'm using mobaXterm and it keep it's own inside the installation directory mounting the home from that root).
If you are experiencing : it's working from command line but not form the application try to access to your remote server with ssh and check with verbose -v option which file is currently used an example following:
 ssh -v git@gitlab.com
 OpenSSH_6.2p2, OpenSSL 1.0.1g 7 Apr 2014
 debug1: Reading configuration data /etc/ssh_config
 debug1: Connecting to gitlab.com [104.210.2.228] port 22.
 debug1: Connection established.
 debug1: identity file /home/mobaxterm/.ssh/id_rsa type 1
 debug1: identity file /home/mobaxterm/.ssh/id_rsa-cert type -1
 debug1: identity file /home/mobaxterm/.ssh/id_dsa type -1
 debug1: identity file /home/mobaxterm/.ssh/id_dsa-cert type -1
 debug1: identity file /home/mobaxterm/.ssh/id_ecdsa type -1
 debug1: identity file /home/mobaxterm/.ssh/id_ecdsa-cert type -1
 debug1: Enabling compatibility mode for protocol 2.0
 debug1: Local version string SSH-2.0-OpenSSH_6.2
 debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2      Ubuntu-4ubuntu2.1
 debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH*
 debug1: SSH2_MSG_KEXINIT sent
 debug1: SSH2_MSG_KEXINIT received
 debug1: kex: server->client aes128-ctr hmac-sha1-etm@openssh.com zlib@openssh.com
 debug1: kex: client->server aes128-ctr hmac-sha1-etm@openssh.com zlib@openssh.com
 debug1: sending SSH2_MSG_KEX_ECDH_INIT
 debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
 debug1: Server host key: RSA b6:03:0e:39:97:9e:d0:e7:24:ce:a3:77:3e:01:42:09
 debug1: Host 'gitlab.com' is known and matches the RSA host key.
 debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19
 debug1: ssh_rsa_verify: signature correct

as you can see the key was found in :
debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19

and not in my windows home under C:\Users\my_local_user\.ssh , i simply merged them and aligned for solve the issue.
Hope this help someone in future

A: Depending on what program you use for ssh, the way to get the proper key could vary. Putty (popular with Windows) uses their own format for ssh keys. With most variants of Linux and BSD that I've seen, you just have to look in ~/.ssh/known_hosts. I usually ssh from a Linux machine and then copy this file to a Windows machine. Then I use something similar to
jsch.setKnownHosts("C:\\Users\\cabbott\\known_hosts");

Assuming I have placed the file in C:\Users\cabbott on my Windows machine. If you don't have access to a Linux machine, try http://www.cygwin.com/
Maybe someone else can suggest another Windows alternative. I find putty's way of handling SSH keys by storing them in the registry in a non-standard format bothersome to extract.

A: Supply the public rsa key of the host :-
String knownHostPublicKey = "mywebsite.example ssh-rsa AAAAB3NzaC1.....XL4Jpmp/";

session.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

A: setting known host is better  than setting fingure print value.
When you set known host, try to manually ssh (very first time, before application runs) from the box the application runs.

A: Just substitute "user", "pass", "SSHD_IP". And create a file called known_hosts.txt with the content of the server's ~/.ssh/known_hosts. You will get a shell.
public class Known_Hosts {
public static void main(String[] arg) {
    try {
        JSch jsch = new JSch();
        jsch.setKnownHosts("known_hosts.txt");
        Session session = jsch.getSession("user", "SSHD_IP", 22);
        session.setPassword("pass");
        session.connect();
        Channel channel = session.openChannel("shell");
        channel.setInputStream(System.in);
        channel.setOutputStream(System.out);
        channel.connect();
    } catch (Exception e) {
        System.out.println(e);
    }
  }
}

A:
Has anyone been able to solve this problem? I am using Jscp to scp files using public key
  authentication (i dont want to use password authentication). Help will be appreciated!!!

This stackoverflow entry is about the host-key checking, and there is no relation to the public key authentication.
As for the public key authentication, try the following sample with your plain(non ciphered) private key,

A: I've found the solution in one of the deleted answers written by @Jairo Martínez
Firstly, the server requires to store the host as hashed rsa

ssh-keyscan -H -t rsa SERVER_IP_ADDRESS >> known_hosts_file

In addition, it was required to tell Jsch that the host key is hashed

session.setConfig("HashKnownHosts",  "yes");

A: JSch jsch = new JSch();
Session session = null;
try {
   session = jsch.getSession("user", "hostname", 22); // default
   UserInfo ui = new MyUserInfo();
   session.setUserInfo(ui);
   session.setPassword("password".getBytes());
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
   Channel channel = session.openChannel("sftp");
   channel.connect();
   System.out.println("Connected");
} catch (JSchException e) {
   e.printStackTrace(System.out);
} catch (Exception e) {
   e.printStackTrace(System.out);
} finally {
   session.disconnect();
   System.out.println("Disconnected");
}


text:
Q: Method To Set Nested Property Value I'm writing a plugin for a piece of software that requires all code to be in a single class (or nested classes)...
What I'm wanting to do is create a method that can handle changes to the nested properties of my _data object and give me a central place to do things like setting a dirty flag so I know to save it later.
Below is some code illustrating my file's structure and at the bottom are two pseudo-methods that hopefully can give you an idea of what I'm trying to accomplish.
public class SomePlugin
{
    private DataObject _data;
    private bool _dataIsDirty = false;

    private class DataObject
    {
        public GeneralSettings Settings { get; set; }
    }

    private class GeneralSettings
    {
        public string SettingOne { get; set; }
        public string SettingTwo { get; set; }
    }

    protected override void Init()
    {
        _data = new DataObject
        {
            Settings = new GeneralSettings
            {
                SettingOne = "Example value one.",
                SettingTwo = "Example value two."
            }
        }
    }

    // These are pseudo-methods illustrating what I'm trying to do.
    private void SetData<t>(T ref instanceProperty, T newValue)
    {
        if (newValue == null) throw new ArgumentNullException("newValue");
        if (instanceProperty == newValue) return;

        instanceProperty = newValue;
        _dataIsDirty = true;
    }

    private void SomeOtherMethod()
    {
        SetData(_data.Settings.SettingOne, "Updated value one.");
    }

}

A: Consider an approach like:
public class SomePlugin
{
    private DataObject _data;
    private bool _dataIsDirty = false;

    public bool IsDirty => _dataIsDirty || (_data?.IsDirty ?? false);

    private class DataObject
    {
        private bool _dataIsDirty = false;

        public bool IsDirty => _dataIsDirty || (Settings?.IsDirty ?? false);
        public GeneralSettings Settings { get; set; }
    }

    private class GeneralSettings
    {
        public bool IsDirty { get; set; }

        private string _settingOne;

        public string SettingOne
        {
            get { return _settingOne; }
            set
            {
                if (value != _settingOne)
                {
                    IsDirty = true;
                    _settingOne = value;
                }
            }
        }

        public string SettingTwo { get; set; } // Won't mark as dirty
    }
}

Note in particular that SettingOne has logic in its setter to determine whether to set IsDirty or not.


text:
Q: EXCEL-compare two cells in two workbooks if matched copy other cell related to matched cell in to checked workbook cell I have two excel workbook and book1 has a column(Name) should match with book2 column(Name) and if matched then it should copy column2(address) from book1 and copy to the column2(address) of the book2. if nothing is matched leave it as it is.
if anyone can help me very much appreciated.
P.S. These two workbooks received from two different sources and have 1000 of rows and 10 or more columns so above is an example only without other columns.

A: If you create the helping column in the Book2, you can try following: =IF((A2=[Book1.xlsx]Sheet1!A2)=TRUE,[Book1.xlsx]Sheet1!B2,B2)
Modify the ranges, since I don't know where you have the data and spread the formula as you wished. If names are same, then it will copy address from Book1 and if not, it will copy address from Book2. Then you can copy and paste as values the helping column into the column with your addresses in Book2 and remove the helping one.


text:
Q: Add a particular string (in that case "\\\hline" to prepare a table in latex) at the end of each line of a text file with python I want to add a particular string (in that case "\\hline" to prepare a table in latex) at the end of each line of a text file
a_file = open("sample.txt", "r")
list_of_lines = a_file.readlines()
for line in range(0, len(list_of_lines)):
  list_of_lines[line] = list_of_lines[line] + r' \\\line'

a_file = open("sample2.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()

Here is sample.txt:
line1
line2
line3

Here is the output:
l1
 \\\linel2
 \\\linel3
 \\\line%

What I want is:
l1 \\\line
l2 \\\line
l3 \\\line

A: The problem is that you are not removing the linebreak '\n' at the end of your lines.
The first line actually looks like this: 'line1\n'. When you add your string, then the result is 'line1\n \\\line' which gets displayed with a linebreak in the place of '\n'. So you first need to strip the linebreak, then add your string and a linebreak again.
Also, I recommend using context managers (with) to open your files , it's much safer than opening and closing the file manually and is considered best practice.
with open('sample.txt') as file:
    list_of_lines = file.readlines()

for i in range(len(list_of_lines)):
    list_of_lines[i] = list_of_lines[i].rstrip() + r'\\\line' + '\n'

with open('sample2.txt', 'w') as file:
    file.writelines(list_of_lines)

A: Try list_of_lines[line].rstrip(). It seems that the end of line character is being appended in your output.


text:
Q: Listing every street name per postal code I would like to export a list of all street names per postal code for Germany.
More specificly, I have looked at OpenStreetMap/the Overpass API.
With
[out:json];
(
    area[postal_code="31061"];
);
way(area)[highway][name];
out;

i can get a list containing information about every street in the postal code "31061 - Alfeld".
Now, I could just use a public API, but I don't think they'd be happy with me firing 30k requests against their API.
I could host my own version of the Overpass API, altough that requires very large amounts of resources (HDD and RAM). I tried importing the dataset for germany, but had limited success due to the large file sizes.
There has to be a better solution to get the data I would like to have.
Is there maybe a commandline-tool available, that can extract all streets for a specific postal code from a http://download.geofabrik.de/europe/germany.html dump?

A: I don't think there is such a command line tool available. You can probably build something similar with osmium-tool. However it will take ages to process a raw PBF or XML file until obtaining all the information you are interested in. You will have to re-read the file for each query and you can't really perform spatial queries against it.


text:
Q: Can maximum number of characters be defined in C# format strings like in C printf? Didn't find how to do that. What I found was more or less on the lines of this (http://blog.stevex.net/string-formatting-in-csharp/):
There really isn't any formatting within a string, beyond it's alignment. Alignment works for any argument being printed in a String.Format call.
Sample  Generates
String.Format("->{1,10}<-", "Hello");  // gives "->     Hello<-" (left padded to 10)
String.Format("->{1,-10}<-", "Hello"); // gives "->Hello     <-" (right padded to 10)

A: What you want is not "natively" supported by C# string formatting, as the String.ToString methods of the string object just return the string itself.
When you call
string.Format("{0:xxx}",someobject);

if someobject implements the IFormattable interface, the overload ToString(string format,IFormatProvider formatProvider) method gets called, with "xxx" as format parameter.
So, at most, this is not a flaw in the design of .NET string formatting, but just a lack of functionality in the string class.
If you really need this, you can use any of the suggested workarounds, or create your own class implementing IFormattable interface.

A: This is not an answer on how to use string.format, but another way of shortening a string using extension methods. This way enables you to add the max length to the string directly, even without string.format.
public static class ExtensionMethods
{
    /// <summary>
    ///  Shortens string to Max length
    /// </summary>
    /// <param name="input">String to shortent</param>
    /// <returns>shortened string</returns>
    public static string MaxLength(this string input, int length)
    {
        if (input == null) return null;
        return input.Substring(0, Math.Min(length, input.Length));
    }
}

sample usage:
string Test = "1234567890";
string.Format("Shortened String = {0}", Test.MaxLength(5));
string.Format("Shortened String = {0}", Test.MaxLength(50));

Output:
Shortened String = 12345
Shortened String = 1234567890

A: I've written a custom formatter that implements an "L" format specifier used to set maximum width. This is useful when we need to control the size of our formatted output say when destined for a database column or Dynamics CRM field.
public class StringFormatEx : IFormatProvider, ICustomFormatter
{
    /// <summary>
    /// ICustomFormatter member
    /// </summary>
    public string Format(string format, object argument, IFormatProvider formatProvider)
    {
        #region func-y town
        Func<string, object, string> handleOtherFormats = (f, a) =>
        {
            var result = String.Empty;
            if (a is IFormattable) { result = ((IFormattable)a).ToString(f, CultureInfo.CurrentCulture); }
            else if (a != null) { result = a.ToString(); }
            return result;
        };
        #endregion

        //reality check.
        if (format == null || argument == null) { return argument as string; }

        //perform default formatting if arg is not a string.
        if (argument.GetType() != typeof(string)) { return handleOtherFormats(format, argument); }

        //get the format specifier.
        var specifier = format.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture);

        //perform extended formatting based on format specifier.
        switch(specifier)
        {
            case "L":
                return LengthFormatter(format, argument);
            default:
                return handleOtherFormats(format, argument);
        }
    }

    /// <summary>
    /// IFormatProvider member
    /// </summary>
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    /// <summary>
    /// Custom length formatter.
    /// </summary>
    private string LengthFormatter(string format, object argument)
    {
        //specifier requires length number.
        if (format.Length == 1)
        {
            throw new FormatException(String.Format("The format of '{0}' is invalid; length is in the form of Ln where n is the maximum length of the resultant string.", format));
        }

        //get the length from the format string.
        int length = int.MaxValue;
        int.TryParse(format.Substring(1, format.Length - 1), out length);

        //returned the argument with length applied.
        return argument.ToString().Substring(0, length);
    }
}

Usage is
var result = String.Format(
    new StringFormatEx(),
    "{0:L4} {1:L7}",
    "Stack",
    "Overflow");

Assert.AreEqual("Stac Overflo", result);

A: Can't you just apply length arguments using the parameter rather than the format?
String.Format("->{0}<-", toFormat.PadRight(10)); // ->Hello     <-
Or write your own formatter to allow you to do this?

A: Why not just use Substr to limit the length of your string?
String s = "abcdefghijklmnopqrstuvwxyz";
String.Format("Character limited: {0}", s.Substr(0, 10));

A: You may want to use this helper in future application, it limits the string at given maximum length and also pads if it is shorter than the given limit.
public static class StringHelper
{

    public static string ToString(this string input , int maxLength , char paddingChar = ' ', bool isPaddingLeft = true)
    {
        if (string.IsNullOrEmpty(input))
            return new string('-', maxLength);
        else if (input.Length > maxLength)
            return input.Substring(0, maxLength);
        else
        {
            int padAmount = maxLength - input.Length;
            if (isPaddingLeft)
                return input + new string(paddingChar, padAmount);
            else
                return new string(paddingChar, padAmount) + input;
        }
    }
}

and you could use it as:
 string inputStrShort = "testString";
 string inputStrLong = "mylongteststringexample";
 Console.WriteLine(inputStrShort.ToString(20, '*', true)); // Output : testString**********
 Console.WriteLine(inputStrLong.ToString(20, '*', true));  // Output : mylongteststringexam


text:
Q: Ruby: add method to existing class I am newish to Ruby and I am trying to write a method to dynamically add methods to n existing ruby class, here is what I have so far:
class Person
end

def attr_addr (target, attr)
    target.send :attr_accessor, attr
end

bob = Person.new

attr_addr(Person,"name")

bob.name = "bob"

But I get:
private method `name=' for ....

What am I doing wrong here? - am I using the wrong approach entirely ;-)?

A: Your original code works for me. Anyway, here's another way to write it:
def attr_addr(target, attr)
  target.instance_eval "attr_accessor :#{attr}"
end

Here it is in action in an IRB session:
>> bob = Person.new
=> #<Person:0x00000000df8798>
>> bob.name = "bob"
NoMethodError: undefined method `name=' for #<Person:0x00000000df8798>
        from (irb):6
        from /home/michi/.rbenv/versions/1.9.3-p0/bin/irb:12:in `<main>'
>> attr_addr(Person, "name")
=> nil
>> bob.name = "bob"
=> "bob"
>> bob
=> #<Person:0x00000000df8798 @name="bob">

A: It works for me (Ruby 1.8.7):
irb(main):001:0> class Person; end
=> nil
irb(main):003:0> Person.send :attr_accessor, :name
=> nil
irb(main):004:0> p = Person.new
=> #<Person:0x7f9716bad768>
irb(main):005:0> p.name = "test"
=> "test"
irb(main):006:0> p.name
=> "test"


text:
Q: Using Python3, is there a simple way to filter a dataframe [WaypointID1, WaypointID2] to get only starting waypointIDs to final waypointIDs I am looking for a method to summarize a 2 columns dataset like this :
Source, Target
PlaceID1,CrossroadID3
PlaceID2,CrossroadID3
CrossroadID3,PlaceID4
PlaceID4,PlaceID5
PlaceID4,PlaceID6
PlaceID6,PlaceID7

To
Source, Target
PlaceID1,PlaceID4
PlaceID2,PlaceID4
PlaceID4,PlaceID5
PlaceID4,PlaceID6
PlaceID6,PlaceID7

CrossroadID3 is used to identify link between PlaceID1 to PlaceID4
CrossroadID3 is used to identify link between PlaceID2 to PlaceID4
CrossroadID3 is not a place, so we dont want to keep it

My dataset contains only the description of [Source|Target] links, representing a set of routes starting at a PlaceID, passing through some of these PlaceIDs and ending at other PlaceIDs. I would like to reduce this dataset to just the start and end PlaceIDs, eliminating CrossroadIDs.
I wonder if there is a simple method, with Python3 and maybe Pandas or a more specialized library.
Note that my dataset contains only IDs, no coordinates :)
Thank you for help,
New in Python and new in stackoverflow ^^


text:
Q: Sending parameter to API with AJAX So I want to execute the following action. In swagger it works like this:

I've done the following in my .js:
  static performAction(id, param, actionUrl) {
  return $.ajax({
     url: api.devices.url + id + actionUrl,
     method: "PUT",
     dataType: "json",
     timeout: api.timeout,
     data: param});
 }

    ...
    //inside a function
    var act = "/setTemperature";
    var temp = "19";
    var arr = [temp];
    var pp = JSON.stringify(arr);

       //Perform action apparently fails and returns null
   api.devices.performAction(item.id, pp, act).done(function(data){
           status.nextElementSibling.innerHTML = nueva_temp + "°C"; //works ok
    });

So I'm assuming the format is wrong?? Why?


text:
Q: Formatting strings with placeholders in SQL Server like in C# I need to store generic messages in an SQL Server table, and then get the values and use them within a stored procedure, e.g. "Dear John", where instead of "John" I would like to be able to insert any name obtained within the procedure. In C#, if I stored the text like this: "Dear {0}", I could then easily format it: string.Format(myString, name). Can I do anything like this in SQL Server, other than just REPLACE? I heard something like using CLR in SQL Server, but have no idea whether or how it would work. What is the best way to achieve what I need?
Could you please help?
Thanks.

A: xp_sprintf may be what you're looking for :
DECLARE @ret_string varchar (255)
EXEC Master.DBO.xp_sprintf @ret_string OUTPUT, '(%s, %s)', 'Hello', 'World'
PRINT @ret_string

Outputs (Hello, World)


text:
Q: Localytics Android: Putting app in background causes BackgroundService to crash Fatal Exception: com.localytics.android.LocalyticsManager$LocalyticsNotInitializedException: You must first initialize Localytics
       at com.localytics.android.LocalyticsManager.getLocationHandler(LocalyticsManager.java:1211)
       at com.localytics.android.LocalyticsManager.updateMonitoredGeofences(LocalyticsManager.java:1108)
       at com.localytics.android.BackgroundService.updateGeofences(BackgroundService.java:49)
       at com.localytics.android.BackgroundService.onRunTask(BackgroundService.java:30)
       at com.google.android.gms.gcm.GcmTaskService$zzb.run(Unknown Source)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
       at java.lang.Thread.run(Thread.java:818)


text:
Q: How to append strings to a vector in R? I am new to R. I am trying to append values from a data frame like this
here is the data frame tu :
         t     u
1     What   LOL
2 Whatever   ALL
3    Works   OLO
4     What  POLO
5 Whatever CHOLO
6 Whatever  LOLO
7    Works     C
8 Whatever     D

I want to print the values of u for which t is "Whatever"
a <- vector()
for(i in 1:8) {
if(tu$t[i] == 'Whatever') {
  a<-c(a,tu$u[i])
}}

When the execution is complete I am getting the value of print(a) as an integer type Vector instead of a vector of a set of strings. "ALL CHOLO LOLO D"
The output is int [1:4] 1 3 6 4 Can anybody explain what is happening?
PS: Ignore the values of u :P

A: First convert your columns to characters
tu$t <- as.character(tu$t)
tu$u <- as.character(tu$u)

And then rerun the code


text:
Q: How can I change the font and font size of a gridview as focus/selection changes In UWP I'm building a Gridview that contains letters. (e.g. A B C D E F G... Z)  as the user navigates in the Gridview I'd like to change the font(and size) of the currently selected/focused letter.  I'd like to be able to do it via XAML if possible but I can't seem to make it work.
Some background:
I've created a DataTemplate to represent my letters (I have 2 data templates, one for enabled letters and one for disabled letters) and I use an ItemTemplateSelector and databinding to render the list of letters.
I've a LetterModel that represents the Letter and it's state so that At page load some the disabled letters have a different look and those items are disabled in the gridview. I'd now like to be able to change the font and font size via the styling of the LIstViewPresenter (if this is even possible).
Some code:
Letter Model:
public class LetterModel
{
    public string Letter { get; set; }
    public bool IsEnabled { get; set; }
}

Data Templates XAML (contained in a resource file along with the GridViewItem Style overrides I've implemented):
    <helpers:LetterSelector x:Key="alphabetSelector" EnabledTemplate="{StaticResource LetterEnabled}" DisabledTemplate="{StaticResource LetterEnabled}"/>

    <DataTemplate x:Name="LetterEnabled">
        <TextBlock x:Name="myLetter" Text="{Binding Letter}" Style="{StaticResource LetterTextStyle}" FontSize="24"/>
    </DataTemplate>

    <DataTemplate x:Name="LetterDisabled">
        <TextBlock x:Name="myLetter" Text="{Binding Letter}" Style="{StaticResource DisabledLetterTextStyle}" Foreground="{StaticResource MyColor}" FontSize="24"/>
    </DataTemplate>

Declaration of GridView in a page:
<GridView x:Name="alphaGrid" Width="Auto" Height="Auto"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch" Margin="22, 0, 22, 0"
    SelectionChanged="AlphaGrid_SelectionChanged"
    ItemsSource="{x:Bind MyViewModel.Letters}"
    ItemTemplateSelector="{StaticResource alphabetSelector}"
    ItemContainerStyle="{StaticResource LetterSelectionGridViewStyle}">

Here is my LetterSelectionGridViewStyle:
<Style x:Key="LetterSelectionGridViewStyle" TargetType="GridViewItem">
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
        <Setter Property="Background" Value="{ThemeResource GridViewItemBackground}"/>
        <Setter Property="Foreground" Value="{ThemeResource GridViewItemForeground}"/>
        <Setter Property="TabNavigation" Value="Local"/>
        <Setter Property="IsHoldingEnabled" Value="True"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Margin" Value="0,0,6,6"/>
        <Setter Property="MinWidth" Value="{ThemeResource GridViewItemMinWidth}"/>
        <Setter Property="MinHeight" Value="{ThemeResource GridViewItemMinHeight}"/>
        <Setter Property="AllowDrop" Value="False"/>
        <Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}"/>
        <Setter Property="FocusVisualMargin" Value="-2,-2,-2,-6"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="GridViewItem">
                    <ListViewItemPresenter x:Name="Root" CheckBrush="{ThemeResource GridViewItemCheckBrush}"
                                           ContentMargin="{TemplateBinding Padding}"
                                           CheckBoxBrush="{ThemeResource GridViewItemCheckBoxBrush}"
                                           ContentTransitions="{TemplateBinding ContentTransitions}"
                                           CheckMode="{ThemeResource GridViewItemCheckMode}"
                                           DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
                                           DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
                                           DragBackground="{ThemeResource GridViewItemDragBackground}"
                                           DragForeground="{ThemeResource GridViewItemDragForeground}"
                                           FocusBorderBrush="{ThemeResource GridViewItemFocusBorderBrush}"
                                           FocusVisualPrimaryBrush="{StaticResource MyOrange}"
                                           FocusVisualPrimaryThickness="0,0,0,8"
                                           FocusVisualMargin="{TemplateBinding FocusVisualMargin}"
                                           FocusSecondaryBorderBrush="{ThemeResource GridViewItemFocusSecondaryBorderBrush}"
                                           HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                           Control.IsTemplateFocusTarget="True"
                                           PressedBackground="{ThemeResource GridViewItemBackgroundPressed}"
                                           PlaceholderBackground="{ThemeResource GridViewItemPlaceholderBackground}"
                                           PointerOverForeground="{ThemeResource GridViewItemForegroundPointerOver}"
                                           PointerOverBackground="{ThemeResource GridViewItemBackgroundPointerOver}"
                                           RevealBorderThickness="{ThemeResource GridViewItemRevealBorderThemeThickness}"
                                           ReorderHintOffset="{ThemeResource GridViewItemReorderHintThemeOffset}"
                                           RevealBorderBrush="{ThemeResource GridViewItemRevealBorderBrush}"
                                           RevealBackground="{ThemeResource GridViewItemRevealBackground}"
                                           SelectedForeground="{ThemeResource GridViewItemForegroundSelected}"
                                           SelectionCheckMarkVisualEnabled="{ThemeResource GridViewItemSelectionCheckMarkVisualEnabled}"
                                           SelectedBackground="{ThemeResource SystemControlTransparentBrush}"
                                           SelectedPressedBackground="{ThemeResource SystemControlTransparentBrush}"
                                           SelectedPointerOverBackground="{ThemeResource SystemControlTransparentBrush}"
                                           VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="Selected"/>
                                <VisualState x:Name="PointerOver">
                                    <VisualState.Setters>
                                        <Setter Target="Root.(RevealBrush.State)" Value="PointerOver"/>
                                    </VisualState.Setters>
                                </VisualState>
                                <VisualState x:Name="PointerOverSelected">
                                    <VisualState.Setters>
                                        <Setter Target="Root.(RevealBrush.State)" Value="PointerOver"/>
                                    </VisualState.Setters>
                                </VisualState>
                                <VisualState x:Name="PointerOverPressed">
                                    <VisualState.Setters>
                                        <Setter Target="Root.(RevealBrush.State)" Value="Pressed"/>
                                    </VisualState.Setters>
                                </VisualState>
                                <VisualState x:Name="Pressed">
                                    <VisualState.Setters>
                                        <Setter Target="Root.(RevealBrush.State)" Value="Pressed"/>
                                    </VisualState.Setters>
                                </VisualState>
                                <VisualState x:Name="PressedSelected">
                                    <VisualState.Setters>
                                        <Setter Target="Root.(RevealBrush.State)" Value="Pressed"/>
                                    </VisualState.Setters>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="DisabledStates">
                                <VisualState x:Name="Enabled"/>
                                <VisualState x:Name="Disabled">
                                    <VisualState.Setters>
                                        <Setter Target="Root.RevealBorderThickness" Value="0"/>
                                    </VisualState.Setters>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </ListViewItemPresenter>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Ideally I'd be able to do something in the VisualStateGroups that understands the selected/unselected behavior and I could change the FontSize Properties in my datatemplate
Or am I just misunderstanding something here?
I tried using behaviors in my DataTemplate however that changed all the letter's fonts... not just the selected.
I've spent a lot of time trying to Understand if this should be doable in XAML.
Thanks!

A: If you set the FontSize=24 in your DataTemplate, then the font size applied to 'ListViewItemPresenter' will not work.
So, if you want to change the font size when the GridViewItem is selected in visual state, you need to remove the FontSize=24 in your DataTemplate and change the font size in 'Selected' visual state directly.
<VisualState x:Name="Selected">
     <VisualState.Setters>
          <Setter Target="Root.FontSize" Value="50"></Setter>
     </VisualState.Setters>
</VisualState>


text:
Q: checking version numbers in rails I've got a mobile app that makes an api call. In the api call, I'm sending the version number of the app because the returned json could be a bit different depending on the api version.
So when I have app version 2.4.1 and I need to check against the current api version 2.4.4, I everything is fine because I'm using

if user_version.gsub('.','').to_i < server_version.gsub('.','').to_i
 //the user version is not current, ask them to update
end

the problem comes in down the line when somebody releases version 2.5. With the above code, the user would have 2.4.4 which gets translated to 244 which is larger than the server side 2.5 or 25.
How would you check this to cover these instances?

A: You can parse the version numbers using a regex, as detailed here: A regex for version number parsing
This one will do: ^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$
So:
version_regex = /^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/
user_version_array = user_version.match(version_regex)[1..3].compact.map(&:to_i)
server_version_array = server_version.match(version_regex)[1..3].compact.map(&:to_i)

For the sake of DRYness, you might want to break this out into a helper method:
def parse_version(str)
  version_regex = /^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/
  str.match(version_regex)[1..3].compact.map(&:to_i)
end

For the example of user_version = '2.4.4' and server_version = '2.5', that gives you the arrays:
user_version_array = [2,4,2]
server_version_array = [2,5]

You can then easily iterate over these to compare:
compliant_version = true
(0..2).each do |i|
  if (user_version_array[i] || 0) < (server_version_array[i] || 0)
    compliant_version = false
  end
end

A: Turns out this is included as a class in Rails
http://rubygems.rubyforge.org/rubygems-update/Gem/Version.html
much easier than writing it yourself. :)