text:
Q: Rails 5 LoadError (cannot load such file -- roo) I cannot seem to load roo and want to use it to import google spreadsheets
Im using rails 5.2.3, ruby 2.6.1p33
roo (2.8.2, 2.7.1)
Does anyone have an idea why this is happening?
When I try requiring roo in irb console, it seems to be working
class User < ApplicationRecord
  has_secure_password

  validates :username, presence: true, uniqueness: true

  require 'roo'

  def self.import(file)
    spreadsheet = Roo::Spreadsheet.open(file.path)
  end
end

Gemfile
gem "roo", "~> 2.8.0"

A: It's mostly an issue with your spring loader, run
  bundle exec spring stop
  bundle exec spring start


text:
Q: Xcode doesn't run app on devices but simulator. dyld: Library not loaded, Reason: image not found I am trying to run an open source project on my Xcode to my devices.
The app runs normally on simulator. But has fatal error when running on a device.

dyld: Library not loaded:
  /Users/Kevinscience/cerbero/dist/ios_universal/lib/libspiceglue.0.dylib
  Referenced from:
  /var/mobile/Containers/Bundle/Application/317EAAE1-F492-44DE-B4BB-68B222E73C44/flexVDI.app/flexVDI
  Reason: image not found (lldb)

Please help me to solve this problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: query distinct returns 5 fields but if 1 field not distinct but matches a certain number i want that in the result set table1
att_id name tel
a1       Joe  123456
a2       Tom  456789
a3       mary  444444
a4       sue   333333

table 2
group_id desc  att_id
5        red     a1
10       blue    a1
12       orange  a1
6        green   a2
5        red     a2
10       blue    a3
6        green   a3
5        red     a4
10       blue    a4
6        green   a4

i want 1 row per att_id, where group id <> 12. but here's the problem. if that attendee does have  a group record that is 5 (red) then I want to see that.
ie
att_id a1 is not on list because it has an item in group 12, which is correct
Results:
a2  tom  456789  red
a3  mary 444444
a4  sue  333333  red

my query goes something like this:
SELECT DISTINCT   Name, Phone
FROM table1 INNER JOIN table2 ON table1.Att_ID = table2.Att_ID
WHERE (table1.Att_ID Not In (select Att_ID from table2 where table2.Group_ID = 12))
this works to exclude the records from table 1 that have a group id 12 in table 2.I don't know how look at the records that get returned to determine if any of them have a 'red' group, yet still only have 1 record returned for that att_id, just with a col to indicate they had a red group record in table 1
sorry not sure how to articulate this well.

A: Using a DLookup() for the "red" column seems to work:
SELECT
    att_id,
    [name],
    tel,
    DLookup("[desc]", "table2", "att_id=""" & att_id & """ AND [desc]=""red""") AS red
FROM table1
WHERE att_id NOT IN (SELECT att_id FROM table2 WHERE group_id=12)


text:
Q: Saving the header of a dataframe to a csv file in pandas I have a dataframe in pandas as such
Name    Age    Gender
Emily   10     female
Rob     12     male

I want to save a csv file from this dataframe so that it looks like so
Index     ColumnName
0         Name
1         Age
2         Gender

I can't find anything online which tell me how I can do this.

A: pd.DataFrame({"ColumnName": df.columns}).to_csv("path/to/file.csv")


text:
Q: Combining data in a cell if criteria is met and then delete duplicate rows In my Excel 365 project I have 3 columns, 2 that need to be tested and 1 that needs data combining.

*

*Column A is a 7-digit "Drawing Number" (e.g. 005-0035)

*Column B is a "Revision Number" (e.g. 0)

*Column C are "Color Codes" that are comma delimited (e.g. GR, NL, TI, G0), some only containing one Color Code.

*Note: there are 3,000 rows.

*

*I need to test Column A and determine if there are any duplicates.

