text:
Q: Pandas binning and sum using custom bins, on categorical columns I want to change my source dataframe to output df output dataframe. Here i'm creating the load column based on min and max of the load column from the source dataframe and create equally spaced bins based on user input. Then i need to sum all the fees values falling between the load values.
source_df = {'opr_date': {0: Timestamp('2022-02-10 00:00:00'), 1: Timestamp('2022-02-10 00:00:00'), 2: Timestamp('2022-02-10 00:00:00'), 3: Timestamp('2022-02-10 00:00:00'), 4: Timestamp('2022-02-10 00:00:00'), 5: Timestamp('2022-02-10 00:00:00'), 6: Timestamp('2022-02-10 00:00:00'), 7: Timestamp('2022-02-10 00:00:00'), 8: Timestamp('2022-02-10 00:00:00'), 9: Timestamp('2022-02-10 00:00:00'), 10: Timestamp('2022-02-10 00:00:00'), 11: Timestamp('2022-02-10 00:00:00'), 12: Timestamp('2022-02-10 00:00:00'), 13: Timestamp('2022-02-10 00:00:00'), 14: Timestamp('2022-02-10 00:00:00'), 15: Timestamp('2022-02-10 00:00:00'), 16: Timestamp('2022-02-10 00:00:00'), 17: Timestamp('2022-02-10 00:00:00'), 18: Timestamp('2022-02-10 00:00:00'), 19: Timestamp('2022-02-10 00:00:00')}, 'opr_hour': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10, 10: 1, 11: 2, 12: 3, 13: 4, 14: 5, 15: 6, 16: 7, 17: 8, 18: 9, 19: 10}, 'market_region': {0: 'Russia', 1: 'Russia', 2: 'Russia', 3: 'Russia', 4: 'Russia', 5: 'Russia', 6: 'Russia', 7: 'Russia', 8: 'Russia', 9: 'Russia', 10: 'USA', 11: 'USA', 12: 'USA', 13: 'USA', 14: 'USA', 15: 'USA', 16: 'USA', 17: 'USA', 18: 'USA', 19: 'USA'}, 'load': {0: 2606.81, 1: 2606.06, 2: 2579.74, 3: 2534.2, 4: 2496.76, 5: 2436.67, 6: 2351.03, 7: 2262.96, 8: 2164.84, 9: 2130.44, 10: 1380.42, 11: 1364.75, 12: 1346.12, 13: 1343.49, 14: 1320.89, 15: 1271.92, 16: 1261.05, 17: 1263.54, 18: 1284.43, 19: 1374.74}, 'fees': {0: -4.165, 1: -2.665, 2: -1.996, 3: -5.45, 4: -2.773, 5: -3.784, 6: -0.988, 7: -2.894, 8: -2.092, 9: 1.104, 10: -4.165, 11: -2.665, 12: -1.996, 13: -5.45, 14: -2.773, 15: -3.784, 16: -0.988, 17: -2.894, 18: -2.092, 19: 1.104}}

output_df = {'opr_date': {0: Timestamp('2022-02-10 00:00:00'), 1: Timestamp('2022-02-10 00:00:00'), 2: Timestamp('2022-02-10 00:00:00'), 3: Timestamp('2022-02-10 00:00:00'), 4: Timestamp('2022-02-10 00:00:00'), 5: Timestamp('2022-02-10 00:00:00'), 6: Timestamp('2022-02-10 00:00:00'), 7: Timestamp('2022-02-10 00:00:00'), 8: Timestamp('2022-02-10 00:00:00'), 9: Timestamp('2022-02-10 00:00:00')}, 'opr_hour': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}, 'Russia': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0, 6: -0.925, 7: -2.894, 8: -21.82, 9: 0.0}, 'USA': {0: -25.64, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0}, 'load': {0: 1261.05, 1: 1395.0, 2: 1592.0, 3: 1663.0, 4: 1797.0, 5: 1931.0, 6: 2065.0, 7: 2199.0, 8: 2333.0, 9: 2606.81}}

Right now i'm doing it by using a for loop, I create load bins using
bin_size = np.arange(
            start=min_bin_value,
            stop=max_bin_value,
            step=self.bin_size,
            dtype=int,
        )

and then i run a for loop to find the fees value for the bins:
    market_region_list = df["market_region"].unique().tolist()
    region_fees_values = {}
    for region in market_region_list:
        df_copy = df[df["market_region"] == region]
        fees_value = []
        for i in range(0, len(bin_size) - 1):
            # logger.info(bin_size[i])
            fee_values = df_copy[
                (df_copy["load"].astype(int) >= bin_size[i])
                & (df_copy["load"].astype(int) < bin_size[i + 1])
            ][fees].sum()
            fees_value.append(fee_values)
        region_fees_values[region] = fees_value

    df2= pd.DataFrame.from_dict(
                region_fees_values, orient="index"
            ).transpose()
    df2["load"] = pd.Series(bin_size)

In the loop i find all the rows between all the load bins and then sum the fees column and transpose the dataframe and attach the load values at the end, so that all the market_regions have same number of rows.
The code is working fine, but it takes quite a lot of time to process big dataframe, I want to use pandas/numpy vectorisation technique to speed up the process. Let me know if you guys have any faster approach to solve this problem.
I found something which you guys might want to look at Pandas: Bin and Sum

A: Another approach I used to solve is using pd.cut and pd.groupby together, instead of using for loop, which reduced the time by 92%.
I created the custom bin using the numpy:
bins = np.arange(
            start=min_bin_value,
            stop=max_bin_value,
            step=self.bin_size,
            dtype=int,
        )

Then I created a loop for each region and binned the data using pd.cut. And took the sum of fees column after groupby. After that i stored the data in dict format with keys being region and list of fees as values. Created a dataframe and transposed it. and got my desired output_df.
market_region_list = source_df["market_region"].unique().tolist()
region_fees_values = {}
for region in market_region_list:
            df_copy = source_df[source_df["market_region"] == region]
            binned_fees_list = self.get_fees_by_bins(df_copy, bins, region)
            region_fees_values[region] = binned_fees_list

output_df= pd.DataFrame.from_dict(
        region_fees_values, orient="index"
    ).transpose()
output_df["load"] = pd.Series(bins)

def get_fees_by_bins(self, df, bins, region):
        df_copy = df
        new_df = pd.DataFrame()
        new_df[str(region)] = (
            df_copy["fees"]
            .groupby(pd.cut(df_copy["load"], bins=bins))
            .sum()
        )
        new_df = new_df.reset_index()
        new_df = new_df.drop("load", 1)
        return new_df[str(region)].tolist()


text:
Q: Youtube captures user after linking to video from app in iOS (with Sencha) I want to play a Youtube video in/from my Sencha/Phonegap built app in Android and iOS. But it fails on both Android and iOS. I'm using an Ext.XTemplate to dynamically load the youtube video code in the following code sample:
'',

This fails for me: On Android, my video thumbnail displays with a play button, but when I click it it will not play. On iOS my entire card stays blank. I tried several options mentioned here on stackoverflow.
Trying to work around this, I'm linking directly to youtube via a dynamic thumbnail in the same Ext.XTemplate:
'',
'',
'',

The video now loads fine. Android lets me choose to use the browser or the native app. After playing, the back-button lets me return to my app.
However, new issue: In iOS, the video plays, but there is no way to return to my app. I do not have a back button, and from the multitask bar I see that I'm still in my app. Returning to the iOS home screen and starting my app again I still return to the video. I need to actively close the app from the multitask bar and then start it again all over.
How can I fix this? Either playing the video in my app (and it automatically closes after playing) or linking to the video and really leaving the app so I can return to it as well.

A: I know this isn't exactly what you want but I recently did a VideoPlayer plugin for Android that supports YouTube videos.
http://simonmacdonald.blogspot.com/2011/11/video-player-plugin-for-phonegap.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tool or technique to compare and group diffs by similarity I have developed a system that allows visitors to submit typo corrections for my blog. It works by having a small client-side app which then sends unified diffs to a server. Behind that, I have an interface which allows me to see all diffs in a nice graphical way, sort them, etc.
However I am thinking that as time passes, many visitors will submit corrections for the same things before I have time to fix them. So I would need a way to group similar or identical diffs together.
Identical diffs are easy enough. But there might be people who fix errors differently, e.g. using American or British spellings, different rules for punctuation, varying understandings of unclear phrases, that kind of thing. Grouping similar diffs would be tremendously helpful.
Are there techniques, algorithms, or tools that are specifically designed or can be used to compute the similarity of diffs?

A: I believe that you have two problems to solve: 1. recognizing fixes for the same text (e.g. same typo location), 2. potentially remove those with the same or nearly equal solutions and at least group all the patches that are related to that location.
Problem 1. The unified diff format is somewhat OK as it gives the lines, but a word level or character level diff (for example, counting each word as a line as wdiff does) might be more precise and help you group more precisely the patches.
Problem 2. if the patches are identical, as you noted it is trivial, if they are different, solving the problem 1 already did much of the work. You can of course use a normalization such as "inflected word parts removal" (removing 's', 'ing' and so on at end of words for example) or "lower casing" before the comparison the replacements part in the unified diffs, thus helping group together nearly identical solutions.
The problem 1 is the problem paused by integration or merge of patches. Problem 2 is more relevant to your particular case.

A: Maybe you could adopt the Damerau-Levenshtein algorithm. It is used to calculate the distance between two strings.


text:
Q: hsqldb supporting oracle functions like listagg I came across few of the challenges while writing testcase's using hsqldb.i tried to test oracle function's like (Wm_concat,Listagg,Decode,over) i am getting error like unexpected token found In my research work i found below statement to support oracle function
SET DATABASE SQL SYNTAX ORA  TRUE ; but that did not help I would appreciate if any one help me getting a solution for this Thks

A: SET DATABASE SQL SYNTAX ORA TRUE only makes HSQL accept Oracle's SQL syntax.  It doesn't supply Oracle functions.
If you want to test things dependent on Oracle functions, you really need to test them in an Oracle database.


text:
Q: GAN Generator output layer is [way] out of target range - potentially due to loss func The TL;DR is that my G(z) (z is normal distributed noise) is way out of the expected range. Picture - see comparison of real against generated data.
(It's also a terrible model, being just a few dense layers - but I can sort that later!)
I've thrown s**t at the wall for the past week to see what sticks and now it's time to ask for an informed opinion! :)

*

*Has anyone else encountered this problem before? Suggested fixes?

*What is your generic loss function for your regressive Generator (with a categorical discriminator)?

As it's a regression problem (with target data normalised between 0 & 1) my G output has a linear activation. However, I'm trying to follow Soumith's GAN Hacks to get it working, where we're conflicting over the activation - he says it should be tanh. One could assume with my expected target range I could choose sigmoid, but as I say, I infer this should be linear as a regressive problem to solve. Opinions?
Plus there isn't much clarity on the loss function. He Says:-

In GAN papers, the loss function to optimize G is min (log 1-D), but in practice folks practically use max log D

Does this mean one should aim to minimise the error log(1-D), or pick the minimum of log(1-D)? Similarly  with max log(D). (I'm using class definitions of true/false, so a maximum and minimum from the can be chosen from the two classes.)
In the Goodfellow et. al  2014 paper on GANs, I can see how some of the loss function for the Discriminator resolves to 0 when applied to the Generator. However, I'm obviously missing something, as the equation states I should take log(D(x)) which will sooner or later hit a NaN.
Clarification about my confused state is thanked many times in advance.

Update:
This tutorial on O'Reilly says

Take a look at the last line of our discriminator: there's no softmax or sigmoid layer at the end. GANs can fail if their discriminators "saturate," or become confident enough to return exactly 0 when they're given a generated image; that leaves the discriminator without a useful gradient to descend.

Which sounds a little like my problem, especially as I was using Softmax. Using no activation doesn't solve the problem, but does make my GAN compete in interesting new ways!


text:
Q: How to use Sitefinity without Themes? We are building a site, and have no interest in creating multiple themes.  We intend to simply use plain old CSS and XHTML markup.
Is there any reasonable way to discard the notion of themes from Sitefinity?  Or is our best bet to just simply create a single, minimalistic theme and leave it at that?

A: Create a main theme (~/App_Themes/Default) and then leave the directory empty.  You'll still be applying a theme to your Sitefinity pages & templates, but the theme won't have any CSS files associated with it, therefore it will be the same as having no theme.
Hopefully this helps.


text:
Q: AWS RDS event subscription with lambda in another account I am trying to get lambda in another account to get it invoked by RDS instance event notifications.
RDS event subscription is set to invoke SNS topic which triggers lambda in other account.
I have setup an entire stack using cloudformation. Things I achieved so far are

*

*RDS events are able to invoke SNS topic, I have tested it using creating email subscription to SNS topic

*SNS topic is able to trigger lambda in another account. I have tested it using publish messages in SNS topic. I can see that is flowing through in cloudwatch logs.

Part I am not able to get working is, RDS events triggering SNS and then Lamba in other account. Its very strage as individual bits are working fine but not end to end. Other observation is status of the SNS subscription in RDS events is shown as Active and I can see subscription log in lambda but nothing happens after I reboot RDS instance to test.
Also, I see this bizzare behaviour that subscription status is set to Null.

I followed below links for reference
https://jimmythompson.co.uk/blog/sns-and-lambda/
https://medium.com/pablo-perez/infrastructure-as-a-code-should-not-be-imperative-43d9a64e3998
Is there something I am missing? Any help is much appreciated.


text:
Q: Overriding a constant in a module I'm using the Python Pygatt module (https://github.com/ampledata/pygatt/tree/master/pygatt).
The classes.py file imports pygatt.constants which sets a few constants. I cannot figure out how to override these constants in my file foo.py I've tried:
import pygatt

pygat.classes.pygatt.constants.DEFAULT_CONNECT_TIMEOUT_S = 8

But it doesn't work. I'm very confused and it's probably something dumb that I'm doing. Your help would be appreciated!

A: try this:
from pygatt.classes import pygatt
pygatt.constants.DEFAULT_CONNECT_TIMEOUT_S = 8


text:
Q: Condensation points I've shown previously that in a separable metric space the set condensation points has no isolation points and is perfect. In a separable metric space $\left(X,d\right)$, the set of condensation points of $X$ is denoted as $\operatorname{cond}\left(X\right)$. How can I show that $\operatorname{cond}\left(\operatorname{cond}\left(X\right)\right)=\operatorname{cond}\left(X\right)$?

A: A separable metric space is  hereditarily  Lindelof.
Suppose (by way of contradiction) that $p\in cond(X)\setminus cond(cond(X)).$ Let  $U$ be open with $p\in U$.
For brevity let $S= U\setminus cond(X).$ For $y\in S$ let $y\in  B(y)\subset U$ where $B(y)$ is open and countable.  Now $\{B(y)\cap S:y\in S\}$ is a countable open cover of the Lindelof sub$space$ $S$, so there exists countable $T\subset S$ such that $\cup \{B(y):y\in T\}\supset S.$  Therefore $S=U\cap S$ is  countable ( because $S$ is a  subset of the countable set $\cup \{B(y):y\in T\}$).
Now $U$ is uncountable because $p\in cond(X)$, and $U =(U \setminus S)\cup (U\cap S),$ with $U\cap S$ countable. So $U\setminus S=U\setminus (U\setminus cond (S))=U\cap cond(S)$ is uncountable. But this means that any open $U$ containing   $p$ has uncountable intersection with $cond(X),$ so $p\in cond(cond(X)),$ a contradiction.
We conclude that $cond(X)\subset cond(cond (X)).$ The reverse inclusion $cond(X)\supset cond(cond(X)$ is easy and I leave it to you.
Remark: If $(X,d)$ is a separable metric space and $D$ is a countable dense subset of $X$ then $B=\{B_d(x,q):x\in D\} \land q\in \Bbb Q^+\}$ is a countable base (basis) for $X,$ so $X$ is Lindelof. And if $Y$ is a subspace of $X$ then $\{b\cap Y:b\in B\}$ is a countable base for $Y,$ so $Y$ is also Lindelof.


text:
Q: Scatter plot combined with line chart I am doing a compensation plot
I need to make a line chart with 30 grades, each having a min and max.(low and high salary within that range) On top of that, I need to plot specific employees within the grade.
The x axis are the 30 grades, the Y axis are the wages min and max overall.
I can do a line graph which is fine for the first part and I can do a scatter plot which looks fine for the second part but when I try to do a combo to combine both, I get garbage.
Been working on this since yesterday. I don't need a secondary axis (I don't think)

A: You can use a stacked column chart to define your ranges.  Then overlay an XY/Scatter chart for each employee to show their position.  For this solution, you'll want the XY/Scatter to plot to a secondary axis to better control the formatting.


text:
Q: Problem with the task. Write a program that determines and prints those numbers that are divisible by 3 among the entered numbers I have a problem with the task. Firstly here are some guidelines for the task.
Input of program: A natural number is loaded from the standard input first n and then n natural numbers each in a new line.
Output of program:All loaded numbers divisible by 3 are printed in order on the standard output.
Print each number in a separate line.
Example I entered the numbers:
100
99
3
4
6

Each number must be in new line.
When I press enter the program must show me which numbers are divisible by 3. Example:
99
3
6

Here is my code
string a;
int n;
while (true)
{
    a = Console.ReadLine();
    if (a == string.Empty)
        break;

    n = Convert.ToInt32(a);
    {
        if (n % 3 == 0)
            Console.WriteLine(n);
    }
}

Problem is that when I enter a number that is divisible by 3 the program prints it immediately instead of waiting for me to finish entering numbers and only then to print numbers that are divisible by 3.

A: Show bellow maybe you can find something usefull:
    static void Main()
    {
        var output = string.Empty;

        if (int.TryParse(Console.ReadLine(), out int iterations))
        {
            while (iterations-- > 0) // or iterations > 0 and if number pass then increase the iterations
            {
                if (int.TryParse(Console.ReadLine(), out int number) /*&& number != 0*/ && number % 3 == 0)
                {
                    output += $"{Environment.NewLine}{number}";
                    // iterations--;
                }
            }
        }

        Console.WriteLine(output);
    }

for the people they say string should not be added:
    static void Main()
    {
        var output = new StringBuilder(Environment.NewLine);

        if (int.TryParse(Console.ReadLine(), out int iterations))
        {
            while (iterations-- > 0) // or iterations > 0 and if number pass then increase the iterations
            {
                if (int.TryParse(Console.ReadLine(), out int number) /*&& number != 0*/ && number % 3 == 0)
                {
                    output.AppendLine($"{Environment.NewLine}{number}");
                    //iterations--;
                }
            }

            Console.WriteLine(output);
        }
    }

and solution with list:
    static void Main()
    {
        if (int.TryParse(Console.ReadLine(), out int iterations))
        {
            //var output = new List<int>();
            var length = iterations;
            var output = new int[length];

            while (iterations > 0) // or iterations > 0 and if number pass then increase the iterations
            {
                if (int.TryParse(Console.ReadLine(), out int number) /*&& number != 0*/ && number % 3 == 0)
                {
                    //outpu.Add(number);
                    output[length - iterations] = number;
                    iterations--;
                }
            }

            Console.WriteLine(string.Join(Environment.NewLine, output));
        }
    }

A: You need to restucture your program to first take all inputs and then process them.
You can do it like this:
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // storage for all numbers
        var numbers = new List<int>();

        while (true)
        {
            var a = Console.ReadLine();
            if (a == string.Empty)
                break;

            // error handling to avoid crashing if non integers are given
            try
            {
                // adding all numbers in case you want to do other things with them
                numbers.Add(Convert.ToInt32(a));
            }
            catch
            {
                Console.WriteLine($"Not a number: {a}");
            }
        }

        // process the collected numbers
        foreach (var n in numbers)
        {
            if (n % 3 == 0)
                Console.WriteLine(n);
        }
    }
}

Testrun:
2
5
6
99
Apple
Not a number: Apple
102

6
99
102

As suggested in the comments: this will not fullfill the task given, you would need to read one number, then read as many inputs (so no while true: ... ).


text:
Q: Can I use a subquery to choose the column I want to select in SQL in MS Access? I have a query written that will return a single record (a class number) from table1.  This class number is the title of a column that I want to select in another table (table2). I want to use this subquery as a mechanism to select this column. Can this be done?
I know this may be bad design but I am just wondering if this sort of thing is possible in MS Access SQL.  I know it is not as powerful as MySQL.

A: The only way you're ever going to do this is using VBA to write the SQL, which really isn't a bad thing.  I'd do it sort of like this:
Dim db as Database
Dim rec as Recordset
Dim MyVar = String '(or whatever the datatype is for ClassNumber in Table1)
Dim sSQL as String
Dim qdfNew As DAO.QueryDef
Dim qryLoop As QueryDef

Set db = CurrentDB
Set rec = db.OpenRecordset("SELECT ClassNumber from Table1")

MyVar = rec(0)

'First check to see if the query already exists.  If so, delete it.
For Each qryLoop In CurrentDb.QueryDefs
If qryLoop.Name = MyVar Then
    DoCmd.DeleteObject acQuery, MyVar
End If
Next

'This will select only the field that relates to the ClassNumber above
sSQL = "SELECT " & MyVar & " FROM Table2"

Set qdfNew = db.CreateQueryDef("MyNewQuery", sSQL)

Then, MyNewQuery is a permanent query in your database which can be used in other queries.

A: There might be a better option, but I can only think of:

*

*Heinous case statement to choose the right column.

*Using VBA.

*Correcting the table design, turning the field name into a value
    that can be joined upon.