*If so, combine all of their Column C data into the cell of the row which contains the highest Revision Number, found in Column B, but only unique Color Codes (i.e. if both rows contain the same, or some of the same Color Code(s), don't duplicate that particular Color Code, as they must remain unique and comma delimited).

*Then, delete duplicate rows based on the Drawing Number (Column A), but keeping the row with the highest Revision Number (Column B). Note: some duplicate rows will have identical Revision Numbers; in that case keep the row with the combination of Color Codes (Column C) from step #2.
Example:
If there are 5 rows that are duplicates based on the Drawing Number (Column A), combine the Color Codes (Column C) into the row with the highest Revision Number (Column B). Finally, delete the other duplicate rows, even if they have duplicate Revision Numbers (Column B); leaving the one row with the combined Color Code (Column C).
I don't have sample code because it is beyond my expertise.

A: Sort the data then scan upwards deleting duplicate rows by comparing with the row above. Use a Dictionary to compile list of unique color codes.
Option Explicit

Sub Macro1()

    Dim wb As Workbook, ws As Worksheet
    Dim dict As Object, rng As Range
    Dim LastRow As Long, i As Long

    Set dict = CreateObject("Scripting.Dictionary")
    Set wb = ThisWorkbook
    Set ws = wb.Sheets(1)
    LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
    Set rng = ws.Range("A1:C" & LastRow)

    With ws.Sort
        .SortFields.Clear

        .SortFields.Add Key:=ws.Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, _
        DataOption:=xlSortNormal

        .SortFields.Add Key:=ws.Range("B1"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, _
        DataOption:=xlSortNormal

        .SetRange rng
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    ' scan
    For i = LastRow To 2 Step -1
        dict(Trim(ws.Cells(i, 3))) = 1
        ' compare with line above
        If ws.Cells(i - 1, 1) = ws.Cells(i, 1) Then
            ws.Rows(i).EntireRow.Delete
        Else
            ws.Cells(i, 3) = Join(dict.keys, ",")
            dict.RemoveAll
        End If
    Next
    MsgBox "Done"
End Sub


text:
Q: I'm switching to Linux desktop full time. I have some graphics/GPU questions, misunderstandings, and confusion Due to my job I've been working with Linux servers for nearly a decade, but on desktop I've really only toyed with it here and there throughout the years. This whole time I've been a macOS user.
Now I'm switching full time to a Dell OptiPlex 7020 running Fedora 30 Linux,  but I have questions pertaining to graphics and GPUs. My machine has an i5 with Intel HD 4600 graphics; on the back it has 1 VGA port and 2 DisplayPort ports. My dual monitors are connected to the DisplayPorts, one each.
I also have an NVIDIA GT 1030 in the machine with 1 HDMI and 1 DisplayPort.
I have very little need for the GT 1030's graphics capabilities except some gaming via Steam here and there. For anything else the Intel HD graphics seems to be more than capable of handling everything thrown at it and also seems to be more stable than the NVIDIA drivers.
So what happens when something needs the accelerated 3D rendering and power of the dedicated GPU but I'm connected via the motherboard's DisplayPorts? Does it still use the dedicated GPU to render? I noticed that if I start Gnome in Xorg mode it uses the GT 1030 (at least it says so in Gnome's "About" area in the settings) but if I use the default Gnome session it seems to fallback to the Intel HD graphics (also according to Gnome's "About" area in the settings). This has something to do with Wayland, correct? Any way around it? And should I even be looking for a way around it (due to my first question about rendering on the dedicated GPU)? Additionally, if I plug into the GPU's output ports and use the default Gnome (Wayland) session, will it render gnome and everything via the GT 1030 or will it still fallback to the Intel HD graphics?
If I ever want to play some games via Steam should I just log out of the standard Gnome session and log into a Gnome Xorg session or is there a less "involved" way of doing it? And do I have to plug my monitors into the GPU instead of the motherboard?
This is all kind of confusing and new to me as I have never really dealt with it before. On Macs I have never had to worry about GPU anything and on Windows I think the OS simply handles rendering on whichever device is most "appropriate" if I'm not mistaken.
Some insight and help would be greatly appreciated.
P.s. what's up with nouveau drivers instead of the proprietary drivers? Any good or should I stick to the proprietary drivers?
Edit:
➜ sudo lshw | grep product | head -n1 && sudo dmidecode -s bios-release-date && sudo dmidecode -s baseboard-product-name && sudo dmidecode -s baseboard-manufacturer:
product: OptiPlex 7020 (05A5)
06/26/2018
02YYK5
Dell Inc.

Fedora 30,
Intel i5-4590 / Intel® HD Graphics 4600,
NVIDIA GT 1030


text:
Q: How to construct a lambda for a custom sort for dbContext used in GridView on related tables I have a GridView using model binding and strongly typed EF5 dbContext classes in a webforms app. The gridview is using the SelectMethod property to return classes from my EF5 model:
<asp:GridView ID="Server_grid" runat="server" AllowSorting="True"
    ItemType="server_table" SelectMethod="getServers">

My EF server_table class has a relationship to another table called user_table. In my grid I am pulling the related username property from the user_table for one of my columns like this:
<asp:TemplateField HeaderText="User Name">
    <ItemTemplate>
        <%# Item.user_table.username %>
</asp:TemplateField>

My select method looks something like:
public IQueryable<server_table> getServers()
{
    return dataContext.server_table.Include(x => x.user_table);
}

This all works just fine, but I need to sort on this column. So... I either need to ditch model binding completely (boo!) and select into an anonymous type in my query (in other words go back to using LinqDataSource and anon types and lose the typechecking that model binding gives me, sigh) which will allow me to simply add a simple SortExpression property on the GridView, or... figure out some way to do a custom sort.
So I've been hacking around with that idea and have come up with something that might work. What I'm doing is declaring a sort event like this:
protected void serverSort(object sender, GridViewSortEventArgs e)
{
    sortExpression = e.SortExpression; //stash in a global
    e.Cancel = true; //don't actually sort
    Server_grid.DataBind(); //I'll sort there based on the stashed sortExpression
}

Then in my SelectMethod, I'm trying to build a lambda based on that saved sortexpression, so for example in this case I'd put "user_table.username" in my column SortExpression property, which gets stored in sortExpression above, then parse it and use it for the below:
public IQueryable<server_table> getServers()
{
    var query = dataContext.server_table.Include(x => x.user_table);
    //how do I use the sortExpression string below to build a lambda?
    query = query.OrderBy(SOMETHING CLEVER HERE);
    return query;
}

So basically, if I have the name of the table property OR the name of the table relationship with a property name on that related table, how can I build a lambda from that? So if my SortExpression is a simple property name on the server_table, it will work, or if it's a property name on a related table, I could parse the sortExpression string apart to have a related table + property name on that table. I need to be able to parse relationships of any length, i.e. user_table.other_table.another_table.yadday-yadday.property. There's got to be a way but my LINQ internals foo is not so great (any suggestions on a book for that?).
OR is there a better/simpler way to be able to sort like this, and continue using model binding, which I love? I wish I could just use user_table.username in the grid SortExpression property!! Agh!

A: You can use attribtes collection in order by p => p.Attributes["ColumnName"]
public IQueryable<server_table> getServers()
{
    var query = dataContext.server_table.Include(x => x.user_table);
    //how do I use the sortExpression string below to build a lambda?
    query = query.OrderBy(p => p.Attributes[ColumnNameStoredInSortExpressVariable]);
    return query;
}


text:
Q: sigma squared notation i wanna to know From where came No. 2 in this:
$$E\left( \sum (x_i - \bar x) \right)^2 = E\left(\sum(x_i - \bar x)^2 +2\sum\sum (x_i - \bar x)(x_j - \bar x)\right)$$
and why in this removed
$$2\sum\sum\rho \sigma^2)= n(n-1)\rho\sigma^2$$

A: I would recommend first working through simple summations with $ n = 2 $, $ n = 3 $, etc. in order to identify patterns in these simple cases.
n = 2
$ E \big( \sum_{i=1}^{2} (x_i-\bar{x}) \big)^2 = E \big( (x_1-\bar{x}) + (x_2-\bar{x}) \big)^2 = E \big( \big[ (x_1-\bar{x}) + (x_2-\bar{x}) \big] \big[ (x_1-\bar{x}) + (x_2-\bar{x}) \big] \big) = E \big( (x_1-\bar{x})^2 + (x_1-\bar{x})(x_2-\bar{x}) + (x_2-\bar{x})(x_1-\bar{x}) + (x_2-\bar{x})^2 \big) = E \big((x_1-\bar{x})^2 + (x_2-\bar{x})^2 + 2(x_1-\bar{x})(x_2-\bar{x}) \big) $
The above line can be re-written as:
$$ E \big( \sum_{i=1}^{2} (x_i - \bar{x})^2 + 2 \underset{i\neq j}{\sum\sum} (x_i-\bar{x})(x_j-\bar{x}) \big) $$
n = 3
$ E \big( \sum_{i=1}^{3} (x_i-\bar{x}) \big)^2 = E \big( (x_1-\bar{x}) + (x_2-\bar{x}) + (x_3-\bar{x}) \big)^2 = E \big( \big[ (x_1-\bar{x}) + (x_2-\bar{x}) + (x_3-\bar{x}) \big] \big[ (x_1-\bar{x}) + (x_2-\bar{x}) + (x_3-\bar{x}) \big] \big) = E \big( (x_1-\bar{x})^2 + (x_1-\bar{x})(x_2-\bar{x}) + (x_1-\bar{x})(x_3-\bar{x}) + (x_2-\bar{x})(x_1-\bar{x}) + (x_2-\bar{x})^2 + (x_2-\bar{x})(x_3-\bar{x}) + (x_3-\bar{x})(x_1-\bar{x}) + (x_3-\bar{x})(x_2-\bar{x}) + (x_3-\bar{x})^2 \big) = E \big((x_1-\bar{x})^2 + (x_2-\bar{x})^2 + (x_3-\bar{x})^2 + 2(x_1-\bar{x})(x_2-\bar{x}) + 2(x_1-\bar{x})(x_3-\bar{x}) + 2(x_2-\bar{x})(x_3-\bar{x}) \big) $
The above line can be re-written as:
$$ E \big( \sum_{i=1}^{3} (x_i - \bar{x})^2 + 2 \underset{i\neq j}{\sum\sum} (x_i-\bar{x})(x_j-\bar{x}) \big) $$


text:
Q: Excel Countifs formula I have nested the below IF/AND/COUNTIFS formula. The logic is based on the country in column N, refer to specific range on another sheet in the same WB. The problem I am running into is I am getting FALSE results when it should be TRUE. I have triple checked all my ranges. And all values on both sheets are formatted as General. An
=IF(AND(N2="Australia")*COUNTIFS(Ratings!A$2:A$14,'Sheet 1'!AT2,Ratings!B$2:B$14,'Sheet 1'!AU2),TRUE,
IF(AND(N2="Brazil")*COUNTIFS(Ratings!D$2:D$13,'Sheet 1'!AT2,Ratings!E$2:E$13,'Sheet 1'!AU2),TRUE,
IF(AND(N2="CanadaEnglish")*COUNTIFS(Ratings!G$2:G$19,'Sheet 1'!AT2,Ratings!H$2:H$19,'Sheet 1'!AU2),TRUE,
IF(AND(N2="CanadaFrench")*COUNTIFS(Ratings!J$2:J$19,'Sheet 1'!AT2,Ratings!K$2:K$19,'Sheet 1'!AU2),TRUE,
IF(AND(N2="France")*COUNTIFS(Ratings!P$2:P$21,'Sheet 1'!AT2,Ratings!Q$2:Q$21,'Sheet 1'!AU2),TRUE,
IF(AND(N2="Germany")*COUNTIFS(Ratings!M$2:M$17,'Sheet 1'!AT2,Ratings!N$2:N$17,'Sheet 1'!AU2),TRUE,
IF(AND(N2="Italy")*COUNTIFS(Ratings!S$2:S$7,'Sheet 1'!AT2,Ratings!T$2:T$7,'Sheet 1'!AU2),TRUE,
IF(AND(N2="Mexico")*COUNTIFS(Ratings!V$2:V$17,'Sheet 1'!AT2,Ratings!W$2:W$17,'Sheet 1'!AU2),TRUE,
IF(AND(N2="Spain")*COUNTIFS(Ratings!Y$2:Y$24,'Sheet 1'!AT2,Ratings!Z$2:Z$24,'Sheet 1'!AU2),TRUE,
IF(AND(N2="United Kingdom")*COUNTIFS(Ratings!AB$2:AB$13,'Sheet 1'!AT2,Ratings!AC$2:AC$13,'Sheet 1'!AU2),TRUE,
IF(AND(N2="USA")*COUNTIFS(Ratings!AE$2:AE$20,'Sheet 1'!AT2,Ratings!AF$2:AF$20,'Sheet 1'!AU2),TRUE)))))))))))

Any thoughts?

A: you formula is working perfect there is nothing wrong in it.
Please check below sample what i have tried as like you. It's working for me and it returns True when actually the conditions are perfect.
Hope this is what your tried for, if not please elaborate your question. So that this will be solved.

And please check you formula option is Automatic or Manual.
Note: I Just copied you formula, and changed reference for Germany and
  it works perfect.

Sheet 1 as per your formula:

Sheet 1 My Own Written Formula as Like yours:

Ratings Sheet:


text:
Q: How should I stop spam robots?
Possible Duplicates:
Blocking comment spam without using captcha
Alternative to Annoying Captcha in Forms: How to SMELL the difference between a Human Customer and a Spammy Robot?

I need a simple and efficient way of detecting spam robots. (possibly in PHP/JS)
I don't want them to insert tons of spam into my database, through a form.
Are there some good ways of doing this (not by using recaptcha)?

A: Akismet is a service/API designed to do this.  It is targeted at comment spam in particular.
You could use a friendly form of captcha.  For example, Tender App asks users things like "What comes after Wednesday?"


text:
Q: HTTPS + SSL on Heroku - Node + Express I've created a self-signed certificate, added it to Heroku, and provisioned an SSL endpoint on Heroku, and I log heroku certs:info it seems to be there.
I'm creating my server on Express like so:
var server = require('http').createServer(app);

And then redirecting to https like so:
app.use(function(req, res, next) {
    var reqType = req.headers["x-forwarded-proto"];
    reqType == 'https' ? next() : res.redirect("https://" + req.headers.host + req.url);
});

The server runs fine, however I came across this code snippet on S.O. to create an https server:
var keys_dir = './sslcert/';
var server_options = {
  key  : fs.readFileSync(keys_dir + 'server.key'),
  ca   : fs.readFileSync(keys_dir + 'server.csr'),
  cert : fs.readFileSync(keys_dir + 'server.crt')
}

var server = require('https').createServer(server_options,app);

I don't point to the certs/keys like this example, and my site is running on https (although the lock is red since it's self-signed).

*

*So my question is, how does my server know about my keys/certs without me explicitly pointing to them like the code snippet with server_options? Is this taken care of by Heroku behind the scenes?

*How does the SSL Endpoint I setup on Heroku interact with the http server I created with var server = require('http').createServer(app);?

EDIT
I just so this answer on another question:
"SSL termination occurs at Heroku's load balancers; they send your app plain (non-SSL) traffic, so your app should create a non-HTTPS server."

*

*What does they send your app plain (non-SSL) traffic mean exactly? Does this mean that I don't have to redirect to https in my app?

A: SSL termination is done on Heroku servers/load-balancers before the traffic gets to your application. The "thing" you added your cert to was not your dyno, but rather a Heroku-controlled server.
So when SSL (https) traffic comes in, it is "stopped" (terminated) at the server. That server opens a new http connection to your dyno, and whatever is gets it sends back over https to the client.
So on your dyno you don't need to "mess" with certs etc, and you will be seeing only incoming http traffic: whether directly from http clients, or from Heroku servers who talk https to clients and http to you.
Redirecting to https is a different matter: if a client "comes" to your app with http, and you prefer they use https, by all means redirect. They will issue a new request, this time https, and go thru Heroku's SSL termination and then to your app. But now you know that the path between the client and Heroku is secure (due to the client using https), and the path between the Heroku SSL termination and your dyno is presumably secure (if you trust Heroku...)
HTH