text:
Q: error for installing Math module CDF in perl I am trying to install Math::CDF in perl
I tried both cpan -i Math::CDP and install from downloaded files
both end up in error after enter make install:
Running make install
make[1]: Nothing to be done for `all'.
Files found in blib/arch: installing files in blib/lib into architecture dependent library tree
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ERROR: Can't create '/opt/local/lib/perl5/site_perl/5.16.3/darwin-thread-multi-2level/Math'
mkdir /opt/local/lib/perl5/site_perl: Permission denied at /opt/local/lib/perl5/5.16.3/ExtUtils/Install.pm line 494.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 at -e line 1.
make: *** [pure_site_install] Error 13
  CALLAHAN/Math-CDF-0.1.tar.gz
  /usr/bin/make install  -- NOT OK

Here is the version of the perl and the path:
bash-4.2$ which make
/usr/bin/make
bash-4.2$ which perl
/opt/local/bin/perl
bash-4.2$ perl -v

This is perl 5, version 16, subversion 3 (v5.16.3) built for darwin-thread-multi-2level

A: This problem may be because you don't have the permission to write onto those files.
You can try to install it locally.
perl Makefile.PL PREFIX=/path/to/home/folder

then you can run:
make
make install


text:
Q: How to train a bounding box detection model? Apparently, this still isn't possible in v12?
I'd like to add a new class to one of the standard object detection architectures. Consider the YOLO v2 detector from the Neural Net Repo.
NetModel["YOLO V2 Trained on MS-COCO Data"]

Which currently has 80 classes:
labels = {"person", "bicycle", "car", "motorcycle", "airplane", "bus",
    "train", "truck", "boat", "traffic light", "fire hydrant",
   "stop sign", "parking meter", "bench", "bird", "cat", "dog",
   "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe",
   "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
   "skis", "snowboard", "sports ball", "kite", "baseball bat",
   "baseball glove", "skateboard", "surfboard", "tennis racket",
   "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl",
   "banana", "apple", "sandwich", "orange", "broccoli", "carrot",
   "hot dog", "pizza", "donut", "cake", "chair", "couch",
   "potted plant", "bed", "dining table", "toilet", "tv", "laptop",
   "mouse", "remote", "keyboard", "cell phone", "microwave", "oven",
   "toaster", "sink", "refrigerator", "book", "clock", "vase",
   "scissors", "teddy bear", "hair drier", "toothbrush"};

As a minimal workable example, here is a toy set of training data for an additional class 'Fish', consisting of image and bounding-box coordinate pairs:
{fish, bboxes} =
  CloudGet @ CloudObject[
   "https://www.wolframcloud.com/objects/9c57ab39-52e2-40d3-84e6-80c9ee9a42a4"];
HighlightImage[fish[[1]], Rectangle @@ bboxes[[1]]]

Unfortunately, I can't find any information on the training net:

If I have to, I can download the original training data:

I also looked on the community but couldn't find any guidance for NetTrain'ing bounding box detection networks.
References:

*

*https://pjreddie.com/media/files/papers/YOLOv3.pdf

*https://blog.wolfram.com/2018/12/06/deep-learning-and-computer-vision-converting-models-for-the-wolfram-neural-net-repository/


text:
Q: React Redux vs fetch I've been using Redux with React and thunk middleware for some time, and don't get some moments.

*

*Is it ok to use plain fetch inside component and save result to local state, when only that component needs this data? What are the drawbacks?

*Suppose we have a page with Authors. User clicks on Author and navigates to the page with all the Books by this Author. Now, users goes back to the Authors page and clicks on different one. The data about previous Author is still in the Redux store and will be displayed, until new request finishes. How to overcome this?

A:
Is it ok to use plain fetch inside component and save result to local state, when only that component needs this data? What are the drawbacks?

The drawback is that it cannot have benefits of global state, like using Redux dev tools and accessing it when needed, e.g. hydrate it with existing data.

Suppose we have a page with Authors. User clicks on Author and navigates to the page with all the Books by this Author. Now, users goes back to the Authors page and clicks on different one. The data about previous Author is still in the Redux store and will be displayed, until new request finishes. How to overcome this?

It looks like Author should be cleared (e.g. assigned with null) on fetch start. A component that depends on data shouldn't be displayed until fetch success.


text:
Q: Emacs: Navigating to compile error I'm setting up emacs as my ruby development environment. I run tests by doing M-x compile and then rake test. I've set up compile-error-regexp-alist appropriately so that the resulting compile buffer can recognize test failures and make them clickable, but I'm facing trouble getting compile-find-file to use the correct directory to find the file from.
Suppose I'm visiting the file proj-home/test/ruby-test-file.rb and hit M-x compile and then use "rake test" for the compile-command. The resultant compile-buffer has "proj-home/test/" set as the default-directory while the rake test output has errors user [./test/ruby-test-file.rb:nn]. So when compile-find-file tries to find the file specified in the error message, it looks in "proj-home/test/./test/ruby-test-file.rb" which is obviously wrong.
How do I make compile-find-file to look in the right place? I've spent quite some time debugging the functions and reading through the function definitions in compile.el, but no joy yet.
One thing that did surprise me is that running rake test from inside a shell cd'd to "proj-home/test" correctly runs the tests (even tho' the Rakefile is in "proj-home" and not "proj-home/test"), so it looks like rake has some intelligence built-in which allows it to search up the directory tree and find the Rakefile in parent directories.
This intelligence in rake might be confusing emacs as to what is the current directory it should use.
The emacs wiki here: http://www.emacswiki.org/emacs/CompileCommand has a code snippet to find a file by searching parent directories (under "Running Make with the closest Makefile"), but I still haven't figured out if/where I need to use that code snippet.

A: You could try to define an advice around compile to set the correct default directory:
(defadvice compile (around set-rail-test-dir (command &optional comint))
  "set the correct directory"
  (if (and (string-match "rake test" command)
           (string-match "\(.*\)/test/$" default-directory))
     (let ((default-directory (match-string 1 default-directory)))
        ad-do-it)
     ad-do-it))

(ad-activate 'compile)

You might want to use something more clever to set the correct directory, and to know if it should be set or no (maybe using one of the code snippet you gave), but the idea is to use this code to change the compile function without redefining it.

A: I finally used the following code to set the default-directory in the compile command as suggested by Remi
 (defun ancestor-directory-with (file-name &optional directory)
  (let ((dir (or directory default-directory))
    (root (expand-file-name "/"))) ;the win32 builds should translate this correctly
    (if (directory-has-file-p dir file-name)
    dir
      (if (equal (directory-file-name dir) (directory-file-name root))
      default-directory
    (ancestor-directory-with file-name (expand-file-name ".." dir))))))

(defun directory-has-file-p (directory file-name)
  (file-exists-p (expand-file-name file-name directory)))

Using this to set the default-directory in the compile command helped me get the correct behaviour.


text:
Q: Code validation in W3C validator getting failed due to aria-required attribute I have a simple login page in my application with username and password fields.
My application is developed by JAVA and it uses Primefaces UI framework.
I have added a Primefaces inputText (p:inputText) for username field and Primefaces password (p:password) for password field.
After the page has rendered in browser, the code probably seems like below.

   E-mail:
   <input type="text" id="email" name="email" size="20" aria-required="true" /> *

   Password:
   <input type="password" id="passwordCtrl" name="password" size="20" aria-required="true" /> *

When I try to validate the HTML code in https://validator.w3.org/, it showing validation error message as shown below.

To get the code to validate, right click on the page and select View Source, then copy the entire code and paste the code in W3C validator.
Among the two controls, the issue is only with the input[type="password"] control. How to handle this HTML code validation error? Is there any way to achieve this?
Note:
I am using Primefaces UI framework


text:
Q: Prevent R Studio from 'skipping' comments. Run EACH line After updating R Studio (i'm using 1.0.153), R ignores comments by skipping to the next executable line. I really don't like this, I prefer to send even comments to the console (the way it has always been before recent update). Is it possible to continue sending comments to the console?

A: To send comments to the console:
Go to Tools -> Options -> Code and uncheck "Execute all lines in a statement."


text:
Q: Output data from multiple sources into separate rows I am pulling data from multiple Excel files within a folder. It outputs all in one column. I wish to make each Excel file data-set its own column and transpose it into rows. How can I accomplish this within a sub?
My thought is that it has something to do with that last if statement (with comments 'set the destrange' and 'we copy the values from the sourceRange to the destrange.'
Sub MergeAllWorkbooks()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    Dim FirstCell As String

'FIND FOLDER *MAKE SURE TO ADD SLASH AT THE END
MyPath = "C:\Users\dube\Desktop\Test for Lease Comps\"

'IF THERE ARE NO EXCEL FILES
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
    MsgBox "No files found"
    Exit Sub
End If

'PULLING DATA FROM EXCEL FILES AND ADDING TO ARRAY
FNum = 0
Do While FilesInPath <> ""
    FNum = FNum + 1
    ReDim Preserve MyFiles(1 To FNum)
    MyFiles(FNum) = FilesInPath
    FilesInPath = Dir()
Loop

'Change ScreenUpdating, Calculation and EnableEvents
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
End With

'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1

'Loop through all files in the array(myFiles)
If FNum > 0 Then
    For FNum = LBound(MyFiles) To UBound(MyFiles)
        Set mybook = Nothing
        On Error Resume Next
        Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
        On Error GoTo 0

        If Not mybook Is Nothing Then

            On Error Resume Next

            With mybook.Worksheets(1)
                Set sourceRange = .Range("C6:C32")
            End With

            If Err.Number > 0 Then
                Err.Clear
                Set sourceRange = Nothing
            Else
                'if SourceRange use all columns then skip this file
                If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                    Set sourceRange = Nothing
                End If
            End If
            On Error GoTo 0

            If Not sourceRange Is Nothing Then

                SourceRcount = sourceRange.Rows.Count

                If rnum + SourceRcount >= BaseWks.Rows.Count Then
                    MsgBox "Sorry there are not enough rows in the sheet"
                    BaseWks.Columns.AutoFit
                    mybook.Close savechanges:=False
                    GoTo ExitTheSub
                Else

                    'Set the destrange
                    Set destrange = BaseWks.Range("B" & rnum)

                    'we copy the values from the sourceRange to the destrange
                    With sourceRange
                        Set destrange = destrange. _
                                        Resize(.Rows.Count, .Columns.Count)
                    End With
                    destrange.Value = sourceRange.Value

                    rnum = rnum + SourceRcount

                End If

            End If

            mybook.Close savechanges:=False

        End If

    Next FNum
    BaseWks.Columns.AutoFit
End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub


text:
Q: set names in a data frame I have a data frame that I want to set names to it. I tried to use rbind function.
I created a vector of names with the same number as the number of the data frame columns. The vector length 32.
names <- c("Pan troglodytes schweinfurthii A910","Pan troglodytes troglodytes A957",
           "Pan troglodytes troglodytes A958", "Pan troglodytes troglodytes A960",
           "Pan troglodytes verus A965", "Pan paniscus A914", "Pan paniscus A915",
           "Pan paniscus A917", "Pan paniscus A919", "Pan paniscus A920 ",
           "Pan paniscus A925", "Gorilla beringei graueri A929",
           "Gorilla gorilla gorilla A931", "Gorilla gorilla gorilla A932",
           "Gorilla gorilla gorilla A937", "Gorilla gorilla gorilla A962",
           "Gorilla beringei graueri A967", "Pongo pygmaeus A943",
           "Pongo pygmaeus A944", "Pongo abelii A947",
           "Pongo abelii A949", "Pongo abelii A953", "Pongo abelii A955",
           "Homo sapiens SD647", "Homo sapiens SD428", "Homo sapiens SD455",
           "Homo sapiens SD583", "Homo sapiens SD643", "Homo sapiens SD961",
           "Homo sapiens SD860","Homo sapiens SD249","Homo sapiens SD1067")

The data frame looks like that with 32 columns:
v218            v227           v254
A914.AVG_Beta   A915.AVG_Beta   A917.AVG_Beta
0.6289983   0.4749584   0.5873566   0.5803553
0.9145997   0.8802801   0.8940547   0.9315571
0.8656011   0.8590986   0.853209    0.9070981

When I run :
tomas_data_450K_b_values <- rbind(names, process_tomas)

I get the warning:

There were 32 warnings (use warnings() to see them)

And that outcome:
v218            v227           v254
NA              NA              NA
A914.AVG_Beta   A915.AVG_Beta   A917.AVG_Beta
0.6289983   0.4749584   0.5873566   0.5803553
0.9145997   0.8802801   0.8940547   0.9315571
0.8656011   0.8590986   0.853209    0.9070981

How can I set the vector names as the data frame names and save the data frame with the new names?

A: You cannot add names to columns by using rbind since that is for combining rows of data. You change the column names of a data frame by using the function colnames()
colnames(my_data_frame) <- c("colname_1", "colname_2", "colname_3")


text:
Q: How to close an adjacent drop down when opening another I'm trying to set up a list of filters for a results page. But I only want one list of the three active at a time. I'm using jQuery to show/hide the lists.
Here's a stripped down version of what I'm working on.
https://jsfiddle.net/JeffSydor/bgpw9x60/

$('.dropMenu ul').css('display', 'none');
$('.dropMenu').click(function() {
  var thisMenu = $(this).children('.listName'),
    thisList = $(this).children('ul');
  if (thisMenu.not('.open')) {
    thisMenu.toggleClass('open');
    thisList.slideToggle();
  }
});

Contributors

name01

name02

Categories

cat01

cat02

Tags

tag01

tag02

I'm trying to figure out how to look for other open menus and close them when clicking on any of the others.
I've looked into preventDefaults too, but it doesn't make any sense to me or if it would work.

A: You can just slide all of them up and then slide the clicked one down.
 $('.dropMenu').click(function(){
    let lists = $('.dropMenu .listName');
    $('.dropMenu .listName').removeClass('.open');
    $('.dropMenu ul').slideUp();

    $(this).children('.listName').addClass('open');
    $(this).children('ul').slideDown();
 });

A: Select the ones that are opened and close them before opening a new one
$('.dropMenu ul').css('display', 'none');
$('.dropMenu').click(function() {
  var thisMenu = $(this).children('.listName'),
    thisList = $(this).children('ul');
  if (thisMenu.not('.open')) {
    $('.dropMenu .open').removeClas('open')
    thisMenu.toggleClass('open');
    thisList.slideToggle();
  }
});

A: This will work, and you won't even need the if statement.

$(document).ready(function(){

 $('.dropMenu ul').css('display', 'none');

  $('.dropMenu').click(function(){
    $('.dropMenu').not($(this)).children('.listName').removeClass('open');
    $('.dropMenu').not($(this)).children('ul').slideUp();
    $(this).children('.listName').toggleClass('open');
    $(this).children('ul').slideToggle();
  });

});

Contributors

name01

name02

Categories

cat01

cat02

Tags

tag01

tag02


text:
Q: Nodejs Mocha test failing Jenkins I am testing my db connection using mocha module of nodejs and the test is passing locally.
describe('Access to DB', function(){
   describe('#fail', function(){
        it('should return -1 because wrong credentials', function(done){
            var connection = mysql.createConnection({
                host: 'localhost',
                user: 'root',
                password: 'head',
                database: 'head'
            });
            connection.connect(done);
        });
    })
});

./node_modules/.bin/mocha ./test/test.js tests pass when I run this command.
But when I run my job using jenkins. The test fails with error:
Access to DB #fail should return -1 because wrong credentials: [0m[31m     Error: connect ECONNREFUSED 127.0.0.1:3306[0m[90m at TCPConnectWrap.afterConnect [as oncomplete]
My jenkins is instaled in different server and Node app in different one. I am comunication between them with SHA keys. Everything is working except for this test. mysql is not installed in jenkins server. Could that be the reason.


text:
Q: By 2030, new well-paid jobs "will be"/"will have been" available Here is the question:

By 2030, new well-paid jobs (will be - will have been - had been - were being) available in London.

This was a question in my exam. I chose "will have been", but my instructor told me that both answers are correct ("will be", "will have been"), so I'm confused now. Which one is really the most correct? Please include an explanation


text:
Q: Can I install C# Razor .NET on XAMPP? I have been trying to install IIS (Windows 8) on my head computer. I ended up installing XAMPP on it, setting up the FileZilla server to work with Visual Studio Community 2015 FTP on my development computer (Windows 8.1 Laptop). FileZilla connects, and VS2015 reads my server. It uploads, everything is well, and I can edit it. Thing is when I launch into the server on Firefox and go to the Home page (Razor C# .NET, Default.cshtml) is shows me the code behind the website. Is there like an extension for C# .NET?
Thanks

A: You should be able to configure FileZilla to FTP files to your IIS website.  It should just be another directory on your file system.


text:
Q: Unable to restart apache2 after installing SSL certificate I installed an SSL certificate from Comodo. After I edited my default-ssl.conf, I encountered an error whilst trying to restart the apache2 service.
PASTEBIN OF THE ERROR: http://pastebin.com/wyAvMNM0

A: There are 3 problems :

*

*There are duplicate files about SSLCertificateFile and SSLCertificateKeyFile which should be removed.

*There is and cloudflare setting that should be disabled - Always use https

*From the forums settings, the URL should be changed to https:// and the 301 redirect will be fine.
I hope this can help you @whitz

A: The error is quite clear:
Jan 04 14:41:21 vps231844.ovh.net apache2[1622]: SSLCertificateChainFile takes one argument, SSL Server CA Certificate Chain file ('/path/to/file' - PEM encoded)

What you should do is to remove the whole line SSLCertificateChainFile which is an optional directive.


text:
Q: Formatting Footer with VBA I am modifying a VBA code another person did at my work place. They have code inserting a footer into a generated quote form. The code for the footer is:
Frow = Sheets("Quote").Range("C65536").End(xlUp).Offset(2, 0).Row

Trow = Frow - 1
Hrow = Frow + 4
Srow = Frow + 4

Sheets("Quote").Range("F" & Frow).Value = "TOTAL:"
Sheets("Quote").Range("G" & Frow).Value = "=SUM(G13:G" & Trow & ")"

Sheets("Quote").Range("A" & Hrow).Value = Foot

'merge with next row
Range("A" & Hrow, "G" & Srow).Select

With Selection
    .HorizontalAlignment = xlGeneral
    .VerticalAlignment = xlTop
    .WrapText = True
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = True
End With

It is moving the text from another sheet and pasting it on the newly generated quote sheet. The problem I am having is that text is very long and gets cut off. I have WrapText set to true as you can see, but the cell is not resizing to show the wrapped text.
What do I need to add to this to get it to autofit?
For reference, here is the beginning of the code where Foot is defined:
Sub CreateQuote1()
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim LastcRow, LastqRow
    Dim Dst
    Dim Foot
    Dim Frow, Trow, Hrow, Srow
    Dim c
    Dim cRange As Range

    LastcRow = Sheets("Data Entry").Range("B65536").End(xlUp).Row
    LastqRow = Sheets("Quote").Range("C65536").End(xlUp).Row
    Foot = Sheets("Instructions").Range("A15").Value

I tried adding With Selection under Foot, but I could not get it to work, and I was unable to find the proper code for autofit in that format.

A: After speaking to a friend who knows code better than I, autofit does not work with this. The best course of action was to increase the amount of merged rows allowing for the text to be shown in its entirety.
He did so by changing the code to the following:
  Range("A" & Hrow, "G" & Srow + 5).Select

            With Selection
            .HorizontalAlignment = xlGeneral
            .VerticalAlignment = xlTop
            .WrapText = True
            .Orientation = 0
            .AddIndent = False
            .IndentLevel = 0
            .ShrinkToFit = False
            .ReadingOrder = xlContext
            .MergeCells = True
            End With

He added +5 to the sRow, increasing the amount of rows merged, solving the issue.

A: question, im not an expert but why dont you create the word template and in the footer add "rich text content control" those you can edit wit vba
wDoc.SelectContentControlsByTitle("TitleOfCC").Item(1).Range.Text = FormName.box1.Value

this is how i do when i have long texts, and with content control i change only the variable text


text:
Q: Database not creating record Inserting a record in the database using EF 5.0 isn't working. Debugging through my code I cannot find any exception. Going through the code it should insert a new record in the database, but when I look at the database there are no new records created. However, I did make changes to my database, and in debug when I check on the "assestUser" (the model) I can see all values, including the deleted columns (the changes I made). Could somebody please help me with what I am doing wrong?
This is what I have done:
Page:
   public partial class _Default : Page
{
    EntityContext context;

    public _Default()
    {
        context = new EntityContext();
    }

     protected void btnSavePersonalDetails_Click(object sender, EventArgs e)
    {
        try
        {
            SkillsAssestUser assestUser = new SkillsAssestUser();
            assestUser.DomainAcc = lblDomAcc.Text;
            assestUser.Name = txtName.Text;
            assestUser.Surname = txtSurname.Text;
            assestUser.Division = txtDivision.Text;
            assestUser.Manager = txtManager.Text;

            context.SkillsAssestUsers.Add(assestUser);
            context.SaveChanges();

            //var assestUser = context.Set<SkillsAssestUser>();
            //assestUser.Add(new SkillsAssestUser
            //{
            //    DomainAcc = lblDomAcc.Text,
            //    Name = txtName.Text,
            //    Surname = txtSurname.Text,
            //    Division = txtDivision.Text,
            //    Manager = txtManager.Text
            //});

            //context.SaveChanges();

            ClearPersonalDetails();
        }
        catch (Exception ex)
        {
            throw new Exception("Error inserting Details. " + ex.Message);
        }
    }

DbContext:
 public partial class EntityContext : DbContext
 {
    public EntityContext()
        : base("name=SOSConnectionString")
    {
        base.Configuration.LazyLoadingEnabled = true;
        base.Configuration.ProxyCreationEnabled = false;
    }

     #region AddTables
    public DbSet<AdditionalSkills> AdditionalSkillss { get; set; }
    public DbSet<CertifiedTraining> CertifiedTrainings { get; set; }
    public DbSet<OtherCertifiedTraining> OtherCertifiedTrainings { get; set; }
    public DbSet<OtherEdu> OtherEdus { get; set; }
    public DbSet<SchoolEdu> SchoolEdus { get; set; }
    public DbSet<SkillsAssestUser> SkillsAssestUsers { get; set; }
    public DbSet<ValueAddedSkills> ValueAddedSkillss { get; set; }
    #endregion
    }

     void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        AuthConfig.RegisterOpenAuth();
        Database.SetInitializer<EntityContext>(null);
    }

What am I doing wrong? ...new to ef....

A: Check Connection String First.
be sure that this is on Global.ASAX:
void Application_Start(object sender, EventArgs e)
 {
    // Code that runs on application startup
    AuthConfig.RegisterOpenAuth();
    Database.SetInitializer<EntityContext>(null);
 }

use code like this:
      using (var mycontext = new context())
        {
           SkillsAssestUser assestUser = new SkillsAssestUser();
           assestUser.DomainAcc = lblDomAcc.Text;
           assestUser.Name = txtName.Text;
           assestUser.Surname = txtSurname.Text;
           assestUser.Division = txtDivision.Text;
           assestUser.Manager = txtManager.Text;

           mycontext.SkillsAssestUsers.Add(assestUser);
           mycontext.SaveChanges();
        }


text:
Q: Best practice to load a static file into memory once and share among all API requests I have a .NET Web Api project and inside my project, I have a few plain text files that basically act as static templates. Each API request that is made contains data that will substitute values inside a copy of these templates(so as to preserve the original) and then written to disk for further processing.
The template files itself are very small(< 100 lines). What is the best way to have these files or the text inside the files always available in memory so I don't have to open and close the FileStream for each request?
Does a IMemoryCache make sense when the values are always static? Should I store the text as a constant in a static class? Any ideas are appreciated. Thank you.


text:
Q: Magento seo question. Nofollow on top links like cart/login? Magento seo question. Nofollow on top links like cart/login?
While reading up on seo I thought to add no follows to default links that exist on every page. Cart. Login. Checkout. TC. Faq.
When looking up my site on Google using site:domain I realized that the top pages were the ones that have links in headers and footers.
By adding rel=nofollow to functional links like cart/login/etc all the seo juice is given only to relevant category and content pages (that dofollow).
Question:
Is this smart to do seo wise? And how can this be done via xml or Phtml using no follow? Or can it be tackled via robots?
Many thanks
......

A: Of course, the best practice would be to put nofollow, noindex on the meta tags and maybe exclude the page(s) in robots.txt. It is not really necessary but just to keep it all clean and tidy i would suggest doing it.
Here is a good explanation how to do it, in case you don´t know
http://doejo.com/blog/magento-how-to-add-noindex-nofollow-robots-meta-tag-or-change-meta-title-or-description-on-certain-pages/#.VObxGPmG_HU

A: Personally, I have never nofollowed the cart and login links on my Magento site and have great site SEO, regardless. Though you could certainly robots.txt prevent crawling of those pages, you'll probably get better bang for your SEO buck by tackling some of the other SEO related issues in Magento (such as defining URL parameters in Google Webmaster Tools).
Also, unless your site is incredibly large or the site architecture is quite deep, you are likely not reaching your site crawl limit and letting Google crawl those two pages will not prevent other pages on your site from being crawled and indexed properly.
Kaylie

A: If u have  used no follow, that is not a big issue but generally you should avoid using no follow.
Matt Cutts suggested that to use  no index instead of no follow for internal pages.
There is not much important  to use no follow link,   but if you want to use with the help of XML or PhTML, we generally use PhTML method to do no follow and it can be tackled with the  robots by using these two steps.
Login
Login

Or
add <META NAME="ROBOTS" CONTENT="INDEX, NOFOLLOW"> in the head section of that page

A: Beware of @Klettseb answer: If you exclude a page in the /robots.txt the bot is no allowed to read the content of the page and therefore can not read any

directives you added to the page.
Better not exclude the page in the robots, add no index to the page and then submit the page in the google search console (fetch as google bot).


text:
Q: How to solve "ValueError: Error when checking target: expected dense_20 to have shape (24,) but got array with shape (1,)"? I'm working on a sign language interpretation using deep learning & for that, i'm building a CNN and i am getting an error like,

ValueError: Error when checking target: expected dense_20 to have
  shape (24,) but got array with shape (1,)

structure of my neural net:
Layer (type)                 Output Shape              Param #

conv2d_62 (Conv2D)           (None, 64, 64, 64)        1088
_________________________________________________________________
conv2d_63 (Conv2D)           (None, 32, 32, 64)        65600
_________________________________________________________________
dropout_31 (Dropout)         (None, 32, 32, 64)        0
_________________________________________________________________
conv2d_64 (Conv2D)           (None, 32, 32, 128)       131200
_________________________________________________________________
conv2d_65 (Conv2D)           (None, 16, 16, 128)       262272
_________________________________________________________________
dropout_32 (Dropout)         (None, 16, 16, 128)       0
_________________________________________________________________
conv2d_66 (Conv2D)           (None, 16, 16, 256)       524544
_________________________________________________________________
conv2d_67 (Conv2D)           (None, 8, 8, 256)         1048832
_________________________________________________________________
flatten_11 (Flatten)         (None, 16384)             0
_________________________________________________________________
dropout_33 (Dropout)         (None, 16384)             0
_________________________________________________________________
dense_19 (Dense)             (None, 512)               8389120
_________________________________________________________________
dense_20 (Dense)             (None, 24)                12312

code:
    model = Sequential()

    model.add(Conv2D(64, kernel_size=4, strides=1, activation='relu', input_shape = (64,64,1),padding = 'same'))
    model.add(Conv2D(64, kernel_size=4, strides=2, activation='relu',padding = 'same'))
    model.add(Dropout(0.2))

    model.add(Conv2D(128, kernel_size=4, strides=1, activation='relu',padding = 'same'))
    model.add(Conv2D(128, kernel_size=4, strides=2, activation='relu',padding = 'same'))
    model.add(Dropout(0.2))

    model.add(Conv2D(256, kernel_size=4, strides=1, activation='relu',padding = 'same'))
    model.add(Conv2D(256, kernel_size=4, strides=2, activation='relu',padding = 'same'))

    model.add(Flatten())
    model.add(Dropout(0.3))
    model.add(Dense(512, activation='relu'))
    model.add(Dense(24, activation='softmax'))

    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

    print(model.summary())

    model.fit(x_train, y_train, validation_data=(x_test, y_test),batch_size=64,epochs=8)

dimensions of arrays used:
x_train: (3977, 64, 64, 1)
y_train: (3977, 1)
x_test:  (995, 64, 64, 1)
y_test:  (995, 1)

A: Your last layer output shape need to match your label's vector shape
So you need to one_hot encode your y_train in order to fit your network.
You can do this like that :
from keras.utils import to_categorical
y_train = to_categorical(y_train, 24)

This will encode each of your label to a vector of size 24 (or whatever you need), filled with 0s and a 1 at the position of the corresponding label.
To learn more about it :
https://keras.io/utils/


text:
Q: Checkstyle length check for import statements How to remove checkstyle violation if it throws a "Line is longer than 80 characters" for an import statement?

A: Remove:
<module name="LineLength">
    <property name="max" value="80"/>
</module>

from your checkstyle configuration.
EDIT:
Disable it only for imports:
<module name="LineLength">
   <property name="ignorePattern" value="someRegex"/>
</module>

You have to provide the regular expression which finds the line starting with import into the value attribute. I am not so good at regex so you will need work out the regular expression yourself.
The regex like: ...value="^import"... should work. But not tested.

A: To exclude import and package statements from the check, you can apply following configuration:
<module name="LineLength">
    <property name="max" value="80" />
    <property name="ignorePattern" value="^(package|import) .*"/>
</module>

Source: https://checkstyle.org/config_sizes.html#LineLength_Examples
Or you can apply tags as suggested by Marko (but first option is more proffered):
// CHECKSTYLE:OFF
import ...
// CHECKSTYLE:ON

A: I want to add some aditional info to Paulius Matulionis's answer.
If you are using default Checkstyle rules, you can find checkstyle configuration file by going to your Idea directory:
%HOMEPATH%.IdeaIC2017.1\config\plugins\CheckStyle-IDEA\classes\sun_checks.xml
Folder name ".IdeaIC2017.1" could be different depends on version of Idea you are using.
Also, you can find your configuration file name in Idea's "Settings"

A: By default, the Checkstyle LineLength configuration ignores package and import statements.  This is accomplished by the default value for the ignorePattern property, which is "^(package|import) .*".
Since your import statement is failing the LineLength check, either it's formatted differently than expected by the default configuration (e.g. it has a leading space), or you've customized the ignorePattern in your project, (inadvertantly) removing the import check configuration in the process.
Import statements can be added back to a customized ignorePattern regex.  For instance, if it's currently set to "somePattern", you could configure your ignorePattern as follows:
<module name="LineLength">
  <property name="ignorePattern" value="^import .*|somePattern"/>
</module>


text:
Q: LibGDX: How to get exact touch time? Is it somehow possible in LibGDX to get exact touch time (~1 ms accuracy)?
InputProcessor.touchDown is only called at beginning of the frame (or at the end of the frame?) so it only has 16.7 ms accuracy if the frame rate is 60 fps. That is, I only know during which frame the touch happened, but not if it happened 0 or 15 ms after the render() was called, which makes a huge difference in reaction-based games.
Gdx.input.getCurrentEventTime() is not any more accurate.
If this is not possible with LibGDX tools, is there any (easy) hack for capturing the touch event on OS (Android) level to just check the time and then let LibGDX handle it normally?

A: I looked closely at the libGDX source code and you can see here that it grabs the time stamp from a libGDX TouchEvent class. And you can see here that it uses the time at the moment it's synchronizing touch events as the timestamp placed into TouchEvent, rather than the time reported by Android's MotionEvent class.
So what I would suggest is cloning (copy-pasting) the libGDX AndroidTouchHandler class to create your own class and modifying it so instead of passing the timeStamp variable to the postTouchEvent method, pass event.getEventTime() instead for ACTION_DOWN events.
Then clone the DefaultAndroidInput class, changing nothing but the touchHandler variable to be your cloned class type, and instantiate that instead in the constructor.
So now this version of AndroidInput will report the actual Android MotionEvent's time in Gdx.input.getCurrentEventTime(). True, it will only report the time for the last motion event that occurred before the current animation frame, but presumably it would be very rare or maybe impossible to receive more than one touch down event in a frame. Keep in mind, it will be reporting the time based on system uptime instead of whatever System.nanoTime is relative to.
Then to use this alternative version of AndroidInput, you override createInput() in your game launcher activity class and return an instance of your own class instead.
Disclaimer: I have not tested any of this, and I don't know how accurately Android reports time in the MotionEvent class.
[If you need to handle multiple touches per frame, this gets more complicated. I think you'd need to create an interface in your core module that has a callback that  can report multiple touch events with individual timestamps, then implement that in your AndroidInput implementation class, and then back in core you could cast Gdx.input to this interface so you could get at that data.]


text:
Q: How to specify preceding-sibling inside for-each loop over a variable I am encountering a syntax error in when I try and use XPath preceding-sibling in an xsl:for-each loop in XSLT 2.0. None of the examples I have seen address this specific case. I am iterating over a sequence of  elemente in the variable $v1. Here is how the XSLT is structured:
<xsl:for-each select="$v1/*">
    <xsl:choose>
      <!-- minus in previous element means loss -->
      <xsl:when
          test="matches(preceding-sibling::.[1]/.string(), '-')">
        <xsl:copy>
          <xsl:sequence
              select="concat('Loss: ', ./string()"/>
        </xsl:copy>
      </xsl:when>
      <!-- just copy node and children -->
      <xsl:otherwise>
        <xsl:sequence select="."/>
      </xsl:otherwise>
    </xsl:choose>
</xsl:for-each>

This is a simplification of the running code. The working version has other when clauses that compile correctly. I'm only showing the when clause that give me a compile time error.
The error refers to Unexpected token "." after axis name. When I reference the current node I use matches(./string(), '(\(|\))') and I have no problem. Why can't I use the same . for the previous node?
I'm using Saxon HE9.5.1.4.

A:
When I reference the current node I use matches(./string(), '(\(|\))') and I have no problem. Why can't I use the same . for the previous node?

IMHO applying the same notion as ./string() you mentioned above for preceding-sibling would result in the following expression, instead of preceding-sibling::.[1]/.string() :
./preceding-sibling::*[1]/string()

A: Instead of matches(preceding-sibling::.[1]/.string(), '-') you probably simply want matches(preceding-sibling::*[1], '-') to match on the immediately preceding sibling element node or matches(preceding-sibling::node()[1], '-') to match on any kind of immediately preceding node. There is no need to call string().

A: This syntax works for my case
matches(preceding-sibling::td[1]/string(), '-')

I'm transforming a sequence of <td> elements in my for-each loop.


text:
Q: Data binding / NSArrayController: What is the job of the Object Controller Every tutorial I read about data binding / NSArrayController told to set the Mode and the Keys in the Object Controller (Attributes Inspector) for the data model class I use. Why do I have to do this?
In my sample application I create all objects in code and add them to the array controller in code too. The program still works fine without any settings in the Object Controller. I use the NSCollectionView to present my data.

A: To answer the question in the subject, the Object Controller section lets you determine what the array controller is controlling. In your screenshot the array controller is controlling objects of a Person class. But the array controller can also control a Core Data entity. That's what the Mode menu is for. The keys are pieces of the object/entity the array controller is controlling.
The reason the tutorials tell you to set the mode and keys is they are demonstrating using NSArrayController with Cocoa bindings. You must set the mode and keys so you can bind the array controller to the collection view in Interface Builder and have the collection view display relevant data from the array controller. If you are writing code to do all the NSArrayController work and not using Cocoa bindings, you can avoid setting the mode and keys.


text:
Q: CSS Changes after full load I am running a WordPress site (v3.6.1) with the Kaleido theme.
I am using the WPGForm plugin to display google forms on the site.
I have added a form, and it is properly showing up. I am styling the form from the theme's main stylesheet. I took the classes and divs from the plugin stylesheet and moved it over to the primary theme css.
On load, the elements that I style show properly. That only happens for a second.
Essentially, the properly styled elements flash and then they default back to the some other styles.
Here is a link to the issue:
http://maefgives.org/apply/curriculum-grant-application/

A: By default it takes the style from plugin class .entry-content. Try to override your style using !important with class name of div on your form.


text:
Q: Grouping on elements in XML transformation with XSLT I am struggling with the concept of grouping (on multiple keys) of table based XML to hierarchy with XSLT
The grouping is based on first four elements, however the grouping must break if there is another element in between the set.
Source XML:
<RECORDS>
<RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F1>A1</F1>
</RECORD>
<RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F1>A2</F1>
</RECORD>
 <RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>195</E5>
    <F1>A3</F1>
  </RECORD>
 <RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F1>A4</F1>
  </RECORD>
 <RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F1>A5</F1>
  </RECORD>
     <RECORD>
    <E1>DONALD</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F1>A6</F1>
  </RECORD>
 <RECORD>
    <E1>DONALD</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F1>A7</F1>
  </RECORD>
 </RECORDS>

Output XML
 <RECORDS>
 <RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F>
     <F1>A1</F1>
     <F1>A2</F1>
    </F>
  </RECORD>
  <RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>195</E5>
    <F>
     <F1>A3</F1>
     <F1>A4</F1>
    </F>
  </RECORD>
  <RECORD>
   <E1>MICKEY</E1> <!--Must break and not merge in first group -->
   <E2>TEST</E2>
   <E4>14</E4>
   <E5>196</E5>
   <F>
   <F1>A5</F1>
   </F>
  </RECORD>
  <RECORD>
    <E1>DONALD</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <E5>196</E5>
    <F>
     <F1>A6</F1>
     <F1>A7</F1>
    </F>
  </RECORD>
 </RECORDS>

Here is the XSL I have come up with so far...
<?xml version="1.0"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
 <xsl:key name="grouped" match="RECORD"
  use="concat(E1, '+', E2, '+', E4 , '+', E5 )"/>

<xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 <xsl:template match="/*">
  <RECORDS>
   <xsl:apply-templates select=
   "RECORD[generate-id()
          =
           generate-id(key('grouped',
                        concat(E1, '+', E2, '+', E4 , '+', E5 )
                          )
                           [1]
                      )
           ]
   "/>
  </RECORDS>
 </xsl:template>
 <xsl:template match="RECORD">
   <RECORD>
  <E1><xsl:value-of select="E1"/></E1>
<E2><xsl:value-of select="E2"/></E2>
<E4><xsl:value-of select="E4"/></E4>
<F>
<xsl:for select="F1">
<F1><xsl:value-of select="F1"/></F1>
</xsl:for>

</F>
   </RECORD>

</xsl:template>
</xsl:stylesheet>

The issue is that I am unable to generate the inner  tag reapeating for each f1. Also I should get 4 set of RECORDS, not 3 that I get with this.
<RECORDS>
  <RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <F></F>
  </RECORD>
  <RECORD>
    <E1>MICKEY</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <F></F>
  </RECORD>
  <RECORD>
    <E1>DONALD</E1>
    <E2>TEST</E2>
    <E4>14</E4>
    <F></F>
  </RECORD>
</RECORDS>

A: Here is a solution using keys. Shorter (28% less lines of code, and not requiring horizontal scrolling). More Robust (see the end of this answer for details)
It is more general, because it will work even in the case where in-between the elements we want to group, there are other elements that must be ignored (that is where preceding-sibling::*[1] may be an element we want excluded from grouping -- in the current problem -- not a RECORD element):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:key name="kStartGroup" match="/*/*" use=
    "generate-id(preceding-sibling::*
      [not(concat(E1, '|', E2, '|', E4, '|', E5)
          = concat(current()/E1, '|', current()/E2, '|', current()/E4, '|', current()/E5)
          )
      ][1])"/>
  <xsl:template match="*[not(concat(E1, '|', E2, '|', E4, '|', E5)
                            =
                              concat(preceding-sibling::*[1]/E1, '|',
                                     preceding-sibling::*[1]/E2, '|',
                                     preceding-sibling::*[1]/E4, '|',
                                     preceding-sibling::*[1]/E5)
                             )]">
    <xsl:copy>
      <xsl:copy-of select="E1 | E2 | E4 | E5"/>
      <F><xsl:copy-of select=
                      "key('kStartGroup', generate-id(preceding-sibling::*[1]))/F1"/></F>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="/*"><xsl:copy><xsl:apply-templates/></xsl:copy></xsl:template>
  <xsl:template match="text()"/>
</xsl:stylesheet>

Robustness / Scalability
Because this transformation doesn't contain recursion (nested calls to <xsl:apply-templates), it is robust and scalable when applied on large XML files.
On the other side, the provided in another answer "siblings recursion" solution crashes due to stack-overflow when the transformation is applied on sufficiently-large XML document. In my case this crash was observed with source XML document of about 13 000 (13 thousand lines) -- this may vary depending on available RAM, XSLT processor, etc.
The current transformation executes successfully even on extremely large XML documents -- such as having 1 200 000 (one million and 200 thousand lines).

A: Apparently you want to do in XSLT 1.0 the equivalent of XSLT 2.0's group-adjacent. This can be achieved using a technique known as "sibling recursion":
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/RECORDS">
    <xsl:copy>
        <!-- start the first group -->
        <xsl:apply-templates select="RECORD[1]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="RECORD">
    <xsl:variable name="key" select="concat(E1, '+', E2, '+', E4 , '+', E5)" />
    <xsl:copy>
        <xsl:copy-of select="E1 | E2 | E4 | E5"/>
        <F>
            <xsl:copy-of select="F1"/>
            <!-- immediate sibling in the same group -->
            <xsl:apply-templates select="following-sibling::RECORD[1][concat(E1, '+', E2, '+', E4 , '+', E5) = $key]" mode="collect"/>
        </F>
    </xsl:copy>
    <!-- start the next group -->
    <xsl:apply-templates select="following-sibling::RECORD[not(concat(E1, '+', E2, '+', E4 , '+', E5)=$key)][1]"/>
</xsl:template>

<xsl:template match="RECORD" mode="collect">
    <xsl:variable name="key" select="concat(E1, '+', E2, '+', E4 , '+', E5)" />
    <xsl:copy-of select="F1"/>
    <!-- immediate sibling in the same group -->
    <xsl:apply-templates select="following-sibling::RECORD[1][concat(E1, '+', E2, '+', E4 , '+', E5) = $key]" mode="collect" />
</xsl:template>

</xsl:stylesheet>


text:
Q: Use urlfetchapp with own redirection? I am trying to do an urlfetchapp on a website, the website contains HTML but thats good enough for me.
For example I want this url.
The problem of this method is it won't show me any data until I first went to this url.
I tried to do 2 urlfetchapp after each other. But this didn't work.
How can I solve this problem?
Below is my test code, if there is data then objTable should get data.
function loadXML()
{
  try
  {
    var URL = "http://www.knzb.nl/verenigingen/wedstrijdsport/waterpolo/uitslagen_waterpolo/iframe/verenigingen/KNZB-DISTRICT-OOST/";
    var response = UrlFetchApp.fetch(URL);
    URL = "http://www.knzb.nl/verenigingen/wedstrijdsport/waterpolo/uitslagen_waterpolo/iframe/verenigingen/poule/1178/2074/DHS289F/";
    response = UrlFetchApp.fetch(URL).getContentText();
    Logger.log(response);
    var doc = Xml.parse(response, true);

    var objTable = doc.html.body.form.div[1].div.div.div.div.div.div;
  }
  catch(err)
  {
    var objTable = "Load failed";
    Logger.log("Loading data failed: " + err);
  }
  return objTable;
}

A: I already found the answer to my own question.
Needed to resend the cookie. The script below is working as it should be.
function loadXML()
{
  try
  {
    var URL = "http://www.knzb.nl/verenigingen/wedstrijdsport/waterpolo/uitslagen_waterpolo/iframe/verenigingen/KNZB-DISTRICT-OOST/";
    var response1 = UrlFetchApp.fetch(URL);
    Logger.log(response1);
    var cookieStr = response1.getHeaders()["Set-Cookie"];
    var params = {method: "POST", headers:{"Cookie": cookieStr}};
    URL = "http://www.knzb.nl/verenigingen/wedstrijdsport/waterpolo/uitslagen_waterpolo/iframe/verenigingen/poule/1178/2074/DHS289F/";
    response = UrlFetchApp.fetch(URL, params);
    Logger.log(response.getAllHeaders());
    response = response.getContentText();
    var doc = Xml.parse(response, true);

    var objTable = doc.html.body.form.div[1].div.div.div.div.div.div;
  }
  catch(err)
  {
    var objTable = "Load failed";
    Logger.log("Loading data failed: " + err);
  }
  return objTable;
}


text:
Q: Class hierarchies in a REST API I am designing a REST service that could be used by many types of clients, most likely .Net, PHP, Flex and JavaScript.  I am building the service using WCF and the REST starter kit.  One of my main goals is to make it as simple as possible for all those clients to use the API.
Let's say that the API deals with zoos.  When the client creates a new zoo it would be nice if they could pass along the initial set of animals so they only need to make a single call to the API, e.g.
<Zoo>
    <Name>My Zoo</Name>
    <Animals>
        <Snake>
            <Name>Frank</Name>
            <Length>2.5m</Name>
        </Snake>
        <Giraffe>
            <Name>Alfred</Name>
            <Height>10m</Height>
        </Giraffe>
    </Animals>
</Zoo>

I then want to deserialize the XML into C# classes like this:
List<Animal> Animals { get; set; }

class Animal { public string Name { get; set; } }
class Snake : Animal { public float Length { get; set; } }
class Giraffe : Animal { public float Height { get; set; } }

WCF doesn't like this as it wants the XML formatted like this:
<Zoo xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Name>My Zoo</Name>
    <Animals>
        <Animal i:type="Snake">
            <Name>Frank</Name>
            <Length>2.5m</Name>
        </Animal>
        <Animal i:type="Giraffe">
            <Name>Alfred</Name>
            <Height>10m</Height>
        </Animal>
    </Animals>
</Zoo>

This looks like it is going to be trickier to work with in client without high end tooling support which raises lots of questions:

*

*Is there a better design for this API?

*Is the second format going to be a problem for non-WCF clients?

*Can I make WCF format this data the first way?

*Should I use these types of hierarchies in the XML at all?

A: Your question seems to be both about using WFC for REST and about modeling a concept in REST. I had an idea on your modeling question:

Is there a better design for this API?

What about introducing a new resource to model the mass-import of animals? You might call it something like "Shipment".
A Shipment might be defined as a list of new animals to be introduced into a Zoo. By exposing Shipment as a first-class resource, you would have the ability to manage them, track which Animal came in on which Shipment (to track down a disease outbreak, for example), and enable Shipments to take place at any time, not just during the creation of a Zoo.
Also, don't forget that REST APIs must be hypertext-driven.

A: If you implement the IXmlSerializable interface on your classes you can make the XML look however you want.

A: To answer part of my own question:

*

*Can I make WCF format this data the first way?

Using the XmlSerializer rather than default Data Contracts you can do the following which produces the desired XML:
[XmlArrayItem(typeof(Animal))]
[XmlArrayItem(typeof(Snake))]
[XmlArrayItem(typeof(Giraffe))]
List<Animal> Animals { get; set; }


text:
Q: Form embedded for many to many & many to one in symfony2. I have a problem when I try to embed a form in Symfony2 for many to many relations or many to one relations.
I have two entities called 'Address' and 'AddressType'  and they are related as you can see on code below.
What I tried to do is when I created a form for Address, I embedded the form for AddressType. I've already tried embedding a collection of AddressType to Address form, but when I try to embed the result of this to Address it seems not to work.
Address Entity
namespace Webmuch\ProductBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @ORM\Entity
 */
class Address
{
    protected $id;
    protected $line1;
    protected $line2;
    protected $state;
    protected $city;
    protected $zip;
    protected $country;
    protected $phone;

    /**
     * @ORM\ManyToOne(targetEntity="AddressType")
     * @ORM\JoinColumn(name="address_type_id", referencedColumnName="id")
     */
    protected $type;

    public function __construct()
    {
        $this->type = new ArrayCollection();
    }

    /**
     * Set type
     *
     * @param Webmuch\ProductBundle\Entity\AddressType $type
     */
    public function setType(\Webmuch\ProductBundle\Entity\AddressType $type)
    {
        $this->type = $type;
    }

    /**
     * Get type
     *
     * @return Webmuch\ProductBundle\Entity\AddressType
     */
    public function getType()
    {
        return $this->type;
    }
}

AddressType Entity:
namespace Webmuch\ProductBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class AddressType
{

    protected $id;

    protected $title;

    public function __construct()
    {
        $this->title = false;
    }

}

In form section->
form
AddressType:
namespace Webmuch\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class AddressType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('line1')
            ->add('line2')
            ->add('city')
            ->add('zip')
            ->add('country')
            ->add('phone')
        ->add('type','collection', array( 'type' =>  new AddressTypeType(),
                                              'allow_add' => true,
                                              'prototype' => true,
                                              'by_reference' => false,
                                              ));
    }
    public function getDefaultOptions(array $options)
    {
        return array('data_class' => 'Webmuch\ProductBundle\Entity\Address');
    }

    public function getName()
    {
        return 'address';
    }

}
AddressTypeType:
namespace Webmuch\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class AddressTypeType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('title');
        ;
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Webmuch\ProductBundle\Entity\AddressType',
        );
    }

    public function getName()
    {
        return 'addresstypetype';
    }

}
Controller Section->
namespace Webmuch\AdminBundle\Controller;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
    use Webmuch\ProductBundle\Entity\Address;
    use Webmuch\AdminBundle\Form\AddressType;

    /**
     * Address controller.
     *
     * @Route("/cusadmin/address")
     */
    class AddressController extends Controller
    {
         /**
     * Displays a form to create a new Address entity.
     *
     * @Route("/new", name="admin_address_new")
     * @Template()
     */
        public function newAction()
        {
            $entity = new Address();

            $form   = $this->createForm(new AddressType(), $entity);

            return array(
                'entity' => $entity,
                'form'   => $form->createView()
            );
        }

    }

I've spent the whole day stuck with this and I have tried a lot of things but I couldn't manage get it working.
Any help is appreciated!
Thanks

A: Edit form AddressType: nd write this code,may be this is help full....
 public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('line1')
            ->add('line2')
            ->add('city')
            ->add('zip')
            ->add('country')
            ->add('phone')
            ->add('type','entity', array('class'=>'WebmuchProductBundle:AddressType','property'=>'value','multiple'=>true
             ));


text:
Q: if else statement dateframe I have a dataframe (df):
df<- Column1  Column2 Column3

I want to do an ifelse statement with the mean of the values of Column2 and call including two other dataframes (df2 and df3) in my statement.
Here is the formula I used:
ifelse(mean(df$Column2)<5,df2,df3)

It does not produce df2 or df3 as a dataframe.
What am I doing wrong?

A: From the "stupid but works" department:
get(ifelse(mean(df$Column2)<5,"df2","df3"))


text:
Q: Extracting specific information from data How can i convert a data format like:
James Smith was born on November 17, 1948

into something like
("James Smith", DOB, "November 17, 1948")

without having to rely on positional index of strings
I have tried the following
from nltk import word_tokenize, pos_tag

new = "James Smith was born on November 17, 1948"
sentences = word_tokenize(new)
sentences = pos_tag(sentences)
grammar = "Chunk: {<NNP*><NNP*>}"
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentences)
print(result)

How to proceed further to get the output in desired fromat.

A: Split the string with 'was born on' after that trim the spaces and assign to name and dob

A: You could always use a regular expressions.
The regex (\S+)\s(\S+)\s\bwas born on\b\s(\S+)\s(\S+),\s(\S+) will match and return data from specifically the string format above.
Here's it in action: https://regex101.com/r/W2ykKS/1
Regex in python:
import re

regex = r"(\S+)\s(\S+)\s\bwas born on\b\s(\S+)\s(\S+),\s(\S+)"
test_str = "James Smith was born on November 17, 1948"

matches = re.search(regex, test_str)

# group 0 in a regex is the input string

print(matches.group(1)) # James
print(matches.group(2)) # Smith
print(matches.group(3)) # November
print(matches.group(4)) # 17
print(matches.group(5)) # 1948


text:
Q: Integral question tricky We're asked to evaluate the integral $\int_{-\infty }^{\infty }\dfrac{dx}{%
(x^{2}+1)^{3}}.$. For some reason, the methods I tried lead nowhere :(
Any suggestions? Thank you!

A: You asked for suggestions so this is what you will get:
try to use the residual theorem and use the facts that:

*

*$\left(x^{2}+1\right)^{3}=\left(x+i\right)^{3}\left(x-i\right)^{3}$

*the integral of your function on a curve in $\mathbb{C}$ which is "very very far away" from $i$ and $-i$ and which is "connecting $-\infty$ and $+\infty$" equals zero.
I do not want to go into more detail because this seems to be a homework. :-P

A: A simple method is using trigonometric substitution that $x=\tan(y)$. Then the integral have been transform by
\begin{equation}
\int_{-\pi/2}^{\pi/2}\frac{1/\cos(y)^2}{1/\cos(y)^6}dy=\int_{-\pi/2}^{\pi/2}\cos(y)^4dy=2\int_0^{\pi/2}\cos(y)^4dy=\frac{3\pi}{8}
\end{equation}

A: The integrals $$I_n=\int_{-\infty }^{\infty }\dfrac{dx}{%
(x^{2}+1)^{n}}.$$ are not as tricky as you could think. These have to asked several times on this site and received nice answers.
If,as already suggested in many other answers, you change variable (setting $x=\tan (\theta )$) and proceed as it has been done in previous answers to posts, they reduce to
$$ I_n=  \int_{0}^{\pi/2} \cos^{{2n-2}}(\theta) d\theta $$ and using multiple angle formula
you arrive to $$I_n=\frac{\sqrt{\pi } \Gamma \left(n-\frac{1}{2}\right)}{\Gamma (n)}$$


text:
Q: Jest coverage test does not include 'rewired' files I am including my non-exported function (let's say A) to the Jest unit tests with the 'rewire' function. When I run the coverage test, the A function is not included to the coverage test. Is there any way to include rewired files to the coverage test?
Is there any configurations which should be provided to the babel.config.json?
{
  "presets": ["@babel/preset-env"],
  "plugins": ["babel-plugin-rewire"]
}


text:
Q: Print unicode and text values of char pointer I am new to c++, I am trying to print some values on console.
I am using below code for this
std::cout  << "text : " << text.latin1().data() <<endl;

text.latin1().data() returns a char* to me.
It works fine as long as values are normal ASCII but it prints "?" for special characters like alpha, beta and gamma (may be for utf-8).
text is WTF::String
latin1 is WTF::CString
and data is char*
How can I get the unicode values for the given char* and print their string values instead of "?".
Thanks

A: std::wcout << L"text : " << text.characters() << wendl;

Does it work ? If not what's the compiler error message ?


text:
Q: Redux-Form reducer plugin not causing component to rerender I have been trying to follow the example here.
I have code containing the following:
export default reduxForm({form: 'AlertTriggerSettingsForm'})(AlertTriggerSettingsFormContainer)

...
export default combineReducers({
  form: formReducer.plugin({ AlertTriggerSettingsForm: alertTriggerSettings })
})

...
const alertTriggerSettings = (state = initialState, action) => {
  switch (action.type) {
    case ACTION_VARIABLE_CHANGE:
      return {
        ...state,
        currentVariable: action.variable,
        values: {
          currentHighValue: '55',
          currentLowValue: '66'
        }
      }
  }
}

...
<Field name='currentLowValue'
      label='Low Set Point:'
      component={HighLowInputField} />

...
const HighLowInputField = ({ label, input: { value, onChange }, meta: { error } }) => (

    {label}
    <input
      onChange={onChange}
      className='form-control'
      type='number' />

)

When the reducer is called, in Redux dev tools I can see that the state is successfully updated, however the component fails to rerender and no @@redux-form/CHANGE event is dispatched.  When I manually enter input into the field, the event is dispatched and the state and component are updated accordingly.

A: Just trying to understand more here.
Are you using redux here?
If so, is it all connected - like this
let myForm = reduxForm({form: 'AlertTriggerSettingsForm'})(AlertTriggerSettingsFormContainer)

const mapStateToProps = (state) => ({
    // Your state here
})

let connectedPage = connect(mapStateToProps)(myForm);

export { connectedPage as MyComponent };


text:
Q: Extracting name of stored procedures from a file, if a particular table is used in it using regex I have a SQL file in which more than one stored procedures are there. I have been given a table name and need to find out in which stored procedure is that table used. It would be nice if answer is given in C#.
Eg. Given two procedures an table name "ucg2.userCompanyId" , we need to tell that which procedure use it.
CREATE PROCEDURE  [dbo].[ActiveUsersAM_prc]
--ActiveUsers_getdata_prc
    @Usercompanyid varchar(max)
AS
Begin

IF OBJECT_ID('tempdb..#ActiveUserCompany') IS NOT NULL
DROP TABLE #ActiveUserCompany

CREATE TABLE #ActiveUserCompany
(userCompanyId INT)

INSERT INTO #ActiveUserCompany
SELECT val FROM dbautil.dbo.Split_fn(@userCompanyID,',')

CREATE CLUSTERED INDEX ix_usercompanyId ON #ActiveUserCompany(userCompanyId)

SELECT * FROM dbo.ActiveUsersAMCache_tbl (nolock)
WHERE userCompanyId IN (SELECT userCompanyId FROM #ActiveUserCompany (nolock))

END

and
CREATE PROCEDURE  [dbo].[ActiveUsersRelatedCompanies_prc]
    @Usercompanyid INT
AS
Begin

select *
FROM dbo.ActiveUsersRelatedCompanies_tbl (NOLOCK)
WHERE userCompanyId in (
        select  ucg2.userCompanyId
        from    userCompanyGrouping_tbl u
                inner join userCompanyGrouping_tbl ucg2
                    on isNull(u.subParentCompanyId,u.parentCompanyId) =
                        (case when u.subParentCompanyId is not null then ucg2.subParentCompanyId
                            else ucg2.parentCompanyId end)
        where   u.userCompanyId = @userCompanyID
)
order by userCompanyName, userGroup, fullName
END

A: There are some simplifications in here, but it should provide a good start.
// Read content
string content = File.ReadAllText(filename);
// Separate procedures from each other
// (you might have to use "ToUpper()" before)
string[] procs = content.Split(new string[] { "CREATE PROCEDURE" }, StringSplitOptions.None);
// Check if one of them contains the table name
string table = "ucg2.userCompanyId";
foreach (string proc in procs)
{
    // If it does, print the first line (which holds the name of the stored procedure
    // (Using regex here might be necessary, depending on the source)
    if (proc.Contains(table))
    {
        Console.WriteLine(proc.Split(new string[] { "\r\n" }, StringSplitOptions.None)[0]);
    }
}


text:
Q: Form won't return results and domain as required So, I have a form, with the following script tag after the form

When the form is submitted, I want the URL that is searched, to appear in the /:URL portion of the slug, and to return the required JSON.
However, this does not seem to be working, and I get a 404 error when running on my local host. The search bar page loads fine, but does not lookup /:URL
Any advice?
Here is a copy of my form:
<form action="/lookup/:url" method="GET">

                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                    <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11"></path>
                </svg>

                <input name="search" type="text" placeholder="Paste a domain here" />

                <button class="btn-search" type="submit">SEARCH</button>

                ex. JeepBeef.com
</form>


text:
Q: How to find value of $c$ in $ax^2+bx+c=0$ having the $a$ and $b$? Problem: solve (find roots): $ 7x^2-3x=0$.
How to find $c$ in order to solve using the Quadratic Formula?

A: HINT
Here $c=0$, so it is easier to simply factor to find the roots: $$x(7x-3)=0$$

A: In your case $c = 0$.
$$
7 x^2 -3x = 7 x^2 -3x + 0 = a x^2 + bx + c
$$
So
$$
a = 7\quad b=-3\quad c=0
$$

A: I think you mean $ax^{2}+bx+c=0$, here you simply have $c=0$. Further, there's no need for the quadratic formula, $x(7x-3)=0$

A: $c$ is $0$ in this case. You can use the Quadratic formula right away to find $x=\frac{3\pm{\sqrt{9-0}}}{14}$ or factorize to get $f(x) = x(7x-3)$.

A: Well, you don't need the quadratic formula here. Note that $7x^2-3x = x(7x-3)$, so this is equal to $0$ only when either $x = 0$ or $7x-3 = 0$, that is, when $x=0$ or $x = \frac{3}{7}$.


text:
Q: How to activate terminal auto completion on macOS Catalina I've just clean installed macOS Catalina and the usual way of activating auto complete does not work for me. I use the default shell zsh:
1 Type in terminal nano ~/.inputrc
2 Paste the following on separate lines

set completion-ignore-case on
set show-all-if-ambiguous on
TAB: menu-complete

3 Hit control+O to save changes to .inputrc followed by control+X to exit nano
4 Open a new Terminal window or tab to open a new session with autocomplete enabled

What am I missing?

A: If you have done a fresh install then you need to be aware that the default shell has changed to zsh which as I understand it doesn't read .inputrc.
So either change your default shell back in System Preferences -> Users & Groups or
use .zshrc instead for your configurations

A: After new installation just run this command in your zsh terminal:
autoload -Uz compinit && compinit


text:
Q: Resources Exceeded During Query Execution: Custom Dimensions & MAX(IF(...)) I'm performing what I thought was a simple events query in BigQuery with two custom dimensions. When trying to execute this query for year-to-date, I get the following error:

query: Resources exceeded during query execution. (error code:
  resourcesExceeded)

Research of this error and investigation of the 'resourcesExceeded' error code indicates that this happens most frequently when using windowed functions, joins, count(distinct()) or group by each, none of which I am using here. The only thing I am doing is order by Date asc, which doesn't appear to eliminate the error when that line is removed. Since this is a shard resources issue, I think this has to be related to the two custom dimensions I'm trying to pull, since the MAX/IF function seem to be the most resource intensive portions of this query. Here's a snippet of the query I'm running:
SELECT
      DATE,
      userId,
      fullVisitorId,
      visitId,
      trafficSource.source,
      trafficSource.medium,
      trafficSource.campaign,
      trafficSource.adContent,
      MAX(IF (hits.customDimensions.INDEX = 1,hits.customDimensions.value,NULL)) WITHIN RECORD AS XXXXXX,
      MAX(IF (hits.customDimensions.INDEX = 2,hits.customDimensions.value,NULL)) WITHIN RECORD AS YYYYYY,
      totals.visits,
      totals.bounces,
      totals.pageviews
FROM (
      TABLE_DATE_RANGE([########.ga_sessions_],
            TIMESTAMP('2016-01-01'), # start date
            TIMESTAMP('2016-07-31')) # end date
      )
ORDER BY DATE ASC;

I've tried this query both through the BigQuery console UI as well as from the command line. I've also set the option, 'allowLargeResults' to True.


text:
Q: Unable to stimulate change event in child component React redux jest I am new to react redux and I am trying to unit test FormContainer component. But I am unable to simulate change event on Form component using enzyme or jest. In wrapper.instance() I am receiving null but I dont' think that should. If not then what is correct way of testing FormContainer.js file, because when I ran test coverage it showed me that change function was uncovered.
FormContainer.js
import React, { Component } from "react";
import { connect } from "react-redux";
import Form from "../components/Form";
import { isNumeric } from "../utils";

class FormContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      number: "",
      error: false
    };
  }
  // componentWillReceiveProps(nextProps) {
  //   console.log(nextProps, this.props, "main component");
  // }

  change = event => {
    let value = event.target.value;
    if (isNumeric(value) && value < 1001 && value >= 0) {
      if (value === "0") {
        this.setState({
          ...this.state,
          error: true
        });
        return;
      } else {
        this.setState({
          ...this.state,
          [event.target.name]: value,
          error: false
        });
      }
    } else {
      this.setState({ ...this.state, error: true });
    }
  };

  render() {
    return (
      <Form change={this.change} value={this.state} error={this.state.error} />
    );
  }
}
const mapStateToProps = state => {
  return { ...state };
};

export default connect(mapStateToProps)(FormContainer);

FormContainer.test.js
import React from 'react';
import configureStore from "redux-mock-store";
import { shallow,mount } from 'enzyme';
import FormContainer from '../../containers/FormContainer';
import { findByAttr } from '../../utils';
import Form from '../../components/Form';

describe("Testing Form container", () => {
    let wrapper;
    let store;
    beforeEach(() => {
        const initialState = {}
        const mockStore = configureStore();
        store = mockStore(initialState);
        wrapper = shallow(<FormContainer store={store} />);
    });
    it("Should render without error ", () => {
        expect(wrapper.exists()).toBe(true);
    });

    it("Simulate change", () => {
        let component = wrapper.find(Form);
        const mockChange = jest.fn();
        wrapper.instance().change = mockChange;
    });
});

Testing Form container › Simulate change
TypeError: Cannot set property 'change' of null

  22 |         let component = wrapper.find(Form);
  23 |         const mockChange = jest.fn();
> 24 |         wrapper.instance().change = mockChange;
     |         ^
  25 |     });
  26 | });

  at Object.<anonymous> (src/__test__/containers/FormContainer.test.js:24:9)

A: Dont need to import import Form from '../../components/Form'; since we are only testing FormContainer component, so remove it.
and there is no event listener called change, Use onChange instead.
<Form onChange={this.change} value={this.state} error={this.state.error} />

Try changing this spec:
it("Simulate change", () => {
    let component = wrapper.find(Form);
    const mockChange = jest.fn();
    wrapper.instance().change = mockChange;
});

To:
it("Simulate change", () => {
    (wrapper.find(Form).first()).simulate('change');
    expect(wrapper.instance().change.mock.calls.length).toBe(1);
});