text:
Q: Why are my two methods of calculating image standard deviation returning different results? I have a dataset consisting of some 17,000 images, each of size 3000x1700.
I have two methods for computing the mean and standard deviation of my dataset: a pixel-wise approach and an image-wise approach. The pixel-wise approach simply computes the mean and std of all the pixels in the dataset, (using Welford's online algorithm since there are too many pixels in total to store them all in memory at once). The image-wise approach computes the means and variances of all the images in the dataset, then averages them (and applies sqrt to the average variance to get the standard deviation).
These two approaches will, in general, obviously not return the same results, since the image-wise approach will give equal weight to images of different sizes. However, all the images in my dataset are of the exact same size, so in my case, the two algorithms should return the same mean and std values.
import numpy as np
import os
from PIL import Image

class RunningStatisticsVar:
    def __init__(self, ddof=0):
        self.mean = 0
        self.var = 0
        self.std = 0

        self._n = 0
        self._s = 0
        self._ddof = ddof

    def update(self, values):
        values = np.array(values, ndmin=1)
        n = len(values)

        self._n += n

        old_mean = self.mean
        delta = values - self.mean
        self.mean += (delta / self._n).sum()

        self._s += (delta * (values - self.mean)).sum()
        self.var = self._s / (self._n - self._ddof) if self._n > self._ddof else 0
        self.std = np.sqrt(self.var)

    def __str__(self):
        if self.std:
            return f"{self.name} (\u03BC \u00B1 \u03C3): {self.mean} \u00B1 {self.std}"
        else:
            return f"{self.name}: {self.mean}"

def calculate_mean_and_std(source_dir, pixelwise=True):
    source_fs = [os.path.join(source_dir, f) for f in os.listdir(source_dir)]

    if pixelwise:
        stats = {colour: RunningStatisticsVar() for colour in 'rgb'}
        for source in source_fs:
            _process_image_pixelwise(source, stats)
            print(f"\u03BC: {[stats[colour].mean for colour in 'rgb']}")
            print(f"\u03C3: {[stats[colour].std for colour in 'rgb']}")

    else:
        means, vars = zip(*(_process_image(source) for source in source_fs))
        means = np.array(means)
        vars = np.array(vars)
        print(f"\u03BC: {[[means[:i+1, c].mean() for c in range(3)] for i in range(len(means))]}")
        print(f"\u03C3: {[[np.sqrt(vars[:i+1, c].mean()) for c in range(3)] for i in range(len(vars))]}")

def _process_image(source_f):
    img = np.array(Image.open(source_f))
    return img.mean(axis=(0,1)), img.var(axis=(0,1))

def _process_image_pixelwise(source_f, stats):
    img = np.array(Image.open(source_f))
    for c, colour in enumerate('rgb'):
        stats[colour].update(img[:, :, c].flatten())

calculate_mean_and_std('/path/to/dataset', True)
calculate_mean_and_std('/path/to/dataset', False)

Now, when running this code, it starts off fine, after the first image it reports:
Pixelwise
μ: [106.0911049019608, 67.80728647058824, 45.90995117647062]
σ: [41.59660208236723, 34.5791272546266, 26.781512448936052]
Imagewise
μ: [106.09110490196079, 67.80728647058824, 45.909951176470585]
σ: [41.596602082409774, 34.579127254617084, 26.78151244893938]

Only a slight aberration in the σ values. However this error gets bigger and bigger as more images are used.
Pixelwise
μ: [101.21394647058824, 65.62210166666667, 46.48841911764708]
σ: [40.41893639932673, 33.3795015706431, 26.946594699203892]
μ: [101.21668875816994, 65.61455176470588, 45.89977104575165]
σ: [39.97502569826382, 33.022993336061994, 27.14311280813053]
μ: [102.36255480392157, 65.52340710784313, 45.7435418137255]
σ: [39.24577507415308, 32.14645170321761, 26.46386419015868]
μ: [103.53420298039215, 66.6776919607843, 47.33793435294118]
σ: [39.50097527065126, 32.707463761715545, 27.354952039420294]
μ: [101.47019483660131, 64.78871330065358, 45.96562905228758]
σ: [39.004169349180536, 32.23864799529698, 26.801524930594407]
μ: [101.37475316526611, 64.89486834733893, 45.781395238095236]
σ: [39.01205310849703, 31.98696402185754, 26.461034312514027]
μ: [100.67556311274511, 64.35973938725489, 45.18712225490196]
σ: [39.4077244026275, 32.09956875358911, 26.236057166690983]
μ: [99.85794368191722, 63.74056908496731, 44.48019496732026]
σ: [39.711590893165045, 32.16450280203762, 26.02186219040715]
μ: [99.51202813725492, 63.552036745098036, 44.69082580392157]
σ: [39.67742805536442, 32.360665575523704, 26.47325733239239]
μ: [99.68222427807488, 63.67247614973262, 44.77697739750446]
σ: [39.704289274013554, 32.212222956614625, 26.25452243516258]
Imagewise
μ: [101.21394647058824, 65.62210166666667, 46.488419117647055]
σ: [40.12360583609732, 33.30789834971034, 26.940384940174805]
μ: [101.21668875816994, 65.61455176470588, 45.899771045751635]
σ: [39.77618485504031, 32.97475731200615, 27.126232255358936]
μ [102.36255480392157, 65.52340710784313, 45.74354181372549]
σ: [39.04354601878276, 32.108905824505584, 26.44949551028786]
μ: [103.53420298039217, 66.6776919607843, 47.33793435294118]
σ: [39.27047375795457, 32.596298448583816, 27.157260809967887]
μ: [101.47019483660131, 64.78871330065358, 45.96562905228759]
σ: [38.53431972571801, 31.865963477681383, 26.4560983662707]
μ: [101.37475316526611, 64.89486834733893, 45.78139523809524]
σ: [38.60904936868449, 31.66418210935895, 26.157487873733803]
μ: [100.6755631127451, 64.3597393872549, 45.18712225490196]
σ: [39.01506478558764, 31.78679779866631, 25.920704631785057]
μ: [99.85794368191722, 63.74056908496732, 44.48019496732026]
σ: [39.29746139951266, 31.839074510873296, 25.66162709110527]
μ: [99.5120281372549, 63.55203674509804, 44.69082580392156]
σ: [39.290881869376754, 32.064732326778504, 26.14723081778954]
μ: [99.68222427807487, 63.672476149732624, 44.77697739750445]
σ: [39.34959988736086, 31.939785095367306, 25.95437650452569]

and finally, after running the procedure on the entire dataset, the error becomes quite significant:
Pixelwise
μ: [101.8700454273955, 74.8429931459155, 64.76057496565133]
σ: [48.662522310391594, 41.730824001340146, 39.50453890881377]
Imagewise
μ: [101.87004542739516, 74.84299314591567, 64.76057496565105]
σ: [36.19880052359236, 32.38430878761532, 31.063098948011394]

As you can see, the means remain pretty much identical with both approaches even when the entire dataset is used. However, the standard deviation results are very far apart, even though they should be the same for both approaches. Which of my two approaches is at fault here and why?


text:
Q: How do I get nested JSON data out of SQLite with a multi-level group by? create table store (id integer primary key, name text);

create table opening (store integer references store(id),
  wday text, start integer, end integer);

insert into store (name) values ('foo'), ('bar');

insert into opening (store, wday, start, end)
  values (1, 'mon', 0, 60),
         (1, 'mon', 60, 120),
         (1, 'tue', 180, 240),
         (1, 'tue', 300, 360),
         (2, 'wed', 0, 60),
         (2, 'wed', 60, 120),
         (2, 'thu', 180, 240);

I'm trying to get in a single query all the stores and their respective openings by weekday as JSON.
{
  "1": {
    "name": "foo",
    "openings": {
      "mon": [ [ 0, 60 ], [ 60, 120 ] ],
      "tue": [ [180, 240 ], [ 300, 360 ] ]
    }
  },
  "2": {
    "name": "bar",
    "openings": {
      "wed": [ [0,60], [60,120] ],
      "thu": [ [180,240] ]
    }
  }
}

Here's the evolution of what I have tried.  I missing a way to do multi-level json_group_object I suppose.
select * from opening;

store       wday        start       end
----------  ----------  ----------  ----------
1           mon         0           60
1           mon         60          120
1           tue         180         240
1           tue         300         360
2           wed         0           60
2           wed         60          120
2           thu         180         240

select * from opening group by store;

store       wday        start       end
----------  ----------  ----------  ----------
1           mon         0           60
2           wed         0           60

select json_group_object(store, wday) from opening group by store;

json_group_object(store, wday)
-----------------------------------------
{"1":"mon","1":"mon","1":"tue","1":"tue"}
{"2":"wed","2":"wed","2":"thu"}

select store, wday, json_group_array(json_array(start, end))
  from opening group by store, wday;

store       wday        json_group_array(json_array(start, end))
----------  ----------  ----------------------------------------
1           mon         [[0,60],[60,120]]
1           tue         [[180,240],[300,360]]
2           thu         [[180,240]]
2           wed         [[0,60],[60,120]]

select json_object('id', store,
  'openings', json_group_object(wday, json_group_array(json_array(start, end)))
) from opening group by store, wday;

Error: near line 17: misuse of aggregate function json_group_array()

select json_object('id', store,
  'openings', json_object(wday, json_group_array(json_array(start, end)))
) from opening group by store, wday;

{"id":1,"openings":{"mon":[[0,60],[60,120]]}}
{"id":1,"openings":{"tue":[[180,240],[300,360]]}}
{"id":2,"openings":{"thu":[[180,240]]}}
{"id":2,"openings":{"wed":[[0,60],[60,120]]}}

How can I group on same id here?
A row will be returned for each unique values corresponding to a group by.  Thus, the outermost select must have a group by store.
select json_group_object(store, x)
from (
  select
    store,
    json_object(
      'id', store,
      'openings', json_object(wday, json_group_array(json_array(start, end)))
    ) x
  from opening group by store, wday
) group by store;

This inner query returns literal JSON however.  It seems silly to decode the inner JSON just to then encode it all in the outer-most query.
{"1":"{\"id\":1,\"openings\":{\"mon\":[[0,60],[60,120]]}}","1":"{\"id\":1,\"openings\":{\"tue\":[[180,240],[300,360]]}}"}

{"2":"{\"id\":2,\"openings\":{\"thu\":[[180,240]]}}","2":"{\"id\":2,\"openings\":{\"wed\":[[0,60],[60,120]]}}"}

IIRC in Postgres this inner query that returns JSON wouldn't return literal JSON but either way I'm confused how to continue.
Thanks for any help.

A: Adding an example for general reference. Shawn's point about using json(x) in the outer selects is key. Here's an example with multiple levels of nested arrays
The sample data: select * from tblSmall
region|subregion    |postalcode|locality                       |lat    |lng    |
------|-------------|----------|-------------------------------|-------|-------|

Delhi |Central Delhi|    110001|Connaught Place                |28.6431|77.2197|
Delhi |Central Delhi|    110001|Parliament House               |28.6407|77.2154|
Delhi |Central Delhi|    110003|Pandara Road                   |28.6431|77.2197|
Delhi |Central Delhi|    110004|Rashtrapati Bhawan             |28.6453|77.2128|
Delhi |Central Delhi|    110005|Karol Bagh                     |28.6514|77.1907|
Delhi |Central Delhi|    110005|Anand Parbat                   |28.6431|77.2197|
Delhi |North Delhi  |    110054|Civil Lines (North Delhi)      |28.6804|77.2263|
Delhi |North Delhi  |    110084|Burari                         |28.7557|77.1994|
Delhi |North Delhi  |    110084|Jagatpur                       |28.7414|77.2199|
Delhi |North Delhi  |    110086|Kirari Suleman Nagar           |28.7441|77.0732|

For each region has multiple subregion values, each subregion has multiple postalcode values, and each postalcode has multiple locality values.
Here's the sql :
select json_object('region', A2.region, 'subregions', json_group_array(json(A2.json_obj2))) from
  (select A1.region, json_object('subregion',
                                 A1.subregion,
                                 'postalCodes',
                                 json_group_array(json(A1.json_obj1)) ) as json_obj2 from
    (select region, subregion, json_object('postalCode',
                                           postalcode,
                                           'localities',
                                           json_group_array(json_object('locality',
                                                                        locality, 'latitude',
                                                                        lat, 'longitude', lng) ) ) as json_obj1
    from tblSmall where subregion in ('Central Delhi', 'North Delhi')
    group by region, subregion, postalcode) as A1
  group by A1.region, A1.subregion) as A2
group by A2.region

Note the json(A1.json_obj1) and json(A2.json_obj2) bits to handle the decode/re-encode of json coming out of the inner queries.
Here's the result (kind of long because of pretty-print) - there's a subregions array, which contains a postalcodes array, which contains a localities array:
{
  "region": "Delhi",
  "subregions": [
    {
      "subregion": "Central Delhi",
      "postalCodes": [
        {
          "postalCode": 110001,
          "localities": [
            {
              "locality": "Connaught Place",
              "latitude": 28.6431,
              "longitude": 77.2197
            },
            {
              "locality": "Parliament House",
              "latitude": 28.6407,
              "longitude": 77.2154
            }
          ]
        },
        {
          "postalCode": 110003,
          "localities": [
            {
              "locality": "Pandara Road",
              "latitude": 28.6431,
              "longitude": 77.2197
            }
          ]
        },
        {
          "postalCode": 110004,
          "localities": [
            {
              "locality": "Rashtrapati Bhawan",
              "latitude": 28.6453,
              "longitude": 77.2128
            }
          ]
        },
        {
          "postalCode": 110005,
          "localities": [
            {
              "locality": "Karol Bagh",
              "latitude": 28.6514,
              "longitude": 77.1907
            },
            {
              "locality": "Anand Parbat",
              "latitude": 28.6431,
              "longitude": 77.2197
            }
          ]
        },
        {
          "postalCode": 110060,
          "localities": [
            {
              "locality": "Rajender Nagar",
              "latitude": 28.5329,
              "longitude": 77.2004
            }
          ]
        },
        {
          "postalCode": 110069,
          "localities": [
            {
              "locality": "Union Public Service Commission",
              "latitude": 28.5329,
              "longitude": 77.2004
            }
          ]
        },
        {
          "postalCode": 110100,
          "localities": [
            {
              "locality": "Foreign Post Delhi IBC",
              "latitude": 28.6563,
              "longitude": 77.1366
            }
          ]
        }
      ]
    },
    {
      "subregion": "North Delhi",
      "postalCodes": [
        {
          "postalCode": 110054,
          "localities": [
            {
              "locality": "Timarpur",
              "latitude": 28.7038,
              "longitude": 77.2227
            },
            {
              "locality": "Civil Lines (North Delhi)",
              "latitude": 28.6804,
              "longitude": 77.2263
            }
          ]
        },
        {
          "postalCode": 110084,
          "localities": [
            {
              "locality": "Burari",
              "latitude": 28.7557,
              "longitude": 77.1994
            },
            {
              "locality": "Jagatpur",
              "latitude": 28.7414,
              "longitude": 77.2199
            }
          ]
        },
        {
          "postalCode": 110086,
          "localities": [
            {
              "locality": "Kirari Suleman Nagar",
              "latitude": 28.7441,
              "longitude": 77.0732
            }
          ]
        }
      ]
    }
  ]
}


text:
Q: Any experience of using PostSharp with ReSharper Has anyone used PostSharp with ReSharper, if so what problems should I expect?

A: I use Resharper when developing PostSharp. I also use Resharper when working on customer projects using PostSharp. There are no significant problems.
As for recommendations done by Resharper, remember that they are done based on an analysis of the source code, and are not aware of aspects.


text:
Q: trying to transfer content from a ol to ul I'm trying to move the li elements from a li list that contains 4 elements (first, second, third, fourth) to a newly created ol element. I decided to create the ol elemend and append the elements to it in a for loop, and then use replacechild to switch out the lists, but the result that I am getting is a new ol list with only two elements inside: first, third
it seems that the iterator skips one element at a time and I don't understand why?
HTML:
<input type="button" value="update" onclick="updateList()">

first

second

third

fourth

JavaScript:
function updateList() {

    var list = document.getElementById("ul");
    var newList = document.createElement("ol");

    var nodes = list.childNodes;

    for(i = 0; i < nodes.length; i++) {
        newList.appendChild(nodes[i]);
    }
parent = list.parentNode;
parent.replaceChild(newList, list)

}

A: When you move element 0, element 1 becomes element 0, and so on. Just move them in a while loop, while they exist:

function updateList() {

    var ul = document.getElementById("ul"),
        ol = document.createElement("ol");

    while (ul.childNodes.length) {
        ol.appendChild(ul.childNodes[0]);
    }

    ul.parentNode.replaceChild(ol, ul);
}
<input type="button" value="Update" onclick="updateList()">

first

second

third

fourth


text:
Q: How to add simple analytics logging to R Shiny app? I have an app.r running on a Shiny Server.
I've added this code to write to the log file, as answered at https://stackoverflow.com/a/54778579/10276092
cat(file=stderr(), paste0("\nStarting application: ", Sys.time(), "\n"))

This code is placed at the top of the UI code (for initialization), as well as in the middle of the UI display code.
However, the code only writes to the log file in /var/log/shiny-server/[appname]-shiny-[date]-[time]-[stamp].log when the R Shiny server re-initializes the app, like after editing app.r.
Is there a way to log every time the Shiny Page is opened by different users?


text:
Q: Firefox CORS failure with express node server I'm using Express.js with the CORS middleware. I'm getting very strange behavior on Firefox v73.0.1 (64-bit)
Clean firefox profile... so nothing is cached.

*

*I try a direct request to http://localhost/search?q=AMZN, I get results as expected.

*I open my webapp which is running on localhost:3000. All of these requests are not using TLS/SSL.

*I get "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/search?q=AMZN. (Reason: CORS request did not succeed)." when it tries to reach out to the API server backend.

*I refresh the other tab where I was accessing localhost directly (same request which succeeded before), and I get a "connection reset".

Chrome does not do this...
I have been looking at wireshark and Firefox simply sends a GET request (several of them? Why?? I'm only making one), sends the headers and such, then it is followed by connection reset.
Sounds like node is doing something wrong? Or I dunno.
const express = require('express');
const fetch = require('node-fetch');
const util = require('util');
const app = express();
const port = 80;

var cors = require('cors')

var copts = {
  origin: function (origin, callback) {
      console.log('yeah');
    // allow all
    callback(null, true);
  }
}

const SEARCH_URL = 'https://api.stocktwits.com/api/2/streams/symbol/%s.json';

app.get('/search', cors(copts), (req, res) => {

The "yeah" part never is hit at all.
Very simple clientside code.
return fetch(BACKEND_URL + uri).then(response => {

Tried removing CORS middleware and added these headers, based on examining github's cross-browser request-response in chrome
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Max-Age', '3600');
    res.header('Vary', 'Origin, Access-Control-Request-Headers, Access-Control-Request-Method, Accept-Encoding');
    res.header('Access-Control-Allow-Origin', '*');

I didn't really have the options handler captured so maybe this didnt matter. I found those headers in the GET response.

A: It might be possible that the node server get crashed on an invalid reqeust and hence you are getting the reset error.
With cors package:
You need to add optionsSuccessStatus property in the  cors options for some legacy browsers. And OPTIONS handler To enable pre-flightin requests.
const express = require('express');
const fetch = require('node-fetch');
const util = require('util');
const app = express();
const port = 80;
var cors = require('cors')
var copts = {
    origin: function (origin, callback) {
        console.log('yeah');
        callback(null, true);
    },
    optionsSuccessStatus: 200
}
app.options("*", cors(copts));
const SEARCH_URL = 'https://api.stocktwits.com/api/2/streams/symbol/%s.json';
app.get('/search', cors(copts), (req, res) => { });

With headers.:
You are missing Access-Control-Allow-Headers in the response headers, you need to add the Access-Control-Allow-Headers header in the response header to allow the Access-Control-Allow-Origin header.
Try this.
const express = require('express');
const fetch = require('node-fetch');
const util = require('util');
const app = express();
const port = 80;
var cors = require('cors')
var copts = {
    origin: function (origin, callback) {
        console.log('yeah');
        // allow all
        callback(null, true);
    }
}
const SEARCH_URL = 'https://api.stocktwits.com/api/2/streams/symbol/%s.json';
app.get('/search', (req, res) => {
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin');
    res.header('Access-Control-Allow-Origin', '*');
    res.status(200).send("Ok")
});

A: in my case, FireFox removes the request header from ajax to a http url, but works fine with https

A: Have you updated your front end package.json file with the following?
"proxy": "http://localhost:[your port here]/",

A: try assigning CORS to the express server like so:
const cors = require('cors');
app.use(cors());


text:
Q: preventing import of same stylesheet We are using a modeling tool that generates a wsdl from the components.  The tool generates multiple wsdl files and one wsdl that imports all the wsdls it needs (some are common objects needed by several web services).  I wrote a xsl that combines all files into one but this results in some wsdls getting included more than once and sometimes as a child of itself.
This is the template that handles import elements:
<xsl:template match="wsdl:import">
  <xsl:apply-templates select="document(@location)"/>
</xsl:template>

I would like a way to test if a file has already been imported and if so, ignore it.  Is there a way to do this in xsl? Thanks.

A: <xsl:key name="imports-by-location" match="wsdl:import" use="@location"/>

<xsl:template match="wsdl:import">
    <xsl:if test="generate-id() = generate-id(key('imports-by-location', @location))">
        <xsl:apply-templates select="document(@location)"/>
    </xsl:if>
</xsl:template>

For more information, see muenchian method (e.g. http://www.jenitennison.com/xslt/grouping/muenchian.html )


text:
Q: How to validate only alphanumeric in mobile browser with js or jquery? i have a problem for validate alphanumeric in mobile browser.
i have code like this.
var regex_alphanumeric = /[^[a-z 0-9]]*/gi;

$('#address').keypress(function (e) {
  if(e.key.match(regex_alphanumeric)){
    e.preventDefault();
    return false;
  }
});

with this code, only support for desktop browser, but if i check in mobile browser, validate alpha numeric not running well because in mobilebrowser e.key value always 229
how to check alphanumeric in mobilebrowser?

A: As mentioned in jquery docs

Note: as the keypress event isn't covered by any official
  specification, the actual behavior encountered when using it may
  differ across browsers, browser versions, and platforms.

Try this one.
One more solution to take a previous char.


text:
Q: `require': cannot load such file I have created a module which then I would inherit in my class to use its methods. But when I run the code. I get error.
mixins2.rb
module ImageUtils
    def self.status
        puts "Image storing Module"
    end

    def self.preview(image)
    end

    def self.transfer(image, destination)
    end
end

run.rb
require 'mixins2'

ImageUtils.status

When I run the file $ ruby run.rb. I get following errors:
/Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- mixins2 (LoadError)
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from run.rb:1:in `<main>'

A: You should use require_relative:
require_relative 'mixins2'

ImageUtils.status


text:
Q: MongoDB 3.0.4 - Issue connecting from Mongo Shell I am trying to connect to a new mongodb replica set which i created on 3 VMs where it was part of another replica set from a VM as Mongo shell. I cleaned up everything in all the VMs and reinstalled MongoDB after purging everything, but still the Mongo shell throws an error pointing to old VMs:
2016-07-07T17:41:35.363-0700 E - [mongosMain] error upgrading config database to v6 :: caused by :: could not write initial changelog entry for upgrade :: caused by :: failed to write to changelog:
 mongos specified a different config database string : stored : old-mongodb-host1:27018,old-mongodb-host2:27018,old-mongodb-host3-h5:27018 vs given : new-mongodb-host1:27018,new-mongodb-host1:27018,new-mongodb-host1:27018

Where this information is stored? I also restarted all the VMs many times and it does not work. Any help would be appreciated. Ubuntu version - 12.04.4 kernel - 3.11.0-15-generic. The replica set comes up fine.


text:
Q: 16 people from various countries are competing. How many possible podium outcomes by country are there? 16 people are competing
3 are from Japan,
2 each from the US, China, Australia, Brazil, and Hungary
1 each from Canada, Spain, and South Africa.

*

*How many possible podium outcomes by country are there? (Ex. Gold: China, Silver: Spain, Bronze: China, would be 1 valid combination)

*Based solely on the number of athletes per country in the semi-finals and not on their relative swimming abilities:
a. What is the probability that Canada will earn at least one medal?
b. What is the probability that Hungary will earn at least one medal?
c .What is the probability that Japan will earn at least one medal?

A: There are $9$ countries competing, hence there are $9\cdot 8\cdot 7$ podiums made by different countries. There is only $1$ podium made by a single country (Japan) and we have to count how many podiums can be conquered by exactly two different countries. There are $6$ countries with at least two athletes and a selected couple of athletes may leave out position $1$, $2$ or $3$ for an athlete from another country. So the possible podiums are
$$ 9\cdot 8\cdot 7 + 1 + 6\cdot 3\cdot 8 = 649. $$
To answer the second question I seem to miss a crucial information, i.e. which probability distribution are we assuming on the set of the possible podiums. Do we select three athletes uniformly at random from the $16$ athletes competing? If so, Japan is out of the podium with a probability equal to $\frac{\binom{13}{3}}{\binom{16}{3}}=\frac{143}{280}$, hence there is at least one japanese in the podium with probability $\frac{137}{280}\approx 48.9\%$. Similarly, the probability that Hungary will earn a medal is $1-\frac{\binom{14}{3}}{\binom{16}{3}}\approx 35\%$ and the probability that Canada will earn a medal is $1-\frac{\binom{15}{3}}{\binom{16}{3}}\approx 18.75\%$.


text:
Q: Visualise Hbase in Azure HDInsight with Power BI Can i connect power bi to Azure Hdinsight directly? And how do i do go about doing it?
I have tried googling online but there isn't any article with clear instruction on this. It is deploy under azure Vnet as well.

A:
As of today, Azure HDInsight HBase is not supported to connect Power BI.

I would suggest you to vote up an idea submitted by another customer.
https://ideas.powerbi.com/ideas/idea/?ideaid=9d8134df-19be-4608-80df-0b08f9c140d4
https://ideas.powerbi.com/ideas/idea/?ideaid=9c08cf4a-7326-493f-bff2-3967f305b6ca
All of the feedback you share in these forums will be monitored and reviewed by the Microsoft engineering teams responsible for building Power BI connectors.


text:
Q: What does the number mean in Base64.encodeToString(data, number)? I saw a lot of java encoding lately with lines like:
Base64.encodeToString(data, 0);
Base64.encodeToString(data, 2);
What does the number mean really? I suspect the 0 is default or false, and what does the 2 mean? Maybe it is the same as Base64.encodeToString(data, Base64.NO_WRAP)?

A: As mentioned here in the doc, you can pass the following flags. Each explained with its meaning.
int CRLF -> Encoder flag bit to indicate lines should be terminated with a CRLF pair instead of just an LF.
int DEFAULT -> Default values for encoder/decoder flags.
int NO_CLOSE -> Flag to pass to Base64OutputStream to indicate that it should not close the output stream it is wrapping when it itself is closed.
int NO_PADDING -> Encoder flag bit to omit the padding '=' characters at the end of the output (if any).
int NO_WRAP -> Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).
int URL_SAFE -> Encoder/decoder flag bit to indicate using the "URL and filename safe" variant of Base64 (see RFC 3548 section 4) where - and _ are used in place of + and /.


text:
Q: Tensorflow translate training - when will it stop? I am using example from Google's Tensorflow. I am able to run it well, but the training doesn't seem to stop as it has a while True: loop.
reference:
translate.py
Coe in train():
while True:
  # Choose a bucket according to data distribution. We pick a random number
  # in [0, 1] and use the corresponding interval in train_buckets_scale.
  random_number_01 = np.random.random_sample()
  bucket_id = min([i for i in xrange(len(train_buckets_scale))
                   if train_buckets_scale[i] > random_number_01])
....

A: This is true, at one point you can abort the training process. The moment of it depends on the model parameters you have choosen. According to the tensorflow documentation it takes about 340K steps with choosen batch-size of 64.
If have selected the option to create checkpoints, you can use any of the checkpoints to check your models performance with the decoder.


text:
Q: How to render React components only once on startup? I've been reading docs about performance but I can't find the answer to my question...
I have a bunch of buttons on my application that will render based on some properties but not state, parent components will never change their properties. Then I have this onKeyDown event handler that will listen for some keys and update another component.
My problem is that when pressing keys and updating this one component, all the other buttons will render too (observed through React dev tools for Chrome). I haven't implemented shouldComponentUpdate(nextProps, nextState) on my buttons, but shouldn't React have this behavior by default? I mean, compare this.props with nextProps and if they are exactly the same, do not call render()?
Am I supposed to do this myself for every component that should only render once on application startup?
EDIT: PureComponent seems solve the problem... But instead of creating a new question, I'm updating this one with a related question:
Why wouldn't the documentation recommend to have all components based on PureComponent by default? What are the arguments against using PureComponent by default instead of the typical Component?

A: Pure components should solve your problem because they implement shallow prop and state comparison by default.
Link to the docs.

If your React component's render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

A: One way to make sure a React component is rendered only once, is by making shouldComponentUpdate return false:
class MyComponent extends React.Component {

  shouldComponentUpdate = () => false

  render() {
    return <div>{ this.props.children }</div>;
  }
}

In the example above, even if this.props.children changes, the component won't render again. It will render only once, when mounted.


text:
Q: Problem constructing Association tables with some operators fixed in 10.0.2

First, set up the example Dataset from the documentation:
titanic = ExampleData[{"Dataset", "Titanic"}];

Why does this fail:
titanic[GroupBy[Key@"class"], <| "length" -> Length, "max" -> Max|>, "age"]

(* ... Part age is not applicable to {__Association}  ... *)

yet this re-expression of the query works:
titanic[GroupBy[Key@"class"], All, "age"][All, <| "length" -> Length,
  "max" -> Max|>]

As do these modifications:
titanic[GroupBy[Key@"class"], <| "length" -> Length|>, "age"]

Strangely, Max doesn't work if substituted for Length above (bug?). Finally, this is not desirable but works without new key names:
titanic[GroupBy[Key@"class"], Query[{Length, Max}], "age"]

A: This appears to be another example of the WRI-acknowledged bug described in Possible bug involving Dataset/Query and RightComposition.
In short, the query is being "compiled" into an expression that applies the "age" operator at the wrong level.
Analysis
If we "compile" the query, we can see that the descending "age" operator is being incorrectly applied to the first level of the grouping results instead of being applied two levels below those results:
Dataset`CompileQuery @
  Query[GroupBy[Key@"class"],<|"length"->Length,"max"->Max|>,"age"]

(* ...
   GroupBy[Key[class]] /*
   Map[
     GeneralUtilities`ApplyThrough[<|length->Length,max->Max|>] @*
     GeneralUtilities`Slice[age]
   ]
   ...
*)

The fact that the Length / Max operator is being applied at the same level is also suspicious here, but it is moot given the incorrect results returned by the preceding "age" operator (preceding because of the use of @* within the Map, not /*).
Note the resemblance of the compiled query above to that of the following manifestly incorrect query:
Dataset`CompileQuery @
  Query[GroupBy[Key@"class"], "age"]

(* ...
   GroupBy[Key[class]] /*
   Map[GeneralUtilities`Slice[age]]
   ...
*)

The variation in the question that uses the simpler operator <| "length" -> Length |> does not fail outright, but it does return the incorrect value 2 for all lengths.  The compiled form of this variation once again reveals the application of "age" at the wrong level:
Dataset`CompileQuery @
  Query[GroupBy[Key@"class"],<|"length"->Length|>,"age"]

(* ...
   GroupBy[Key[class]] /*
   Map[
     GeneralUtilities`ApplyThrough[<|length->Length|>] @*
     GeneralUtilities`Slice[age]
   ]
   ...
*)

Workaround
A nested sub-query can be used as a work-around to this problem.  Its compiled form applies the operators at the correct levels and produces the correct results:
Dataset`CompileQuery @
    Query[GroupBy[Key@"class"], Query@<|"length"->Length,"max"->Max|>, "age"]

(* ...
   GroupBy[Key[class]] /*
   Map[
     Map[GeneralUtilities`Slice[age]] /*
     GeneralUtilities`ApplyThrough[<|length->Length,max->Max|>]
   ]
   ...
*)

Note how the "age" operator is now being applied at the proper level: two levels below the grouping and one level below the Length / Max application.  (And also note the subtle switch from @* to /*).

A: The bug here is fairly simple: <| |> is being treated as descending, not ascending like the documentation says.
I've just fixed this, it should show up in 10.0.2.
As WReach has already pointed out, for now you can just force the <| |> operator to be ascending by wrapping it in Query:
 titanic[GroupBy[Key@"class"], Query[<|"length" -> Length, "max" -> Max|>], "age"]

A: This has been fixed in 10.0.2. On windows 7, 64 bit


text:
Q: Woocommerce - show products in search results before everything else Currently I have the following code:
 <?php while ( have_posts() ) : the_post(); ?>

        <?php
            if ( get_post_type() !== 'post' ) {
                if ( get_post_type() == 'landing-pages' ) {
                    get_template_part( 'templates/content/archive', 'landingpages' );
                } elseif ( get_post_type() == 'product' ) {
                    get_template_part( 'templates/content/archive', 'product' );
                } else {
                    get_template_part( 'templates/content/archive', 'cpt' );
                }
            } else {
                get_template_part( 'templates/content/archive', 'posts' );
            };
        ?>

    <?php endwhile; ?>

  <?php get_template_part( 'templates/modules/nav', 'pagination' ); ?>

However, this just displays most recent to oldest. With custom posts, woocommerce products, posts, pages, all mixed togather.
I want only products to be displayed, then once all matching products have been displayed, anything else that matches the search query is returned, eg: other custom post types, pages, and posts.
Any suggestions on how to achieve this?
Thanks.

A: Copy and paste the following code in functions.php file of your theme.
add_filter('posts_orderby','search_sort_custom',10,2);
function search_sort_custom( $orderby, $query )
{
    global $wpdb;

    if(!is_admin() && is_search())
        $orderby =  $wpdb->prefix."posts.post_type DESC, {$wpdb->prefix}posts.post_date DESC";

    return  $orderby;
}


text:
Q: Оператор сравнения == в С++ Как реализовать сравнение двух переменных, чтобы получить значение типа bool, говорящее, равны они или нет.
Что надо изменять? Написал вроде бы правильно, но нет никакой реакции   на p2==p;, нет даже вывода в консоль ни нуля, ни единички.
И как реализовать операторы >, >= и подобные?
#include<stdio.h>
#include<math.h>
#include <iostream>

using namespace std;
class abstact
 {
public:
virtual void input () = 0;
virtual void output () = 0;
virtual void rachet () = 0;

};

class racheti:public abstact
{
private:
    float ksi;
    float speed;
    float alfa;
    float ro;
    float Relson;
    float nu;
    float f;
    float S;
    float test;
public:
    friend bool operator==(racheti &a, racheti &b);
      void input()
    {
        ro=1.29;
        speed=8;
        alfa=1e-3;
        nu=1.73e-5;
        cout << "S =";
        cin  >> S;
    }
    void output()
    {
        cout << "F = " << f << " Relson = " << Relson << " S = " << S << " KSI = "<< ksi << endl;
    }
    void rachet()
    {
        Relson=(speed*alfa*ro)/nu;

        if(Relson<=2)
        {
            ksi=24/Relson;
        }
        else if(Relson>2 && Relson<=500)
        {
            ksi=18.5/(pow(Relson,0.6));
        }
        else if(Relson>500){ksi = 0.44;}

        f=ksi*S*((ro*pow(speed,2))/2);

    }

};
int main()
{
    int a;
   abstact *p = new racheti; // * В покажчик р на базовий клас заноситься адреса, виділена під об'єкт похідного класу crug * /
    p ->input();
    p ->rachet();
    p ->output();
    cout << endl;
    abstact *p2 = new racheti;
    p2 ->input();
    p2 ->rachet();
    p2 ->output();

    p2==p;

    return 0;
}
bool operator==(racheti &a, racheti &b)
    {
        if(a==b)
          return 1;
        else return 0;
    }

A: Что? Требуется сравнить a и b? Нет вопросов! Смотрим типы... ага! вот он, оператор сравнения a и b! Поехали...
bool operator==(racheti &a, racheti &b)
{
    if(a==b) return 1;

Что? Требуется сравнить a и b? Нет вопросов! Смотрим типы... ага! Вот он -
bool operator==(racheti &a, racheti &b)
{
    if(a==b) return 1;

Что? Требуется сравнить a и b? Нет вопросов! Смотрим типы... ага! Вот он - ...
Ну, вы поняли, что въехали в бесконечную рекурсию?...
А вот если встретится
    if(a.ksi   != b.ksi) return 0;
    if(a.speed != b.speed) return 0;
    ...

то будет примерно так - ага, тут нас просят сравнить два float. Нет вопросов - это встроенный оператор сравнения, вызываем его.


text:
Q: Raman Scattering vs. Fluorescence (1-photon / 2-photon process) I have a question considering the difference between Raman Scattering and fluorescence.
I know that Raman Scataring is a non-resonant process, while fluorescence is resonant, that Raman scattering retains coherence while fluorescence doesnt and that in Raman scattering the photon is "emited" immediatelly while there is some specific time dependent decay in fluorescence. These things are clear.
What is not clear to me is why the Raman Scattering is supposed to be 2-photon process, while fluorescence is 1-photon process (I actually read this in some book that had some kind of Feynman diagrams in it - but no further information). Can someone please explain this? The more detailed explanation, the better :).
Thank you very much.
EDIT !!!
I found the book I was talking about. There is this picture. And it basically says that in case of fluorescence the system goes through a transition state (excited state) at one time - photons interact with bra and ket vector at the same time. While in Raman one photon interacts with bra vector, it is emited and only then the second photon interacts with ket vector (and is once again emited). This is their reasoning for this 1-photon/2-photon stuff.
Do I understand it correctly? And is it even explained well?

A: I think this is a matter of how one defines one's terms, what one means by photon, and that's a slippery business.  I'm assuming that fluorescence here means resonant elastic scattering.  (Otherwise it's hard to see how it can be called a one-photon process.)
In scattering, we usually associate a photon mode with a plane wave having a well-defined frequency and wave vector.   By this definition, fluorescence is a two-photon process.  One photon destroyed, another created. (That's my personally preferred picture.)  Another point of view notes that the frequency of the photon hasn't changed.  The only thing that has changed is the direction.  The incident photon has been re-directed.  When I look at the the way the theory is usually presented in QED, I see two photons.


text:
Q: Why twitter cursor is null? I have some tweet id. I want to get retweeters of this tweet. Therefore, I use this api: https://dev.twitter.com/rest/reference/get/statuses/retweeters/ids.
There is a example of code written with help python 3 and TwitterAPI:
credentials = "credentials.txt"
o = TwitterOAuth.read_file(credentials)
api = TwitterAPI(o.consumer_key, o.consumer_secret, auth_type='oAuth2')

data = api.request('statuses/retweeters/ids', {'id': "370134917713494016", 'count': 100})

My result is:
{"ids":[id1,id2,..id100],"next_cursor":0,"next_cursor_str":"0","previous_cursor":0,"previous_cursor_str":"0"}

I don't understand, why my cursors are null.

A: That's how the API for retweeters works.

While this method supports the cursor parameter, the entire result set can be returned in a single cursored collection. Using the count parameter with this method will not provide segmented cursors for use with this parameter.

You can only get a maximum of 100 users out of it.  So there's no need for a cursor.


text:
Q: Running IIS Application with different user Credentials I have deployed an application on IIS Server and Servlet Exec configured.  I need run the application with windows User Credentials rather than Anonymous User. I tries changing the username and password of annonmous user in properties/Security but the application stops responding changing it back to default Anonymous IIS user account works fine??
Abdul Khaliq

A: If it is on iis 6 or greater, there is a place you can create application pools. If you don't have a dedicated application pool for your application yet, create one. While creating you can set the default identity it should work with. You can set it to system defaults or a custom identity you've created...

A: You should change the identity for the application pool (not the website). So it's best to create a specific application pool for every site which needs specific user credentials.
But this question really belongs on serverfault.com


text:
Q: cloud.speech.v1.StreamingRecognizeResponse - error: an enum switch case label must be the unqualified name of an enumeration constant I made a project in Android Studio with Google Cloud Platform Java sample project from github a year ago. It was working correctly by then but a month ago when I opened the project, I faced the following error:
error: an enum switch case label must be the unqualified name of an enumeration constant

I have checked other solutions on SO,Ex, but on the StreamingRecognizeResponse class I saw the code is written as the solution suggests. Ex:
protected final Object dynamicMethod(
  com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
  Object arg0, Object arg1) {
switch (method) {
  case NEW_MUTABLE_INSTANCE: {
    return new com.google.cloud.speech.v1.StreamingRecognizeResponse();
  }
  case IS_INITIALIZED: {      //**clicking on first error takes to this line.** but it is as solution suggests.
    return DEFAULT_INSTANCE;
  }
  case MAKE_IMMUTABLE: {
    results_.makeImmutable();
    return null;
  }
  case NEW_BUILDER: {
    return new Builder();
  }
  case VISIT: {...
 ...................

I can't compile my project anymore and I need to fix this error.
Any suggestion to solve this problem would help.

A: It is unclear which Java sample you are referring to, but com.google.protobuf enumeration GeneratedMessageLite.MethodToInvoke generally has these constants:
Object dynamicMethod(MethodToInvoke method, Object arg0, Object arg1) {
    switch (method) {
        case GET_DEFAULT_INSTANCE: {
            return DEFAULT_INSTANCE;
        }
        case GET_PARSER: {
            break;
        }
        case IS_INITIALIZED: {
            break;
        }
        case MAKE_IMMUTABLE: {
            results_.makeImmutable();
            return null;
        }
        case MERGE_FROM: {
            break;
        }
        case NEW_BUILDER: {
            return new Builder();
        }
        case NEW_INSTANCE: {
            return new com.google.cloud.speech.v1.StreamingRecognizeResponse();
        }
        case PARSE_PARTIAL_FROM: {
            break;
        }
    }
}

There is no NEW_MUTABLE_INSTANCE and there is no VISIT. One can also list them:
for (GeneratedMessageLite.MethodToInvoke c : GeneratedMessageLite.MethodToInvoke.values()) {
    System.out.println(c);
}

Also see StreamingRecognizeResponse.


text:
Q: Dynamically changing class in v-text-field in default slot I am trying to dynamically change font-size in v-text-field default slot based on the length of the text. However, it seems that v-text-field ignores any specification I specify in the  section.
Here is the code
        <v-text-field
          v-model="attr.name"
          hide-details
          :readonly="true"
          class="core-select"
          label="Core Attribute"
        >
          <template
            v-slot:default
          >
            <div :class="attrNameStyle[0]">
              {{ attr.name }}
            </div>
          </template>
        </v-text-field>

I have verified that attrNameStyle[0] is gets set correctly, however that style never gets applied to the default slot. I can change the way input slot looks via this CSS class .v-text-field__slot input { ... } however, I can't update that CSS dynamically.
Thanks for help!
Edit: Adding more context.
.core-select {
  width: 180px;
}

.short-core-select {
  font-size: 12px;
}

attrNameStyle[0] is set to either '', or 'short-core-select'.

A: Since v-text-field__slot is working, you could edit that CSS from a higher level.
<v-text-field
      v-model="attr.name"
      hide-details
      hide-details
      class="core-select"
      :class="attrNameStyle[0]"
      label="Core Attribute"
    >
      <template>
        <div>
          {{ attr.name }}
        </div>
      </template>
    </v-text-field>

<style>
  .short-core-select .v-text-field__slot {
    font-size: 12px;
  }
</style>


text:
Q: How to pass specific event type to command attribute of Tkinter widget? I would like to define a callback taking different action according to different Radiobutton selected.
In the following code, I used a callback function to print the value of selected Radiobutton as well as the index in list of Radiobutton. After execution, I found IntVar() was updated after invocation of callback function, and the previous value is printed.
import Tkinter as tk

def RadioChange(event):
    print(radiovalue.get())
    print(radios.index(event.widget))

root = tk.Tk()

radiovalue = tk.IntVar()
radios = []
for i in range(3):
    radios.append(tk.Radiobutton(root,text="Option {}".format(i),variable=radiovalue,value=i))
    radios[i].bind("<Button-3>",RadioChange)
    radios[i].pack()

root.mainloop()

If I used command attribute to print the value of selected Radiobutton, it worked well.(in the following code)
import Tkinter as tk

def RadioChange():
    print(radiovalue.get())

root = tk.Tk()

radiovalue = tk.IntVar()
radios = []
for i in range(3):
    radios.append(tk.Radiobutton(root,text="Option {}".format(i),variable=radiovalue,value=i))
    radios[i].configure(command=RadioChange)
    radios[i].pack()

root.mainloop()

In the practice of using bind, I can bind specific event to callback function but print wrong value. In the practice of using command attribute, I can print correct value but can't assign other event except left-button-click. My question is: Is it possible to pass desired event to command attribute in order to get correct value as well as handling desired event? Or there are other solutions, such as make callback using bind() get correct value?


text:
Q: I want to authenticate HOST users inside a docker container Is there a way to authenticate the host os users from docker container ?
Bind mapping the passwd , shadow and pam.d file make it work.
for example :
-v /etc/pam.d:/etc/pam.d
-v /etc/passwd:/etc/passwd
-v /etc/shadow:/etc/shadow
But is there any other feature / way in Docker which makes this possible without doing bind mapping?

A: Anyone who can run Docker commands is root, so it doesn't matter.  As a corollary, if you need to make decisions based on the calling host user, you almost certainly don't want your tool packaged in a Docker image.
Put another way: if I can use docker run -v to bind-mount the host's /etc/shadow into a container for authentication purposes, then I can also docker run -u root -v /:/host ubuntu sh and make whatever changes I want to /host/etc/passwd, steal and decrypt the root password from /host/etc/shadow, add myself to /host/etc/sudoers, and so on.


text:
Q: execution of stored procedure :PL000103 error I am trying to execute a stored procedure which is already present in the schema.
After repeated attempts I am unable to make my query run as I am facing the following error:
Error report -
ORA-06550: line 2, column 2:
PLS-00103: Encountered the symbol " " when expecting one of the following:

   begin function pragma procedure subtype type <an identifier>
   <a double-quoted delimited-identifier> current cursor delete
   exists prior
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

This is what I trying to execute :
SET SERVEROUTPUT ON

DECLARE
   P_RESULT_OUT      SYS_REFCURSOR;
   P_ERRORCODE_OUT   NUMBER;
   P_ERRORMSG_OUT    VARCHAR2 (2000);
BEGIN
   NKADM.BSCS_USAGE_QUERY_PKG.ZKSA_BILLED_USAGE_QUERY_SP ('CUST0000000763',
                                                          NULL,
                                                          NULL,
                                                          'ALL',
                                                          '20-04-2018',
                                                          '01-05-2018',
                                                          P_RESULT_OUT,
                                                          P_ERRORCODE_OUT,
                                                          P_ERRORMSG_OUT);
   DBMS_OUTPUT.PUT_LINE (P_ERRORCODE_OUT || '::' || P_ERRORMSG_OUT);
END;
/


text:
Q: Can I use httprequest to post a file automatically, in the same way I might with a regular upload? I'm stuck on something that (I think) should be quite simple, but I can't work out how to do it. I can't find any information either here on SO or on Google.
We have a web app that takes data from our site and automatically POSTS this to another API.
We'd like to send over a binary file also - for example, we'd grab the file from a local URL and POST it's contents over to the other site.
Could anybody point me in the right direction for this?  For example, would I need to embed the file URL in the data somehow and POST as multipart/form-data?

A: I created these Classic ASP function to POST a file to another server. Hopefully it will help you too.
Function PostDocument(intDocumentID, binFile, strFilename, strContentType)
Dim objHttp, strBoundary, strRequestStart, strRequestEnd, binPost
Dim objStream

strBoundary = "---------------------------9849436581144108930470211272"

Set objHttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")

strRequestStart = "--" & strBoundary & vbCrlf &_
    "Content-Disposition: form-data; name=""id""" & vbCrlf &_
    vbCrlf &_
    intDocumentID & vbCrlf &_
    vbCrlf &_
    "--" & strBoundary & vbCrlf &_
    "Content-Disposition: form-data; name=""file""; filename=""" & strFilename & """" & vbCrlf &_
    "Content-Type: " & strContentType & vbCrlf &_
    vbCrlf

strRequestEnd = vbCrLf & "--" & strBoundary & "--"

Set objStream = Server.CreateObject("ADODB.Stream")

objStream.Type = adTypeBinary '1
objStream.Mode = adModeReadWrite '3
objStream.Open
objStream.Write StringToBinary(strRequestStart)
objStream.Write binFile
objStream.Write StringToBinary(strRequestEnd)
objStream.Position = 0

binPost = objStream.Read

Response.Write binPost

objStream.Close
Set objStream = Nothing

objHttp.Open "POST", "(url removed)", False, "(username removed)", "(password removed)"
objHttp.setRequestHeader "Content-Type", "multipart/form-data; boundary=""" & strBoundary & """"
objHttp.Send binPost

PostDocument = objHttp.ResponseText

Set objHttp = Nothing
End Function

Function StringToBinary(toConvert)
Dim objStream, data

Set objStream = Server.CreateObject("ADODB.Stream")

objStream.Charset = "ISO-8859-1"
objStream.Type = adTypeText '2
objStream.Mode = adModeReadWrite '3
objStream.Open
objStream.WriteText toConvert

objStream.Position = 0
objStream.Type = adTypeBinary '1
StringToBinary = objStream.Read

objStream.Close
Set objStream = Nothing
End Function


text:
Q: Ocaml comparison not working I am trying to write a simple server program in Ocaml that communicates with other processes via a socket. I currently have a problem that the strings the server reads (with input_line ic) do not seem to compare with other strings properly. For example, I run the server program and use telnet to connect to it, if I send "end" as a line, the server program trys to match with "end", but this doesn't work as expected. The function that handles communication is service (below), which is called to handle a client as part of a forking server (something like the double fork treatment here).
let service ic oc
    try while true do
        let instr = input_line ic in
        match instr with
        | "end" -> print_endline "matching end" (* this never runs *)
        | _ -> output_string oc ((String.uppercase instr) ^ "\n") ; flush oc
    done
    with End_of_file -> print_endline "Input stream ended."
;;

In fact, if I do print_endline (string_of_bool ("end" = instr)) I always get false (even when I send "end" via telnet). To try and get some sense of what is going I printed out the result of different comparison operations between the let-binding and the try block:
print_endline instr ;
print_endline "end" ;
print_endline (string_of_bool ("end" = instr)) ;
print_endline (string_of_bool ("end" == instr)) ;
print_endline (string_of_int (String.compare "end" instr)) ;

When I send "end" the server now prints out

end
end
false
false
-1

I'm really lost as to what could be going on - I presume it must be something about getting the instr via reading from a socket, as usually you can compare strings just fine.
I don't think I actually had a question in all that background so here are a few variants that could work:

*

*What am I doing wrong?

*Why can't I test the input in order to take different actions?

*Is this a bug in Ocaml?

*Do you need the complete source to figure this out?

A: My guess is that there are carriage returns in the strings coming in from telnet. As I recall, the old protocols tend to send CRLF at the ends of lines.
You might try printing the string out using String.escaped.
It's pretty unlikely you're seeing a bug in OCaml.


text:
Q: Q: How to change the parallelism value only in the case of master branch?(CircleCI2.0) I use CircleCI2.0 in my rails app.
I want to change the parallelism value only when master branch.
so I set the circleci/config.yml like below.
but it doesn't work. just Error occured.
It's possible to adjust Parallelism for the particular branch?
please give me any hint or advise.
thanks.
 version: 2
 jobs:
   build:
    if [ $CIRCLE_BRANCH = "master" ]; then
      parallelism: 2
    else
      parallelism: 8
    fi

A: disclaimer: Developer Evangelist at CircleCI
No, not really. The way you're trying to do it cannot be done and the simplest answer is that you can't do it.
What you can do as a workaround, and use CircleCI Workflows and duplicate the job. Then, with filters, have one version of it run only with master and 2x parallelism and the other run for all branches other than master with 8x parallelism.
This is going to cause some redundant lines in the YAML though. Much of which you can deduplicate using YAML anchors.


text:
Q: Server.HtmlEncode vs Encoder.HtmlEncode I have the below code in my MVC application.
 text = Server.HtmlEncode(text);
 text=Encoder.HtmlEncode(text);

what is the difference will do if I use AntiXSS library here?
I passed the value     <script>alert("strek")</script>
to the variable text it returns the same output for both the cases. Where it will make difference?

A: As seen here, Server.HtmlEncode(text) uses a instance of System.Web.HttpServerUtility while AntiXSS' Encoder.HtmlEncode(text) is static.


text:
Q: Removing isolated nodes in order to make the graph connected I have a graph that is not connected.
import json
import networkx as nx
from networkx.readwrite import json_graph

G = nx.read_gml('/Users/luca/Desktop/networks_analysis/astro-ph/astro-ph.gml')

print(nx.info(G))
Name:
Type: Graph
Number of nodes: 16706
Number of edges: 121251
Average degree:  14.5159

nx.is_connected(G)
False

I tried to remove all isolated nodes but the graph still remain non-connected.
G.remove_nodes_from(list(nx.isolates(G)))

print(nx.info(G))
Name:
Type: Graph
Number of nodes: 16046
Number of edges: 121251
Average degree:  15.1129

nx.is_connected(G)
False

How can I obtain a connected graph?
Thank you.

A: You can get the largest connected subgraph with:
nodes = max(nx.connected_components(G), key=len)
H = nx.subgraph(G, nodes)


text:
Q: How can I separate access within a network? I am struggling to find a 'rule' in my router that separates access to different wired computers.
I have fibre coming into the building that links via Ethernet cable to a zyxel router. From this I have Ethernet to an 8 port switch which on turn attaches 4 computers and 2 printers together with full shared access to all systems attached to it.
What I want is to put in a second router/ switch that can have up to 5 other devices attached wired to it. Problem is I don't want these other devices to be able to access the original computers on the network OR be able to use the 2 printers.

A: What you need is a Firewall. A firewall is really a function. Now, a router can have firewall functionality, but to see if that is the case, you should mention the model of router, and you and others can check the manual of that router and see if it is possible. If it doesn't and it may not, then you could get a Firewall appliance or a router that has that functionality. A firewall would let you set rules like block incoming and/or outgoing connections to this range of ip addresses.
Also, particular recommendations are unpopular here, or popular but not accepted, they call it "shopping". But, you could try asking in the chat for what people use/suggest.

A: There are a few ways of solving this problem - One would be
Internet
    |
   Xyxel
    |
    +---  New Network PC1
    |
    +---  New Network PC 2.5 ... (You may need a switch for more ports)
    |
    +------ (wan) Ethernet Router
                    |
                   8 Port Switch
                    |
                    +----- (lan) Printer
                    |
                    +----- (lan) Printer 2
                    |
                    +----- (lan) Existing PC 1 ...
This will allow your existing network to access the devices of the new network, but not the other way around, assuming the Ethernet Router is configured to do NAT.  Note that you will have to ensure the LAN IP addressess for the Ethernet router are in a different subnet to the IP Addresses handed out by the Xyxel.  (If the Xyxel hands out 192.168.x.x, you could set the Ethernet Router up to use 172.16.x.x).   There is a minor issue you need to be aware of of "double NAT", which might cause problems with some obscure protcols.
A "Better" solution requires 2 ethernet routers and might look as follows:
                  Internet
                    |
                  XYXEL Router
                    +      +
       -------------+      +------------------------
       |                                           |
 Ethernet Router 1                             Ethernet Router 2
 |                                              |
 |---  Printer 1                                |--- New PC1
 |---  Printer 2                                |--- New PC2
 |---  (rest of old network)                    |--- New PC3...

You may need a switch or 2 to extend the number of ports available on the ethernet router(s) - just make sure you don't run a cable between Ethernet Router 1 and Ethernet Router 2.
This second solution is a "better" solution then the first as it does not require double nat, and is more secure (ie separate zones).    You need to be mindful that the IP range on the LAN Interface on Ethernet Router 1 and (and Ethernet Router 2) are different to the LAN interface on the Zyxel, ideally using 3 different networks [ but strictly speaking you can use the same ranges on the LAN interfaces of Ethernet Router 1 and 2 ].  I'd recommend
192.168.1.x netmask 255.255.255.0 for the Zyxel
10.1.1.x    netmask 255.255.255.0 for Ethernet Router 1
10.1.2.x    netmask 255.255.255.0 for Ethernet Router 2
In each case, the "gateway" (or LAN interface on the router should be X.X.X.1 or X.X.X.254 (for example 192.168.1.1 or 10.1.2.254)
An Ethernet router is quite a cheap device and I'd imagine you can pick them up for around $50.


text:
Q: Linq expression tree string comparison I am trying to construct an expression tree to operate against a string array.  I need to figure out how to use the Equal method.
Could anyone give me an example of
1) using the Expression.Equal (or .Equals) method to compare a string to a constant, and
2) using an Expression of whatever sort to use the string.Contains() method for filtering purposes.
I am trying to learn the Expression Tree mechanics, but as of yet, I have not found a good tutorial.  I greatly appreciate your help.
string[] arr = {"s1","s2","s3"};
IQueryable<String> queryableData = arr.AsQueryable<string>();

// what should go below here?
ParameterExpression p1 = Expression.Parameter(typeof(string), "c");
Expression left = Expression.Constant("s2");
Expression e1 = Expression.Equal(left, p1);

IQueryable<string> res = queryableData.Provider.CreateQuery<string>(e2);

A: Aaah, I see what you are asking... And you're really entering some very murky waters, one of the few areas that the .NET reflection libraries aren't beautiful to work with. You have to create a call expression to call Queryable.Where() on the queryableData object, and create a new query using that expression... The problem is that getting a generic version of a method in .NET isn't necessarily the easiest thing you've ever run across in your life:
MethodCallExpression call = Expression.Call(
    null, // Calling Queryable.Where(), extension method, not instance method
    getGenericMethod<string>(typeof(Queryable), "Where", typeof(IQueryable<string>), typeof(Expression<Func<string,bool>>)),
    Expression.Constant(queryableData),
    Expression.Lamda(
       e1,
       p1)
);
IQueryable<string> res = queryableData.Provider.CreateQuery<string>(call);

You would also have to define getGenericMethod (you can find better implementations for this online at other places, this is really quite a simple approach):
private static MethodInfo getGenericMethod<T>(Type type, string name, params Type[] paramTypes)
{
    MethodInfo[] methods = type.GetMethods(name);
    foreach(MethodInfo mi in methods)
    {
        if(!mi.IsGenericMethodDefinition) // or some similar property
            continue;
        if(mi.GetGenericArguments().Length != 1)
            continue;
        if(mi.GetParameters().Length != paramTypes.Length)
            continue;

        MethodInfo genMethod = mi.MakeGenericMethod(new Type[]{typeof(T)});
        var ps = genMethod.GetParameters();
        bool isGood = true;
        for(int i = 0; i < ps.Length; i++)
        {
            if(ps[i].ParameterType != paramTypes[i])
            {
               isGood = false;
               break;
            }
        }

        if(isGood)
            return genMethod;

    }

    return null;
}

There are almost undoubtedly a few errors in there, but I hope you can see where to go from there...

A: Just to give my solution:
string[] arr = {"s1","s2","s3"};
IQueryable<String> queryableData = arr.AsQueryable<string>();
ParameterExpression pe = Expression.Parameter(typeof(string), "company");
Expression right = Expression.Constant("on");
Expression left = Expression.Call(pe, typeof(string).GetMethod("Contains"), right);
MethodCallExpression e2 = Expression.Call(
            typeof(Queryable),
            "Where",
            new Type[] { queryableData.ElementType },
            queryableData.Expression,
            Expression.Lambda<Func<string, bool>>(left, new ParameterExpression[] { pe }));

IQueryable<string> res = queryableData.Provider.CreateQuery<string>(e2);


text:
Q: How to execute js in selenium? Selenium WebDriver Java
Anyone knows how to execute this script js.executeScript("window.addEventListener('load',function(){document.getElementsByTagName('script')[1].src='google.com'})");
or
js.executeScript("window.load = function()
{document.getElementsByTagName('script')[1].src='google.com'})");

This script return null.
Eclipse says: Exception in thread "main" java.lang.NullPointerException
    at autotesting.itacademy.main(itacademy.java:58)
The main code here it is:
package autotesting;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

//for read and write from file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;

public class itacademy {

     private static WebDriver driver = null;

     public static JavascriptExecutor js = (JavascriptExecutor) driver;

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        JavascriptExecutor js = (JavascriptExecutor) driver;

        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://office.co.uk/");

        js.executeScript("window.addEventListener('load',function(){document.getElementsByTagName('script')[1].src='google.com'})");
            }}

Thanks in advance

A: You never initialize your JavascriptExecutor. Look here, you assign driver as null, then try to cast it to JavascriptExecutor and never initialize it:
private static WebDriver driver = null; // driver is null
public static JavascriptExecutor js = (JavascriptExecutor) driver; // js is null

Later, you assign js to driver and then initialize your driver object, here:
JavascriptExecutor js = (JavascriptExecutor) driver; // js is null
driver = new FirefoxDriver(); // driver is now an object

But by the time you do anything with js, it's still null:
js.executeScript("window.addEventListener('load',function({document.getElementsByTagName('script')[1].src='google.com'})"); // It's still null here!

You need to properly initialize your js object. By the way, you've already declared js as a class member, why are you reassigning it immediately in main?
public static JavascriptExecutor js = (JavascriptExecutor) driver;
JavascriptExecutor js = (JavascriptExecutor) driver; //  This line is unnecessary in main


text:
Q: Creating UITableView in init failed I'm trying the following in Xcode 4.3.2. I've created a single view application. My ViewController implements UITableViewDelegate, UITableViewDataSource.
In ViewController.m:
UITableView *tv = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, 120, 100)
                                               style:UITableViewStylePlain];
tv.delegate = self;
tv.dataSource = self;

[self.view addSubview:tv];

I implemented numberOfSectionsInTableView, numberOfRowsInSection, cellForRowAtIndexPath and didSelectRowAtIndexPath. It works fine, and displays "welcome" in two rows. But If i place the UITableView creation in the init, then it is not working.
- (id)init
{
    self = [super init];
    if (self) {
        UITableView *tv = [[UITableView alloc] initWithFrame:
            CGRectMake(0, 10, 120, 100) style:UITableViewStylePlain];
        tv.delegate = self;
        tv.dataSource = self;
        [self.view addSubview:tv];
    }

    return self;
}

A: Two things:

*

*if you're loading from a xib file or storyboard, the initializer used is initWithCoder:.

*the view controller's views are not loaded until they're needed, which means viewDidLoad: rather than any init... method.  (Though, viewDidLoad: is triggered by a reference to the view property.)


text:
Q: Get-Aduser in Powershell cutting off fields I know its out there but can 't seem to get it right, this Get-Aduser command is getting the info  need but cutting out fields sometimes(giving me the "...") What am I doing wrong? thx
Get-ADUser -f * -Properties *|
    where {$_.enabled -eq $true} |
    ft Name,EmailAddress,*Phone,*Title,GivenName,Surname,Department > D:\UtilityFiles\AD\users.csv

A: Helps you getting the data to the file without cut
Get-ADUser -f * -Properties *| where {$_.enabled -eq $true} |select-object Name,EmailAddress,*Phone,*Title,GivenName,Surname,Department | export-csv -path D:\UtilityFiles\AD\users.csv  -notypeinformation


text:
Q: Material-UI Call function when clearing autocomplete textfield I'm using a material-ui autocomplete text field to filter a list and I want to be able to repopulate the list to its full form when the text is deleted and enter is hit. As far as I can tell the onNewRequest property is only called if there is text in the text field. Is there a way to call a function when pressing enter with no text?

A: You can use the onUpdateInput event of the AutoComplete component to test if the text field is empty:
<AutoComplete
  ...
  onUpdateInput={
    (value) => {
      if (value.length === 0) {
        console.log('Refresh the list here');
      }
    }
  }
/>


text:
Q: Securing API calls from cross domain using RESTful service I have a booking site from where I provide a few lines of code to the user where I add API key in a div along with the code. The users are required to add these codes in their website. Then I load the view from my site over their site using ajax calls. My concern is: How can I make these calls secure using public and private API Key with restful web services using codeIgniter?
My code provided to user looks like
    <link rel="stylesheet" type="text/css" href="http://localhost/bookingpoints_com/apiTesting/styles/first.css" />

By these lines of code I make an ajax call to my site and render the view on users site. How could I make it work like google's client and secret key structure with authentication using restful services using pure API architecture?

A:
Ajax requests can be emulated by creating the
  proper headers. If you want to have a basic check to see if the
  request is an Ajax request you can use:
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {  //Request
  identified as ajax request }, However you should never base your
  security on this check. It will eliminate direct accesses to the page
  if that is what you need.

But this is not enough, you have to secure your Ajax call using server side scripting(e.g. PHP). For example, if your AJAX passes the key to the PHP file, write code in the PHP file to make sure that is the correct key.

A: Facebook, Google and other large companies uses iframe for these kind of services.
Take example of facebook it gives you on script to put in code which when runs will create an iframe for particular view.
Also you can not make cross-site ajax calls. Only iframe which is loaded from your site can securely load the page.
Now with the keys, you can always provide public key in script. The iframe href will point to you website with $_SERVER['http_referer'] where you can make sure the api key is authorized. Don't use private key unless you are not going to post any private confidential data.

A: I wrote an article awhile back on securing REST APIs, specifically those consumed by a browser. I recommend taking a look https://www.moesif.com/blog/technical/restful-apis/Authorization-on-RESTful-APIs/
Auth0, an authentication provider has quite a few resources also, I have no affiliation other than used them before and like their product.
Many APIs are secured through JWTs which are nice since they allow you to authenticate an API call without centralized auth servers. They are based on public/private crypto algorithms where the two keys are mathematically related. The keys are generated in a trusted environment such as your server, but anyone can verify that they come from who they say they did. You can design other authentication token schemes.
Depending on what you need, the keys will be accessible by any client, so you can design a specific permissions model to ensure the key has the rights of least privilege (i.e. they shouldn't have admin rights, etc)


text:
Q: Terminate debug on device I'm a bit confused about debugging on a device.
When I use the emulator, after the debug session, I simply close the emulator window...
but when debugging on my device, how can I close the session??simply disconnecting the USB cable?
And the installed .apk ( installed by Eclipse ) should be removed manually?

A: You can do this by going to the Debug perspective, right clicking your application, and selecting "Disconnect" or "Terminate".

A: As soon as you disconnect, the debug session is terminated.
Any APKs installed during debugging must be removed manually, since technically they're not part of the debugging process.


text:
Q: WP8 Network Share API For desktop apps, I've used the following to access network shares:
    [DllImport("mpr.dll")]
    private static extern int WNetAddConnection2(NetResource netResource,
        string password, string username, int flags);

    [DllImport("mpr.dll")]
    private static extern int WNetCancelConnection2(string name, int flags,
        bool force);

Are there similar APIs available on WP8 SDK?

A: No. Windows phone doesn't support network shares. It's not the same as full windows. There is not dllimport or access to native Apis

A: I don't think this is possible either. Plus I'm sure you don't want to build a small server to serve up files and folders from the targeted computer... but you can do something similar to what the app "Easy Transfer" (http://www.windowsphone.com/en-us/store/app/easy-transfer/5ccb6655-2ff9-4977-bf8b-577e92bbb236) did and build the app to act as the server.