text:
Q: ReactJS vs NodeJS - Why do I need to create both? I understand that React is frontend, and NodeJS is the backend that allows Javascript code to function outside of a browser. What I don't understand (and this is after following tutorials online on setting up a React project and a NodeJS project) is why I have to create an instance of each.
For example, in my React project, I managed to create a website. But because I needed a backend, I decided to use NodeJS. But I'm doing NodeJS tutorials, and I can create a website using NodeJS too. I'm confused because right now, it's appearing to be that React and NodeJS do the SAME THING.
I have never worked with NodeJS before so I am a bit confused. I was under the impression that I would just use NodeJS to host the backend, but after seeing that I'm literally having to create an entire website with NodeJS, I don't understand how I'm supposed to use React and NodeJS together.
How do the two, React and NodeJS, integrate together to create a fully-functioning web app? I have yet to see something online that clearly breaks down how the two interact.

A: NodeJS is just a runtime that allows you to run javascript code outside of the browser.
In order to compile and transpile the react JS app, they use webpack and other tools which runs over NodeJS.

A: React is front-end library. It provides great tooling for creatiing user interfaces. And it creates a single page application. Which means when you open a react app. It does not reload and its really fast.
While you could also use nodejs and something like handlebars to create a website. But that website would be rendered on server and then served to the user. But its alot more than that. There are a lot of things that you want to do on the server. Like authentication. You want that part to be secure. So you keep it on the server.
Now the answer to the final part of your question.
For a fully functional app. You would use react to create user interfaces. And nodejs for creating an API which your react app will call.

A: NodeJS is not just regular javascript, it is a javascript runtime that sits on top of a C++ engine called V8, provided by Google. Node executes outside the browser, whereas React / Vue / Angular / etc are in-browser javascript frameworks.
React is a whole separate animal; it is a framework that renders its own DOM in the browser.   It is a javascript engine that is configured to optimize DOM manipulation.
While the development pattern of frontend and backend appear similar, they are doing different things. React is handling component lifecycles, applying dynamic style rules, processing in-browser data, and making API calls. Node is handling requests from the browser, coordinating access to the server's file system, managing network I-O, performing cryptographic evaluation, etc. Because of these different responsibilities, Node makes use of different dependencies (read: node modules) than a frontend framework.
Ultimately, Node and React communicate through HTTP calls (or, less frequently, through a WebSocket or SOAP protocol).
It would behoove you to read about how node works under the hood.

A: NodeJS will serve as your backend, whereas ReactJS will create the interface/UI where you can actually manipulate your server (nodeJS). So first you'll write your NodeJS server or API. You don't need to use ReactJS to create a frontend that would interact with your node server, like you said you can use NodeJS to create your views as well through a different library. ReactJS is just one choice of many for the front end of your NodeJS app.

A: The point is that react and any other SPA library is working on a client-side (browser).
React fetch and consume the data from the server API.
You don't need to use Node.js for building API. You can use various frameworks based on the technology you prefer.
If you are not familiar with the Back End, you can use https://www.npmjs.com/package/http-server to have a fake API service and can build the Front End part with it.

A: NodeJS is a javascript framework that allows you to create a server to serve up websites using Express or the built in libraries. It also is capable of building a website with just NodeJS.
You can take advantage of the ability to do server side rendering with a NodeJS server.
https://reactjs.org/docs/react-dom-server.html
There is a ReactJS framework called NextJS tha has server side rendering of ReactJS component.
https://nextjs.org/#features
You could potentially have some areas of your website that are built solely with NodeJS and other pages that use ReactJS and a NodeJS backend. But it is cleaner to use ReactJS for the front-end and NodeJS for the backend.


text:
Q: Examples of self-dual categories Call a category $C$ self-dual if there exists an equivalence of categories $F: C \rightarrow C^{op}$. I am looking for examples of self-dual categories. Rigid monoidal categories and more generally star-autonomous categories are self-dual essentially by definition. What are other classes of examples? Are there self-dual categories that do not admit a star-autonomous monoidal structure?

A: The category $\text{Mod}_f(\mathbb{H})$ of finite rank modules over the quaternions $\mathbb{H}$ is an example that doesn't admit any closed monoidal structure; the self-duality is given by taking the $\mathbb{H}$-linear dual, which is canonically an $\mathbb{H}^{op}$-module, then applying the isomorphism $\mathbb{H} \cong \mathbb{H}^{op}$ given by quaternionic conjugate to get an $\mathbb{H}$-module structure.
This category admits no closed monoidal structure because no nonzero object has a commutative monoid of endomorphisms and hence no nonzero object could be the monoidal identity (by the Eckmann-Hilton argument). And if the zero object is the monoidal identity in a closed monoidal category then every hom space is zero.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where does the job status in GKE come from? And why is it different than 'kubectl get job' The GKE UI shows a different status for my job than I get back from kubectl. Note that the GKE UI is the correct status AFAICT and kubectl is wrong. However, I want to programmatically get back the correct status using read_namespaced_job in the Python API, however that status matches kubectl, which seems to be the wrong status.
Where does this status in the GKE UI come from?
In GKE UI:
apiVersion: batch/v1
kind: Job
metadata:
  creationTimestamp: "2020-06-04T08:00:06Z"
  labels:
    controller-uid: ee750648-1189-4ed5-9803-054d407aa0b2
    job-name: tf-nightly-transformer-translate-func-v2-32-1591257600
  name: tf-nightly-transformer-translate-func-v2-32-1591257600
  namespace: automated
  ownerReferences:
  - apiVersion: batch/v1beta1
    blockOwnerDeletion: true
    controller: true
    kind: CronJob
    name: tf-nightly-transformer-translate-func-v2-32
    uid: 5b619895-4c08-45e9-8981-fbd95980ff4e
  resourceVersion: "16109561"
  selfLink: /apis/batch/v1/namespaces/automated/jobs/tf-nightly-transformer-translate-func-v2-32-1591257600
  uid: ee750648-1189-4ed5-9803-054d407aa0b2

...

status:
  completionTime: "2020-06-04T08:41:41Z"
  conditions:
  - lastProbeTime: "2020-06-04T08:41:41Z"
    lastTransitionTime: "2020-06-04T08:41:41Z"
    status: "True"
    type: Complete
  startTime: "2020-06-04T08:00:06Z"
  succeeded: 1

From kubectl:
zcain@zcain:~$ kubectl get job tf-nightly-transformer-translate-func-v2-32-1591257600 --namespace=automated -o yaml
apiVersion: batch/v1
kind: Job
metadata:
  creationTimestamp: "2020-06-04T08:00:27Z"
  labels:
    controller-uid: b5d4fb20-df8d-45d8-a8b5-e3b0c40999be
    job-name: tf-nightly-transformer-translate-func-v2-32-1591257600
  name: tf-nightly-transformer-translate-func-v2-32-1591257600
  namespace: automated
  ownerReferences:
  - apiVersion: batch/v1beta1
    blockOwnerDeletion: true
    controller: true
    kind: CronJob
    name: tf-nightly-transformer-translate-func-v2-32
    uid: 51a40f4a-5595-49a1-b63f-db75b0849206
  resourceVersion: "32712722"
  selfLink: /apis/batch/v1/namespaces/automated/jobs/tf-nightly-transformer-translate-func-v2-32-1591257600
  uid: b5d4fb20-df8d-45d8-a8b5-e3b0c40999be

...

status:
  conditions:
  - lastProbeTime: "2020-06-04T12:04:58Z"
    lastTransitionTime: "2020-06-04T12:04:58Z"
    message: Job was active longer than specified deadline
    reason: DeadlineExceeded
    status: "True"
    type: Failed
  startTime: "2020-06-04T11:04:58Z"[enter image description here][1]

Environment:
Kubernetes version (kubectl version):
Client Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.9", GitCommit:"2e808b7cb054ee242b68e62455323aa783991f03", GitTreeState:"clean", BuildDate:"2020-01-18T23:33:14Z", GoVersion:"go1.12.12", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"15+", GitVersion:"v1.15.9-gke.26", GitCommit:"525ce678faa2b28483fa9569757a61f92b7b0988", GitTreeState:"clean", BuildDate:"2020-03-06T18:47:39Z", GoVersion:"go1.12.12b4", Compiler:"gc", Platform:"linux/amd64"}

OS:
cat /etc/os-release PRETTY_NAME="Debian GNU/Linux rodete"

Python version (python --version):
Python 3.7.7

Python client version (pip list | grep kubernetes):
kubernetes 10.0.1

A: For anyone else who finds a similar issue:
The problem is with the kubeconfig file (/usr/local/google/home/zcain/.kube/config for me)
There is a line in here like this:
current-context: gke_xl-ml-test_europe-west4-a_xl-ml-test-europe-west4
If the current-context is pointing to a different cluster or zone than where your job ran, then when you run kubectl job get or use the Python API, then the job status you get back will be weird. I feel like it should just error out but instead I got the behavior above where I get back an incorrect status.
You can run something like gcloud container clusters get-credentials xl-ml-test-europe-west4 --zone europe-west4-a to set your kubeconfig to the correct current-context


text:
Q: Relative URLs in AJAX requests in MVC application I tried to make sense of the results I got (see ajax call below) in relation to this post:
Relative URLs in AJAX requests
The comments annotated with [WORKS and [FAILS] below show various URLs that worked and failed.  Since the above post only talked about document based URLs, I tried to make the analogy that a method in a controller corresponds to a document and a controller to folder.  However, the results below belie that analogy.
CAS is a MVC application which runs off the root of a website. Subject is a controller.  Index, GetSubject and RegisterSubject are methods in the Subject controller.
Not all of these URLs should work.  However, I cannot explain why one does another does not.
EDIT: UrlHelpers. I want to understand the rules.  What are the rules for resolving a MVC type of url:  http://[domain]/[MVC App]/[Controller]/[Method]/ [params] where params is like [p1/p2/ . . ].
I don't see the pattern.  As noted below the document url =  [http://localhost/cas/Subject/Index] when either method is called.
var ajaxService = (function () {

    var ajaxGetJson = function (method, jsonIn, callback, errorCallback, controller) {
        var ajaxUrl = getSvcUrl(method, controller);
        var docUrl = document.URL; // at his point document url =  http://localhost/cas/Subject/Index

        //[WORKS] when ajaxUrl = ../GetSubject/359143 where 359143 is the id of Subject in database
        //        correctly resolves to http://localhost/cas/Subject/GetSubject/359143

        //[FAILS] when ajaxUrl = ../RegisterSubject
        //        resolves to http://localhost/cas/RegisterSubject  <-- notice Subject controller is missing.

        //[FAILS] when ajaxUrl = /RegisterSubject --> resolves to http://localhost/RegisterSubject

        //[WORKS] when ajaxUrl = "RegisterSubject" or "RegisterSubject/
        //        resovles to http://localhost/cas/Subject/RegisterSubject

        //[FAILS] when ajaxURL = "GetSubject"/359143"
        //        resolves to http://localhost/cas/Subject/Index/GetSubject/359143

        if (method === "RegisterSubject") { //workaround for the above failure
            ajaxUrl = "http://localhost/cas/Subject/RegisterSubject";
    }

    $.ajax({
        url:  ajaxUrl, //getSvcUrl(method, controller),
        type: "GET",
        data: ko.toJSON(jsonIn),
        dataType: "json",
        contentType: "application/json",
        success: function (json) {
            callback(json);
        },
        error: function(json) {
            errorCallback(json);
        }});
    }

    // other AJAX types omitted

    return {
        ajaxGetJson: ajaxGetJson;
    };
}


text:
Q: Is it possible to use std::enable_if to select a member template specialization? Given a class declaration
class A {
    template <typename T> T foo();
};

I would like to specialize A::foo for various types (int, ...) and type classes (POD, non-POD) of T. Unfortunately, I cannot seem to use std::enable_if for the latter. The following doesn't compile:
template <> int A::foo<int>(); // OK

template <typename T>
typename std::enable_if<is_pod<T>::value, T>::type foo(); // <<<< NOT OK!

template <typename T>
typename std::enable_if<!is_pod<T>::value, T>::type foo(); // <<<< NOT OK!

The issue is probably due to the std::enable_if<...> stuff being part of the function signature, and that I did not declare any such member inside A. So how can I specialize a template member based on type traits?

A: I'd just forward this to a structure, which does handle this well:
#include <type_traits>
#include <iostream>

template <typename T, typename = void>
struct FooCaller;

class A {
public:
    template <typename T>
    T foo() {
        // Forward the call to a structure, let the structure choose
        //  the specialization.
        return FooCaller<T>::call(*this);
    }
};

// Specialize for PODs.
template <typename T>
struct FooCaller<T, typename std::enable_if<std::is_pod<T>::value>::type> {
    static T call(A& self) {
        std::cout << "pod." << std::endl;
        return T();
    }
};

// Specialize for non-PODs.
template <typename T>
struct FooCaller<T, typename std::enable_if<!std::is_pod<T>::value>::type> {
    static T call(A& self) {
        std::cout << "non-pod." << std::endl;
        return T();
    }
};

// Specialize for 'int'.
template <>
struct FooCaller<int> {
    static int call(A& self) {
        std::cout << "int." << std::endl;
        return 0;
    }
};

A: I see no reason to specialize here, overloading the function seems to suffice in my mind.
struct A
{
    template <typename T>
    typename std::enable_if<std::is_integral<T>::value, T>::type foo()
    {
        std::cout << "integral" << std::endl;
        return T();
    }

    template <typename T>
    typename std::enable_if<!std::is_integral<T>::value, T>::type foo()
    {
        std::cout << "not integral" << std::endl;
        return T();
    }
}

When checking for POD or no POD, you only have these two choices, so a more generic function is not needed (and not allowed, because it would be ambiguous). You need more than that? You can check for explicit types without specialization with the help of std::enable_if<std::is_same<int, T>::value, T>::type.


text:
Q: How to retrieve data from two MySQL tables with multiple associations I got these two tables where one table is having multiple foreign keys to the second table.
Table rankings
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| id             | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| search_text    | varchar(255) | YES  | MUL | NULL    |                |
| first_item_id  | bigint(20)   | YES  | MUL | NULL    |                |
| second_item_id | bigint(20)   | YES  | MUL | NULL    |                |
| third_item_id  | bigint(20)   | YES  | MUL | NULL    |                |
| forth_item_id  | bigint(20)   | YES  | MUL | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

Table item
+---------------------------+--------------+------+-----+---------+----------------+
| Field                     | Type         | Null | Key | Default | Extra          |
+---------------------------+--------------+------+-----+---------+----------------+
| id                        | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| item_code                 | varchar(255) | YES  | MUL | NULL    |                |
+----------------+--------------+------+-----+---------+---------------------------+

One ranking record may have multiple association to item table using first_item_id, second_item_id, third_item_id or forth_item_id fields. I want to retrieve ranking records with the corresponding item_code instead of the item.id. What would be the most efficient way to do this if i have a big number of data?
PS: There are 10 associations to the item.id as first_item_id ... tenth_item_id. Im using Rails ActiveRecord ORM. Any workaround with that also fine.
Sample data ranking
SELECT id,search_text,first_item_id as first,second_item_id as second,third_item_id as third,forth_item_id as forth from rankings limit 10;
+----+-------------+-------+--------+-------+-------+
| id | search_text | first | second | third | forth |
+----+-------------+-------+--------+-------+-------+
|  1 | test 1      |     1 |      2 |     3 |     4 |
|  2 | test 2      |     1 |      2 |     3 |     4 |
|  3 | test 3      |     1 |      2 |     3 |     4 |
|  4 | test 4      |     1 |      2 |     3 |     4 |
+----+-------------+-------+--------+-------+-------+

Sample item data
SELECT id,item_code from items limit 5;
+--------+------------+
| id     | item_code  |
+--------+------------+
|      1 | 125659     |
|      2 | 125660     |
|      3 | 125661     |
|      4 | 125662     |
+--------+------------+

Expected data
+----+-------------+-------+--------+-------+-------+
| id | search_text | first | second | third | forth |
+----+-------------+-------+--------+-------+-------+
|  1 | test 1      | 125659| 125660 | 125661| 125662|
|  2 | test 2      | 125659| 125660 | 125661| 125662|
|  3 | test 3      | 125659| 125660 | 125661| 125662|
|  4 | test 4      | 125659| 125660 | 125661| 125662|
+----+-------------+-------+--------+-------+-------+

A: Joining the table multiple times (even many, many times) should not be a problem, as you are joining on the primary key, i.e. you have an index that will be used.
select
  r.id,
  r.search_text,
  i1.item_code as item_code_1,
  i2.item_code as item_code_2,
  i3.item_code as item_code_3,
  i4.item_code as item_code_4
from rankings r
left join item i1 on i1.id = r.first_item_id
left join item i2 on i2.id = r.second_item_id
left join item i3 on i3.id = r.third_item_id
left join item i4 on i4.id = r.forth_item_id
order by r.id;

I am using outer joins here, because all your item columns are nullable.


text:
Q: Count ocurrencies of pattern in pandas dataframe based on condition Consider this dataframe:
pd.DataFrame(['A(3)BC(1)', 'A(2)BC(5)', 'A(1)BC(3)', 'A(2)BC(5)', 'A(4)BC(2)'], columns=['Column1'])

    Column1
0   A(3)BC(1)
1   A(2)BC(5)
2   A(1)BC(3)
3   A(2)BC(5)
4   A(4)BC(2)

Is there a way to count the number of times A has a number higher than (3) without iterating through every line of the dataframe?

A: Let's try
out = df['Column1'].str.extract('A\((\d+)\)')[0].astype(int).gt(3).sum()

print(out)

1

A: If the format is always A(X) at the start, you can do:
df['Column1'].apply(lambda st: int(st[st.find("A")+2:st.find(")")])).gt(3).sum()
Output
1


text:
Q: Is there a good example passing build parameters with Python jenkinsapi and why is the below example failing? I'm trying to invoke a job using the Python jenkinsapi package. I am able to kick of the build using jop.py no problem, but when trying to pass string parameters to the Jenkins server the parameters are not being picked up and the default values configured on the Jenkins server are being used instead.
Here's a quick example of what I'm using using job.py invoke:
my_job.invoke(securitytoken = 'mytoken', params = {'param1':'value1', 'param2':
'value2'})

Again, the above kicks off the build successfully on the Jenkins server, but none of the parameter values are picked up by the Job on the server and instead the default values in the Job config on the server are used instead.
Could someone tell me what is wrong with the above usage? Are there other parameters that are needed? Does someone have an example of invoking parameterized builds using jenkinsapi?
This is for jenkinsapi 0.1.16

A: After digging into this one a bit more, it turns out the URL was not getting constructed properly. By changing line 91 in jenkinsbase.py in version 0.1.16 using Python 2.6.4 I was finally able to get the build parameters to pass properly:

*

*if params: stream = fn_urlopen( url, urllib.urlencode(params) )

*if params: stream = fn_urlopen( url + '?' + urllib.urlencode(params) )

After changing this line in jenkinsbase.py, the example in my original question had the build parameters passed into the job correctly.


text:
Q: Power Dissipated by Resistor in AC Circuit I'm having a problem with the following review question:
Given the circuit:

I am asked to find the power dissipated by R1 and C. I know that for C it is 0. For R1, I know I need to use Vrms (120*rt2 V/rt2) = 120 V. I'm stuck as to where to go from here. I thought about using a voltage divider to find the voltage on R1, then using V^2/R to get the power, but I don't know how to do this with three resistors.

A: Break it into two problems. First, consider the three resistors in series, and replace them with a single equivalent resistor. Now you can figure out how much current flows through the capacitor, and how much through the resistor. You correctly figured out there is no power dissipation through the capacitor, since current and voltage will be in quadrature; and since there is no internal impedance on the voltage source, the current through the resistor doesn't depend on the presence of the capacitor.
Once you know how much current is flowing, you can remove the capacitor and figure out what fraction of the current flows through the resistor you are asked about. And use $\frac12 I^2 R$ to obtain the power.


text:
Q: FluentValidation Rule for MVC DropDownListFor? I am trying to validate dropdown list using FluentValidation. I think I am doing wrong, but not able to find to solution. I need your help.
Model
 [FluentValidation.Attributes.Validator(typeof (MeetingAbstractValidator))]
 public class MeetingAbstract
 {
     public string CompanyAllowedBoolLabel { get; set; }
     public string CompanyAllowedBoolOptions { get; set; }
     public string CompanyAllowedBoolText { get; set; }
     ...
 }

class MeetingAbstractValidator : AbstractValidator<MeetingAbstract>
{
     public MeetingAbstractValidator()
     {
        RuleFor(x => x.CompanyAllowedBoolText).NotEqual("Select Option...").
        WithMessage(i18n_Models_Abstract.RequiredField); ;

  }
}

view

@Html.Label(Model.CompanyAllowedBoolLabel,
               new { @class = "control-label mandatory" })

            @{

                var options = Model.CompanyAllowedBoolOptions;
                var optionsList = options.Split(',').ToList();
                var optionSelect = optionsList.Select(option =>
                 new SelectListItem() { Text = option, Value = option }).ToList();
                optionSelect.Insert(0,new SelectListItem() {
                             Text = "Select Option...", Value = "0" });
            }
            @Html.DropDownListFor(model => model.CompanyAllowedBoolText,
                optionSelect,
                 new { @class = "input-validation-error form-control" })
            @Html.ValidationMessageFor(model => model.CompanyAllowedBoolText)

Generated HTML

   <select class="form-control valid" id="CompanyAllowedBoolText"
                              Name="CompanyAllowedBoolText">
          <option value="0">Select Option...</option>
          <option value="да/yes">да/yes</option>
          <option value="нет/no">нет/no</option>
    </select>

Its working for textboxes. not dropdowns.

A: make sure that value is empty for select option

optionSelect.Insert(0,new SelectListItem() {
                               Text = "Select Option...", Value = "" });

and then add this

RuleFor(x => x.CompanyAllowedBoolText).NotEmpty().WithMessage("your error
  message");

A: Part of the problem is that you shouldn't be validating specific kinds of controls.  Validating a dropdown list should be no different from validating a textbox, it's all about the selected value.  When a form posts a DropDownList to the server, it only posts the value, not the text.  You're checking for the text.
Another part of the problem is that you are not correctly building your drop down list.  You should use the built-in functionality for the unselected value.  I'm not sure why you're trying to include validation css classes.  You shouldn't be.  ie:
@Html.DropDownListFor(model => model.CompanyAllowedBoolText, optionSelect,
     "Select Option...")

In this case, if the user does not select anything, the value will be either null or empty.  So you need only use a required validation.  Remember, the text doesn't get posted, only the value.
RuleFor(x => x.CompanyAllowedBoolText).NotNull().NotEmpty().
    WithMessage(i18n_Models_Abstract.RequiredField);

A: From your generated html (and drop down creation code), posted values of CompanyAllowedBoolText can be

*

*0

*да/yes

*нет/no

So the  option's VALUE , not the option's "text".
So your rule should check for
RuleFor(x => x.CompanyAllowedBoolText).NotEqual("0").<bla bla bla>();


text:
Q: Fractal dimension after nonlinear transformation Let's assume X(s) is a fractal surface with Hausdorff dimension D. Now we take a nonlinear transformation f which transforms X(s) to f(X(s)). In this case, what will be the Hausdorff dimension of the transformed surface f(X(s))?
More clarification (asked by Theo Buehler) > Let's start with a simple example of one dimensional random walk. The path of the random walker becomes a fractal with the Hausdorff dimension 1.5. Let's call the path $X(t)$ at time $t$. Then we can think about the path $Y(t)=X(t)^3−2X(t)$. What will be the Hausdorff dimension of $Y(t)$?
Added (by anon) > Let's add the condition for $f$. $f$ is continuous, differentiable and bounded. In this case, will the Hausdorff dimension remain the same?

A: If a map $f$ is Lipschitz ( that is, $|f(x)-f(y)| \le M |x-y|$ for some constant $M$ ), then is does not increase Hausdorff dimension: $\dim f(K) \le \dim K$.  An example of a Lipschitz function is one that is differentiable with bounded derivative.  Dimension does not increase, but it may decrease.


text:
Q: Positioning controls in the middle of a CheckBox THis is a followup to my previous question "Font-dependent control positioning." It's an attempt to solve the real problem behind that question, perhaps in ways different than the one I was asking about.
Example of the problem statement: I want a checkbox that says "Adjust prices by <X> <Y> after loading," where <X> is a number---adjustable with a NumericUpDown---and <Y> is either "percent" or "dollars," with the choices being made by a ComboBox. This will be on a single line.
The complication: I want to be able to change my fonts for all these controls (basically setting them to System.Drawing.Fonts.MessageBoxFont, which is Tahoma 8 pt on Windows XP/etc. and Segoe UI 9 pt on Vista), without messing up my layout, which with my current Position-property--setting paradigm does not work.
More generally, I'd like the controls to be dynamically laid out in a font-independent way, so that the <X> NumericUpDown fits snugly into the space between "by " and the <Y> ComboBox, and similarly the <X> ComboBox fits in with respect to the <X> CheckBox and the string " after loading" to its right.
The part everyone seems to miss: This is all nested within a CheckBox. So, ideally, clicking on the words "after loading" should check/uncheck the checkbox, and draw that little highlight rectangle around "Adjust prices by          after loading." So just slapping an extra Label on the end doesn't work, because then it doesn't toggle the CheckBox; similarly, trying to band-aid things by hooking up such a Label's Click event won't produce the desired highlight-rectangle.
Solutions? At this point I'm thinking either:

*

*Rethink the problem, somehow, maybe with an ugly solution like two separate lines of text: "Adjust found prices after loading" (CheckBox), "Adjustment amount:" (NumericUpDown and ComboBox). This is really bad because my options box is absolutely full of options of this type (i.e. the type in the example), so it would at least double in vertical size.

*Some sort of custom control? SplittableCheckBox?

*Some kind of magic with a TableLayout control? (Pretty sure this fails at "the part everyone seems to miss.)

*Give up and either go back to MS Sans Serif, or use Tahoma uniformly, or package Segoe UI with my application, thus disrespecting the system default fonts.

*(New, via edit) Switch to WPF, if someone can convince me that it supports this scenario exactly.

A: If you have several options that follow this layout, why not create a user control?  The user control will contain the CheckBox, a NumericUpDown, a ComboBox and a label for the "after loading".  You can override OnFontChanged to adjust the location of the controls based on the rendering of the text with the given font.  Add an EventHandler to the Label to check/uncheck the CheckBox.
As for having the focus rectangle surround all of the controls, you should be able to give the user control focus when one of its inner controls is clicked.


text:
Q: Global variables in React Native let check1 = 0;

const App: () => React$Node = () => {
  const video = useRef();
  const [check2, setCheck2] = useState(0);
  let check3 = 0;

  useEffect(
    () => {
      askPermission().then((record) => {
        if (record) {
          RNSoundLevel.start();
          RNSoundLevel.onNewFrame = (data) => {
            if(check1 < 10) check1++;
            if(check2 < 10) setCheck(check2++);
            if(check3 < 10) check3++;
          }
        }
      });

If check1, the value can be read and written normally.
check2 and check3 give the value (0) at the time of the first render.
It seems that it can be solved by using check1, but the code does not seem to be clean.
I want to use check2, is there a way to read it?


text:
Q: AngularJS dynamic directive content HTML:

Controllers value:

{{_tc.value}}

    <button ng-click="_tc.addInput()">Add Directive Value</button>

    <test-directive></test-directive>

JS:
var app = angular.module('plunker', []);

var testController = function( testService ) {

  this.value = 'Test Value!';

  this.content = '';

  this.addInput = function() {

    testService.add('<input placeholder="Enter value" ng-model="_tc.value" />');

  }

};

var testService = function( $sce ) {

  this.content = '';

  this.add = function( content ) {

    this.content = $sce.trustAsHtml( content );

  }

};

var testDirective = function( testService ) {

  return {

    template:'
If you enter value below it should be bound to the controllers value above because scope is shared but value is not binding

',
    link: function( $scope ) {

      $scope.data = testService;

    }

  }

};

testService.$inject = ['$sce'];
app.service( 'testService', testService );

testController.$inject = ['testService'];
app.controller('TestController', testController );

testDirective.$inject = ['testService'];
app.directive( 'testDirective', testDirective );

Plunkr:
http://plnkr.co/edit/rqnFjtYZ0s4wdOlBpEV1?p=preview
The problem:
When the directives content is added the data binding is not working in the directive.
I understand that the dynamically added content is only text and can not bind any values but i don't know how to compile it proper way for it to work as supposed to.
Any help will be really appreciated

A: I finally figured out how to do so. There are a lot of tutorials about $compile and a lot of answers about $compile, but all of them are really very specific case based allowing no flexibility or a lot of hassle to handle different situations.
The easy and very flexible approach is to use a directive inside a directive for dynamic content which has to be compiled like shown in this plunkr:
http://plnkr.co/edit/5QTVKoAyDMJORNeopVib?p=preview
This way you can then just compile whole directive without need to select elements and some other crazy unflexible staff like this:
var contentDirective = function( testService,$compile,$timeout ) {

  return {

    scope: {

      data:'='

    },
    link: function( $scope,$element ) {

      $element.html( $scope.data );

      $compile( $element.contents() )( $scope.$parent );

    }

  }

};

In the plunkr there is a $timeout in the content directive just for presentation purposes, generally it won't be needed when the data will be loaded with some action and not immediately on load like in the example.


text:
Q: Remove default rectangular border of edittext when opened in dialog How can i remove the default rectangular border of EditText when opened in dialog?
I tried by setting background to null but it didn't worked.That  rectangular border only appears with EditText when I use it in dialog.
Here is the XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background_whitedialog"
    android:focusable="true"
    android:focusableInTouchMode="true">
...
    <android.support.design.widget.TextInputLayout
        android:id="@+id/inputPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:background="@null" >
        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="@dimen/dp48"
             android:maxLines="1"
            android:paddingLeft="@dimen/dp12"
            android:textColor="@color/numbertextcolor"
            android:textSize="@dimen/sp16" />
    </android.support.design.widget.TextInputLayout>

</RelativeLayout>

Here is the Java code:
Dialog dialog = new Dialog(mContext, R.style.DialogSlideAnim);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_item);
dialog.show();

A: To remove border in EditText please provide background drawable in EditText. Plus TextInputEditText with TextInputLayout as mentioned in https://developer.android.com/reference/android/support/design/widget/TextInputLayout.html

A:
I have use your code to generate a dialog. This is what i got.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true">
    <android.support.design.widget.TextInputLayout
        android:id="@+id/inputPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:background="@color/white"
        >
        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:hint="@string/new_password"
            android:background="@android:color/transparent"
            android:paddingLeft="12dp"
            android:textColor="@color/red"
            android:textSize="12sp" />
    </android.support.design.widget.TextInputLayout>

</RelativeLayout>

A: Try setting the background of Edit Text to transparent
 <EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Hello"
    android:background="#00000000" />


text:
Q: What should I do to use function interface on Class property method As you can see, in the Request Class, there are get(), put(), delete(), post() methods, and each of them has quite a few parameters. So I just want to use one interface.
interface fetchParam {
  (
    url: string,
    params?: string | object | [],
    alwaysBack?: boolean,
    options?: object,
    resolveResult?: boolean,
  ): {}
}

class Request {
  constructor() {}

  fetchApi(url, method, params, alwaysBack, options, resolveResult) {
     return new Promise((res, rej) => {
       // do somthing
     })
  }

  get(url, params, alwaysBack, options, resolveResult) {
    return this.fetchApi(url, 'get', params, alwaysBack, options, resolveResult)
  }

  post(url, params, alwaysBack, options, resolveResult) {
    return this.fetchApi(url, 'post', params, alwaysBack, options, resolveResult)
  }

  put(url, params, alwaysBack, options, resolveResult) {
    return this.fetchApi(url, 'put', params, alwaysBack, options, resolveResult)
  }

  delete(url, params, alwaysBack, options, resolveResult) {
    return this.fetchApi(url, 'delete', params, alwaysBack, options, resolveResult)
  }

}

I do not want to like this, too cumbersome
get(url: string, params?: string | object | [], alwaysBack?: boolean) {
    // do somthing
}

so, what should I do?

A: my idea is to wrap it into an object
get({ url, params, alwaysBack }: fetchParam) {
// do something
}


text:
Q: DropDrop selection event refresh all the UpdatePanel in Ajax I am using AJAX extension in visual studio 2005.
First of all i am created a Web custom control which contains Dropdown list.
I have also set AutoPostBack="true" for getting its SelectionEventChange event.
I am added this web control on another page inside a UpdatePanel.(i added dynamically on another page).
MyControl = (MyControl) LoadControl("MyControl.ascx")

My problem is when i select the values from dropdown it refersh my whole update panel.
What can i do please help me.
I searched in google and somebody says Use triggers
<Triggers>

<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />

But on AJAX Extension i am not getting it please Help me.

A: Triggers tag is part of update panel. Also look at some other important properties of UpdatePanel and search on how to use and referesh nested update panels.

A: Add this web custom control inside another(other then one you are already having, that is, have Multiple UpdatePanels) UpdatePanel, and call .Update() manually, in order to refresh only the web control.
Dont forget to set the UpdateMode to Conditional.


text:
Q: eBay Browse API: shopping cart add item doesn't work Working with Ebay's Browse API I'm having an issue with the /shopping_cart/add_item method, when I call it, it systematically returns an error 204.
I'm working on the API's sandbox. The calls are made from an iOS application in Canada. Until then, I had no issues requesting and retrieving data from responses.
Here's how I proceed:

*

*Using the sandbox, I retrieve mock items with /item_summary/search.

*The user goes through the OAuth process and grants his shopping cart access to my app. It returns a user access token that I use for the following request.

*Finally, I call add_item with the following parameters:
Request JSON parameters:
{"quantity": 1, "itemId": "v1|110385018358|0"}

Request headers:
Authorization: Bearer [sandbox user access token from step 2.]
Content-Type: application/json
X-EBAY-C-MARKETPLACE-ID: EBAY_US

Then I get an empty response (aka error 204), while it shouldn't as mentioned in the documentation.
The response I get only contains headers which are the following:
{
    Status Code: 204, Headers {
        Connection = ( "keep-alive" );
        "Content-Encoding" = ( gzip );
        "Content-Length" = ( 0 );
        "Content-Type" = ( "application/json" );
        Date = ( "Thu, 22 Nov 2018 15:14:32 GMT" );
        RlogId = ( "t6q%60ktkjvdbwrfsl%2Bbmsgcufboja%7Ct6n%3C%3Dsm%7Eufhuoluefqqgwj%284%3F34%3F11%2Busqdrrp%2Bufmadh%7B%2Bceb%7Ce4-fij-1673bfca0ca-0x133" );
        "Set-Cookie" = ( "dp1=bu1p/QEBfX0BAX19AQA**5dd7fb58^;Domain=.ebay.com;Expires=Sat, 21-Nov-2020 15:14:32 GMT;Path=/" );
        "X-EBAY-C-REQUEST-ID" = ( "ri=LVOZVdAO%2FSpS,rci=n76DxeaOd61P0WBf" );
        "X-EBAY-C-VERSION" = ( "1.0.0" );
        "X-EBAY-REQUEST-ID" = ( "1673bfca0a9.a0962ac.25e7e.fffdc702!/buy/browse/v1/shopping_cart!10.9.98.172!esbnewesbngcos[]!add_item!10.9.103.137!r1remshopcartapi-envadvcdhidzs5k[ItemClient[!Ginger.ViewItemServiceV1.litedetails!10.9.99.212!r1viappsvc-envadvcdhidzs5k[]]!ShopcartServiceClient[!Ginger.shopcase.v2.POST!10.9.101.40!r1scartsvc-envadvcdhidzs5k[]]]" );
        "X-EBAY-SVC-EP-COOKIELET" = ( "321=0001542899671242" );
        "X-EBAY-SVC-TRACKING-DATA" = ( "nqt=AA**&!_epec=7,6,8&nqc=AA**" );
    }
}

Moreover, logged in the ebay sandbox website with the test user I used above, if I open the cart, I get an error page stating:

We were unable to load your cart. Please try again. If the problem persists, contact Customer Support or send us feedback.

Still from the sandbox website, when I open any item, I get another error stating:

Unfortunately, access to this particular item has been blocked due to legal restrictions in some countries. [...]

I still hope the problem is on me and not on Ebay as their API is still a Beta.

A: Well ... It was nowhere in the API documentation, but hidden somewhere on the Sandbox website page "unsupported feature list for the sandbox":

Cart is not supported.  You may see some functionality working, like adding items to your cart, but please do not depend on or expect cart to function properly.

Although it states that AddItem may work, it actually does not, so I guess it is expected and that I should take this as the answer to my question.
Quite frustrating...
I guess I all I can do is to wait for Ebay's partnership approval.


text:
Q: Flask - passing an argument to window.location.replace() In a Flask framework, I have a menu.html, with a clickable link:
{{ lunch }}

and this is the corresponding url view:
@app.route('/loading/<name>')
def loading(name):
    return render_template('loading.html',
                            name=name)

loading.html has this script at he bottom:

pointing to a final view where a consuming task is being processed:
@app.route('/lunch/<name>')
    def (name):
        #(long, consuming task)
        return render_template('lunch.html',
                                name=name)

and if a click, for example, on a item link named 'meat', I get a 404, like so:
127.0.0.1 - - [01/Feb/2018 16:27:02] "GET /loading?name=meat HTTP/1.1" 404 -

and not GET /loading/meat 200, as expected.
so what is the simplest way of passing correctly the call to window.location.replace()in this framework?

A: Ok, I would use window.location.href = 'path/to/destination'
Since your waiting for and API responce it would go something like this (using promises anyway)
fetch(url).then((response) => {
 // do something to the response
}).then(() => {
  window.location.href = '/lunch/{{name}}'
})

This will take you to the function your looking use.
For those looking for just redirect you can use the redirect from the flask library. First import the redirect from the library:
from flask import Flask, render_template, request, redirect, [anything else]

Then I'd write the first function like this:
@app.route('/loading/<string:name>')
def loading(name):
    return redirect(url_for('name',
                            name=name))

This will send you to your function name with the name that was clicked originally. I also think it helps to specify the type when putting a variable in the @app.rout decorator like I did with <string:name> or if you had an id <int:id>


text:
Q: R summaries when dates in main df fall within ranges from small df Similar to do.call/lapply approach here, and data.table approach here, but both have the setup of:

*

*MainDF with data and startdate/enddate ranges

*SubDF with a vector of single dates

Where the users are looking for summaries of all the MainDF ranges that overlap each SubDF date. I have

*

*MainDF with data and a vector of single dates

*SubDF with startdate/enddate ranges

And am looking to append summaries, to SubDF, for multiple rows of MainDF data which fall within each SubDF range. Example:
library(lubridate)
MainDF <- data.frame(Dates = seq.Date(from = as.Date("2020-02-12"),
                                      by = "days",
                                      length.out = 10),
                     DataA = 1:10)
SubDF <- data.frame(DateFrom = as.Date(c("2020-02-13", "2020-02-16", "2020-02-19")),
                    DateTo = as.Date(c("2020-02-14", "2020-02-17", "2020-02-21")))
SubDF$interval <- interval(SubDF$DateFrom, SubDF$DateTo)

Trying the data.table approach from the second link I figure it should be something like:
MainDF[SubDF, on = .(Dates >= DateFrom, Dates <= DateTo), allow = TRUE][
, .(SummaryStat = max(DataA)), by = .(Dates)]

But it errors with unused arguments for on. On my actual data I got a result by using (the equivalent of) max(MainDF$DataA), but it was 3 repeats of the second value (In my actual data the final row won't run as it doesn't have a value for DateTo). I suspect using MainDF$ means I've subverting the grouping.
I suspect I'm close but I'm really struggling to get my head around the data.table mindset for complex use cases. The summary stats I'm looking to do are (for example data):

*

*Mean & Max of DataA

*length(which(DataA > 3))

*difftime(last(Dates), first(Dates), units = "mins")

*Dates[which.max(DataA)]
I added the interval line above as data.table's %between% help suggests one might be able to use a Dates %between% interval format but it doesn't mention intervals/difftimes specifically in the text nor examples and my attempts are already failing elsewhere so I'm loathe to concentrate on improving my running while I can't walk!
I've focused on the data.table approach since it's used for a similar problem, but I've been wondering whether dplyr's group_by/group_by_if could be used instead? group_by_if's .predicate seems to be constrained to tests on the columns (e.g. are they factors) rather than relating to data in the columns' rows, but I could be wrong.
Thanks in advance for any help!


text:
Q: Equivalent in scala to java static method with type parameters This is a cakewalk question: how to properly declare the T Type parameter in this object method Xforms.rotate?  Note it would not be my intention to provide type parameters to the object itself..
object Xforms {
  def rotate(data : Traversable[T]) = { }
}

For clarification I would be looking for a more or less equivalent of
public static <T> T rotate(T data) {
    T newData = null;
    // perform rotations on newData ..
    return newData;
}

A: The type parameters for a method come after the method name.
def rotate[T]( //...


text:
Q: How to enable persitence storage in jboss 6? I have configured jms message queue in jboss and changed the default database to mysql db.
Now i want to enable persistence storage.
This is the horneq-configuration.xml file in jboss/server/default/deploy/hornetq
<!--
  ~ Copyright 2009 Red Hat, Inc.
  ~  Red Hat licenses this file to you under the Apache License, version
  ~  2.0 (the "License"); you may not use this file except in compliance
  ~  with the License.  You may obtain a copy of the License at
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~  Unless required by applicable law or agreed to in writing, software
  ~  distributed under the License is distributed on an "AS IS" BASIS,
  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  ~  implied.  See the License for the specific language governing
  ~  permissions and limitations under the License.
  -->

<configuration xmlns="urn:hornetq"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">

   <log-delegate-factory-class-name>org.hornetq.integration.logging.Log4jLogDelegateFactory</log-delegate-factory-class-name>

   <bindings-directory>${jboss.server.data.dir}/hornetq/bindings</bindings-directory>

   <journal-directory>${jboss.server.data.dir}/hornetq/journal</journal-directory>

   <!-- Default journal file size is set to 1Mb for faster first boot -->
   <journal-file-size>${hornetq.journal.file.size:1048576}</journal-file-size>

   <!-- Default journal min file is 2, increase for higher average msg rates -->
   <journal-min-files>${hornetq.journal.min.files:2}</journal-min-files>

   <large-messages-directory>${jboss.server.data.dir}/hornetq/largemessages</large-messages-directory>

   <paging-directory>${jboss.server.data.dir}/hornetq/paging</paging-directory>

   <connectors>
      <connector name="netty">
         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
         <param key="host"  value="${jboss.bind.address:localhost}"/>
         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
      </connector>

      <connector name="netty-throughput">
         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
         <param key="host"  value="${jboss.bind.address:localhost}"/>
         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
         <param key="batch-delay" value="50"/>
      </connector>

      <connector name="in-vm">
         <factory-class>org.hornetq.core.remoting.impl.invm.InVMConnectorFactory</factory-class>
         <param key="server-id" value="${hornetq.server-id:0}"/>
      </connector>

   </connectors>

   <acceptors>
      <acceptor name="netty">
         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
         <param key="host"  value="${jboss.bind.address:localhost}"/>
         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
      </acceptor>

      <acceptor name="netty-throughput">
         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
         <param key="host"  value="${jboss.bind.address:localhost}"/>
         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
         <param key="batch-delay" value="50"/>
         <param key="direct-deliver" value="false"/>
      </acceptor>

      <acceptor name="in-vm">
        <factory-class>org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory</factory-class>
        <param key="server-id" value="0"/>
      </acceptor>

   </acceptors>

   <security-settings>
      <security-setting match="#">
         <permission type="createNonDurableQueue" roles="guest"/>
         <permission type="deleteNonDurableQueue" roles="guest"/>
         <permission type="consume" roles="guest"/>
         <permission type="send" roles="guest"/>
      </security-setting>
   </security-settings>

   <address-settings>
      <!--default for catch all-->
      <address-setting match="#">
         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
         <redelivery-delay>0</redelivery-delay>
         <max-size-bytes>10485760</max-size-bytes>
         <message-counter-history-day-limit>10</message-counter-history-day-limit>
         <address-full-policy>BLOCK</address-full-policy>
      </address-setting>
   </address-settings>

</configuration>

Here what i need to change here? Can anyone tell me?
How to enable persistence in jboss 6?

A: Well, the messages are actually stored in a persistent manner. From the offical documentation:

Each HornetQ server has its own ultra high performance persistent journal, which it uses for message and other persistence.

HornetQ has its own way of storing the messages directly on the file system.
If you want to store the messages in the MySQL database, this is not supported by HornetQ, and will probably not be in the future.
This has been debated a few times, for example here. The HornetQ team obviously don't think there is a need to add such support.


text:
Q: ImportError: No module named TestModel when use manage.py to runserver I user Django create a project named testdj, and also in it I created a APP named TestModel, see my tree:
aircraftdeMacBook-Pro:TestPython ldl$ tree testdj/
testdj/
├── db.sqlite3
├── manage.py
├── templates
│   ├── base.html
│   ├── ext-1.html
│   ├── hello.html
│   └── index.html
└── testdj
    ├── TestModel
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── migrations
    │   │   └── __init__.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── __init__.py
    ├── __init__.pyc
    ├── helloworld.py
    ├── settings.py
    ├── settings.pyc
    ├── urls.py
    ├── urls.pyc
    ├── view.py
    ├── view.pyc
    ├── wsgi.py
    └── wsgi.pyc

But when I cd to the testdj/ directory, I want to run the wsgi server:
$ python manage.py runserver

I get the below error:
Unhandled exception in thread started by <function wrapper at 0x10b80ede8>
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/management/commands/runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 250, in raise_last_exception
    six.reraise(*_exception)
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named TestModel

It says ImportError: No module named TestModel in it.

In the testdj/testdj/settins.py, I have added the TestModel as APP:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'TestModel',
]

A: Bro bro bro, why arent you following any tutorial? you messed up
the app folder and the main testdj folder will be there where you have manage.py,
at this point you have inserted the testmodel inside the testdj folder where settings.py is ,
so take it out and place at the place of manage.py, the whole folder,
then run
python manage.py runserver

A: This (https://stackoverflow.com/a/44673465/6563567) will work but it is not wrong to move your app to settings.py level.
You just have to tell django where to find the apps.
Since your apps are not in manage.py level, your installed apps should look like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testdj.TestModel',
]

Further you can add 'testdj', in installed apps if you want to add views.py file in setting level.
Remember that your app is a python package and each file inside the app is a python module and that's how django uses them.


text:
Q: Magento category count I would like to have Magento display the total count of the products including the products in subcategories. Eg. if the Main category has two products and a subcategory has five products.
I.e.:

*

*MAIN CATEGORY (12)

*SUB CATEGORY A (5)

*SUB CATEGORY B (5)

How can I do this?

A: Try with this code.

          <?php
           // This is category id
           $id = 42;

           $cat = Mage::getModel('catalog/category')->load($id);
           $subcats = $cat->getChildren();
           foreach(explode(',',$subcats) as $subCatid):
           $_category = Mage::getModel('catalog/category')->load($subCatid);
           if($_category->getIsActive()):
                $productCount = Mage::getModel('catalog/category')->load($_category->getId())->getProductCount();?>

<a href="<?php echo $_category->getURL();?>"><?php echo $_category->getName();?>
<?php echo '('.$productCount.')'?>

        <?php endif;
         endforeach;?>

A: Or else you can use this function.
public function getProductCount($category)
{
$prodCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($category);
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($prodCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($prodCollection);
return $prodCollection->count();
}


text:
Q: If $A^3=I$ for a real matrix, is $A$ normal/orthogonal? I read earlier that if $A$ is a real $3\times 3$ matrix satsifying $A^3=I$, then $A$ is similar to a matrix of form
$$
\begin{bmatrix}
1 & 0 & 0\\
0 & \cos\theta & -\sin\theta\\
0 & \sin\theta & \cos\theta
\end{bmatrix}
$$
From the structure theorems for normal operators, I know that among the real normal operators, the othogonal operators are exactly those matrices which are block diagonal with their eigenvalues and $2\times 2$ blocks of the above form.
So I suppose $A$ must be normal/orthogonal? Is there a way to deduce that at all from just knowing that $A^3=I$ without appealing to the structure theorem in hindsight?

A: This is not true.  That $A^3=I$ implies that $A$ is diagonalizable over $\mathbf{C}$ and that its eigenvalues are cube roots of unity and thus on the unit circle.
And while being diagonalizable with eigenvalues on the unit circle is necessary for being unitary (over $\mathbf{R}$, orthogonal), it is not sufficient: the corresponding eigenvectors must be orthogonal for different eigenvalues.
A counterexample can be found simply by conjugating an orthogonal matrix with a matrix that is not orthogonal.

A: Let $A=\begin{bmatrix} 1 & -\frac{3}{2} & \frac{\sqrt{3}}{2} \\ 0 & -\frac{1}{2} & -\frac{\sqrt{3}}{2} \\ 0 & \frac{\sqrt{3}}{2} & -\frac{1}{2} \end{bmatrix}$. Then $A^3=I$, but $A$ is not orthogonally
similar to the matrix above since the matrix above is normal whereas $A$ is not.
Elaboration:
To construct $A$ we note that we must have $\lambda^3 = 1$ for all eigenvalues $\lambda$, so we have two choices of eigenvalues (since if $\lambda$ is an eigenvalue, so must $\overline{\lambda}$): $\{1\}$ (multiplicity 3), or $\{1, e^{i 2 \pi/3}, e^{-i 2 \pi/3} \}$.
If the eigenvalues are all $1$, then we must have $A=I$, which is uninteresting.
To see this, since all eigenvalues are 1, Cayley Hamilton gives $(A-I)^3 = 0$, which gives $A^2 = A$ (since $A^3 = I$), multiplying across by $A$ gives $A^3 = A^2 $ from which it follows that $A=I$.
So we have eigenvalues $1$, $\lambda = e^{i 2 \pi/3}$, and $\overline{\lambda}$. (Note that if $A v = \lambda v$, then $A \overline{v} = \overline{\lambda} \overline{ v}$.) To finish I want to pick three linearly independent, non-orthogonal eigenvectors. I choose $e_1$ for the eigenvalue $1$, and $(1,1,i)^T$ for the eigenvalue $\lambda$ (hence the eigenvector for the eigenvalue $\overline{\lambda}$ must be $(1,1,-i)^T$). Multiplying these out appropriately gives the above matrix.

A: The matrix that governs the heptagonal isomorphs satisfies $A^3=I$.
 1   1  1        1   0  1            1  0  0
 0  0   1   ->   0  -1 -1   ->       0  1  0
 0 -1  -1        0   1  0            0  0  1

When this matrix is applied to numbers (i,a,b), where these are the chords of a unit-edge heptagon (1, 1.801937736, 2.2469796037), then the outcome comes to the chords of a unit edge heptagrams (7/3, 7/2), and back again.
But it is a matrix that satisfies this relation, and not in the form of cos(x), sin(x).


text:
Q: Max sum of non prime numbers on triangle of numbers I have a triangle of numbers. I want to find the largest sum of the NOT PRIME numbers starting from the top in this triangle. For example:

*

*You will start from the top and move downwards to an adjacent number as in below.

*You are only allowed to walk downwards and diagonally.

*You can only walk over NON PRIME NUMBERS.

*You have to reach at the end of the pyramid as much as possible.

*You have to treat the input as pyramid.

According to above rules the maximum sum of the numbers from top to bottom in below example is 24.
      *1
     *8 4
    2 *6 9
   8 5 *9 3

As you can see this has several paths that fits the rule of NOT PRIME NUMBERS; 1>8>6>9, 1>4>6>9, 1>4>9>9
1 + 8 + 6 + 9 = 24.  As you see 1, 8, 6, 9 are all NOT PRIME NUMBERS and walking over these yields the maximum sum.
My code is below. My code doesn't consider prime numbers. How can I do it like in the example above?
public class MaxPathSum {

    public static void main(String[] args) throws Exception {
        int[][] data = Files.lines(Paths.get("src/main/triangle.txt"))
                .map(s -> stream(s.trim().split("\\s+"))
                        .mapToInt(Integer::parseInt)
                        .toArray())
                .toArray(int[][]::new);

        for (int r = data.length - 1; r > 0; r--)
            for (int c = 0; c < data[r].length - 1; c++)
                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);

        System.out.println(data[0][0]);
    }
}

Example data:
        1
       8 4
      2 6 9
     8 5 9 3

A: Somewhere at a value, row r, column c. You possibly could come from left parent [r-1][c-1] (c > 0) or right parent [r-1][c] (c < r).
You stop with failure when the value is a prime.
Going down in both cases you want the maximum, and with a solution of the subtree.
When failure fail.
So going first down the subtree:
record Solution(int sum, List<Integer> path) {}

Optional<Solution> solve(int r, int c) {
    int value = data[r][c];
    if (isPrime(value)) {
        return Optional.empty();
    }
    if (r+1 >= data.length) {
        List<Integer> path = new ArrayList<>();
        path.add(value);
        return Optional.of(new Solution(value, path));
    }
    Solution left = solve(r+1, c);
    Solution right = solve(r+1, c+1);
    if (!left.isPresent()) {
        if (!right.isPresent()) {
            return Optional.empty();
        } else {
            List<Integer> path = left.path;
            path.add(0, value);
            return Optional.of(new Solution(value + left.sum, path));
        }
    } else {
        if (!right.isPresent()) {
            List<Integer> path = right.path;
            path.add(0, value);
            return Optional.of(new Solution(value + right.sum, path));
        } else {
            if (left.sum > right.sum) {
                List<Integer> path = left.path;
                path.add(0, value);
                return Optional.of(new Solution(value + left.sum, path));
            } else {
                List<Integer> path = right.path;
                path.add(0, value);
                return Optional.of(new Solution(value + right.sum, path));
            }
        }
    }
}

Of course you could also work with an int[][] sum at the bottom row filling primes with a -1, and a sum of the two values under when not -1.


text:
Q: Erro PHP - Não cadastra no banco de dados O PHP retorna 4 erros ao eu tentar cadastrar um usuário no banco de dados, os erros são

Warning: move_uploaded_file(fotos/2f66a74ededbbd39c3651c02e62998af.jpg): failed >to open stream: No such file or directory in C:\Program Files (x86)\EasyPHP->Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 63
Warning: move_uploaded_file(): Unable to move 'C:\Users\User\AppData\Local\Temp\phpD504.tmp' to 'fotos/2f66a74ededbbd39c3651c02e62998af.jpg' in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 63
Notice: Array to string conversion in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 66
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in C:\Program Files (x86)\EasyPHP-Devserver-17\eds-www\Sistema_Aluno\inseriraluno.php on line 67

PHP:

// Recupera os dados dos campos
$nome = $_POST['nome'];
$email = $_POST['email'];
$foto = $_FILES['foto'];
$senha = $_POST['senha'];
$turmaid = $_POST['idturma'];
$rm = $_POST['rm'];
// Se a foto estiver sido selecionada
if (!empty($foto["name"])) {

    // Largura máxima em pixels
    $largura = 1000;
    // Altura máxima em pixels
    $altura = 1000;
    // Tamanho máximo do arquivo em bytes
    $tamanho = 100000;

    $error = array();

    // Verifica se o arquivo é uma imagem
    if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){
       $error[1] = "Isso não é uma imagem.";
    }

    // Pega as dimensões da imagem
    $dimensoes = getimagesize($foto["tmp_name"]);

    // Verifica se a largura da imagem é maior que a largura permitida
    if($dimensoes[0] > $largura) {
        $error[2] = "A largura da imagem não deve ultrapassar ".$largura." pixels";
    }

    // Verifica se a altura da imagem é maior que a altura permitida
    if($dimensoes[1] > $altura) {
        $error[3] = "Altura da imagem não deve ultrapassar ".$altura." pixels";
    }

    // Verifica se o tamanho da imagem é maior que o tamanho permitido
    if($foto["size"] > $tamanho) {
        $error[4] = "A imagem deve ter no máximo ".$tamanho." bytes";
    }

    // Se não houver nenhum erro
    if (count($error) == 0) {

        // Pega extensão da imagem
        preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto["name"], $ext);

        // Gera um nome único para a imagem
        $nome_imagem = md5(uniqid(time())) . "." . $ext[1];

        // Caminho de onde ficará a imagem
        $caminho_imagem = "fotos/" . $nome_imagem;

        // Faz o upload da imagem para seu respectivo caminho
        move_uploaded_file($foto["tmp_name"], $caminho_imagem);

        // Insere os dados no banco
        $insert = "INSERT INTO aluno (RM, Turma_ID, Foto, Nome, Email, Senha ) VALUES ('$rm','$turmaid','$foto','$nome','$email','$senha'";
        $sql = mysqli_query($conn,$insert);
        // Se os dados forem inseridos com sucesso
        if ($sql){
            echo "Você foi cadastrado com sucesso.";
        }
    }

    // Se houver mensagens de erro, exibe-as
    if (count($error) != 0) {
        foreach ($error as $erro) {
            echo $erro . "
";
        }
    }
}

HTML:

<fieldset>
  <input placeholder="RM" type="number" tabindex="1" name="rm" required autofocus>
</fieldset>
<fieldset>
  <input placeholder="Email" type="email" tabindex="2" name="email" required>
</fieldset>

<fieldset>
  <input placeholder="Nome" name="nome" type="text" tabindex="4" required>
</fieldset>
<fieldset>
  <input type="password" name="senha" placeholder="Senha" tabindex="5" required>
</fieldset>
 <fieldset>
  <input type="number" name="idturma" placeholder="ID Turma" tabindex="6" required>
</fieldset>

 <fieldset>
<input type="file" name="foto" placeholder="Foto"/ tabindex="7">

</fieldset>

<fieldset>
  <button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Enviar</button>
</fieldset>

A: Olha na parte
"... VALUES ('$rm','$turmaid','$foto','$nome','$email','$senha'";
Faltou fechar o parenteses:
"... VALUES ('$rm','$turmaid','$foto','$nome','$email','$senha')";


text:
Q: Lovasz theta and circulant graphs Let $\theta(G)$ denote Shannon zero error capacity of graph $G$ and $\vartheta(G)$ be Lovasz upper bound for $\theta(G)$.
Let $C_{2n+1}$ denote cycle graph with $2n+1$ nodes.
We know following two things:

*

*$$\theta(C_{2n+1})\leq \vartheta(C_{2n+1})=\frac{n\cdot \cos(\frac\pi n)}{1+\cos(\frac\pi n)}$$

*$$\theta(C_5)=\vartheta(C_5)=\sqrt{5}$$
Let $\mathcal{Circ_n}$ be a collection of all circulant graphs on $n$ vertices. Naturally $C_n\in\mathcal{Circ_n}$.
Other than for $C_n$ is there any other class of $G\in\mathcal{Circ_n}$ for which exact expression of $\vartheta(G)$ is known?

A: $\vartheta(G_p)=\sqrt{p}$ if $G_p$ is the Paley graph of order $p$


text:
Q: Casperjs/Phantomjs does not respect hosts file I am trying to run tests against my vagrant box with lives at 192.168.0.100. In my hosts file I have 192.168.0.100 lc.mysite.com and the site loads fine and works normally at that url with chrome.
However, when I try and run my tests against it, the url fails and never loads anything. Remote urls work fine but the local ones are just failing.
How can I get casperjs to respect my hosts file? Or is it something else?

A: Turns out it was due to the url being ssl and it kept failing. Using this answer solved my issue.
CasperJS/PhantomJS failing SSL handshakes on some sites even with --ssl-protocol=any

A: If you are using a self-signed SSL certificate (e.g. on your development box), set phantomjs option
--ignore-ssl-errors=true
From the documentation:
--ignore-ssl-errors     Ignores SSL errors (expired/self-signed certificate errors): 'true' or 'false' (default)


text:
Q: Pandas Dataframe - find the row with minimum value based on two columns but greater than 0 I have a dataframe with 3 columns: x, y, time. There are a few thousand rows.
What I want to do is retrieve the row with the minimum time but I would like that the minimum should not be 0.
e.g.
x     y    time
240   1    28.5
240   2    19.3
240   240     0
240   19    9.7

So far what I've tried were the following:
df.loc[df['time'] > 0].min()
# this gives me a series and I want a row
# x    225.000000
# y      0.000000
# time   1.066606

df['time'].drop_duplicates().nsmallest(1)
# 225    0.0

I have also tried something with groupby as well
df.loc[df.groupby('id_x', sort=False)['time'].idxmin()]

I know had problems subsetting this one as I usually got a series.

A: Try this:
In [69]: df.loc[df.time>0, 'time'].idxmin()
Out[69]: 3

or
In [72]: df.loc[[df.loc[df.time>0, 'time'].idxmin()]]
Out[72]:
     x   y  time
3  240  19   9.7

A: You can filter out 0 values by query and get index of minimal value by idxmin, last select by loc:
s = df.loc[df.query('time != 0')['time'].idxmin()]
print (s)
x       240.0
y        19.0
time      9.7
Name: 3, dtype: float64

df = df.loc[[df.query('time != 0')['time'].idxmin()]]
print (df)
     x   y  time
3  240  19   9.7

A: You don't need groupby at all. Here's an option with mask/where + loc + idxmin;
df.loc[[df.time.mask(df.time.eq(0)).idxmin()]]

Or,
df.loc[[df.time.where(df.time.ne(0)).idxmin()]]

     x   y  time
3  240  19   9.7


text:
Q: Reproduce CPU diagram I am trying to reproduce a simplified Intel processor diagram, without any good luck.
What I cannot understand is how to make the L3 part common, and my code is producing the following:

What I'd like to achieve is the size of L3 equal to the width of the diagram excluding RAM: if I add two more cores, it should stretch accordingly.
This is my minimal compilable code, what am I missing here?
Thanks!
\documentclass{article}

\usepackage{tikz}
\usepackage{subfigure}
\usetikzlibrary{calc,trees,positioning,arrows,chains,shapes.geometric,%
    decorations.pathreplacing,decorations.pathmorphing,shapes,%
    matrix,shapes.symbols}

\tikzset
{
    % nodes
    darkstyle/.style =
    {
        circle,draw,fill = gray!20
    },
    % trajectory
    serpent/.style =
    {
        line join  = round,
        line width = 2pt,
        line cap   = round,
        opacity    = .7,
        red
    },
    >=stealth',
    core/.style =
    {
        rectangle,
        rounded corners,
        draw           = black, thick,
        text width     = 5em,
        minimum height = 3em,
        text centered,
        on chain
    },
    cache/.style =
    {
        rectangle,
        rounded corners,
        draw           = gray!40, thin,
        text width     = 5em,
        minimum height = 3em,
        text centered,
        on chain
    },
    line/.style =
    {
        draw, thick, <-
    },
    element/.style =
    {
        tape,
        top color      = white,
        bottom color   = blue!50!black!60!,
        minimum width  = 8em,
        draw           = blue!40!black!90, very thick,
        text width     = 10em,
        minimum height = 3.5em,
        text centered,
        on chain
    },
    every join/.style =
    {
        ->, thick,shorten >=1pt
    },
    decoration =
    {
        brace
    },
    tuborg/.style =
    {
        decorate
    },
    tubnode/.style =
    {
        midway, right = 2pt
    },
}

\begin{document}

\begin{figure}
    \centering
    \begin{tikzpicture}[node distance = .8cm, start chain = going below]
        % cores
        \node [core]  (c1) {Core 1};
        \node [core]  (c2) [right = of c1] {Core 2};
        % caches
        \node [cache] (l11) [below = of c1]  {L1 \\  64 KB} edge [-] (c1);
        \node [cache] (l12) [below = of c2]  {L1 \\  64 KB} edge [-] (c2);
        \node [cache] (l21) [below = of l11] {L2 \\ 256 KB} edge [-] (l11);
        \node [cache] (l22) [below = of l12] {L2 \\ 256 KB} edge [-] (l12);
        % common cache
        \node [core,text width = 10em,xshift=-20.5pt]  (l3)  {L3 \\   8 MB} edge [-] (l21) edge [-] (l22);
        % ram
        \node [core]  (ram)  [right = of l3] {RAM} edge [-] (l3);
    \end{tikzpicture}
    \label{fig:cache}
    \caption{Cache hierarchy diagram for the 2016 Intel Kaby Lake Microarchitechture.}
\end{figure}

\end{document}

A:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{arrows, calc, chains, positioning}

\tikzset
{
 core/.style = {
        rectangle,
        rounded corners,
        draw           = black, thick,
        text width     = 5em,
        minimum height = 3em,
        align=center,
        on chain
                },
cache/.style = {
        core,
        draw           = gray
                }
}% end of tikzset

\begin{document}
    \begin{tikzpicture}[
node distance = 8mm,
start chain = going below]
% left branch
\node [core]                (c1)  {Core 1};
\node [cache,join]          (l11) {L1 \\  64 KB};
\node [cache,join]          (l12) {L2 \\ 256 KB};
% right branch
\node [core,right=of c1]    (c2)  {Core 1};
\node [cache,join]          (l21) {L1 \\  64 KB};
\node [cache,join]          (l22) {L2 \\ 256 KB};
% common cache
\path   let \p1 = ($(c2.east)-(c1.west)$),
            \n1 = {veclen(\x1,\y1)} in
        node [core,minimum width = \n1,
              below=of $(l12.south)!0.5!(l22.south)$]  (l3)  {L3 \\   8 MB};
        \draw   (l12) -- (l12 |- l3.north)   (l22) -- (l22 |- l3.north);
% ram
\node [core,join]  (ram)  [right = of l3] {RAM};
    \end{tikzpicture}
\end{document}

Off-topic:
package subfigure is obsolete, it is replaced with subfig, but even better control over sub figures you can achieved by subcaption. In above example is not used figure environment, but placing image code in in it (and use article document class) shouldn't be big problem :-)
For width of L3 block is used calc library with macro veclen. Also is exploited chain library in positioning of vertical branches.


text:
Q: Switching between power source I'm making this speaker where I have 2 12v batteries in series giving 24v an amp.
and a PSU giving 24v to the same amp.
I wanna make a circuit that switches off the batterie link between each other and the Amp when the PSU Is live.
so only the PSU is giving power to the Amp
:D


text:
Q: Getting SyntaxError for working code that uses os.popen() I am writing a Python script to test my CS50 assignment by extracting, executing, and comparing against commands extracted from a string. The commands themselves work and produce results; however, that doesn't seem to be the case when called using os.popen() or other Python bash callers, and it ends up producing a SyntaxError.
The Code:
import os
import re

with open("makefile", "r") as file:
    data = file.read()
    data = re.split("\n", data, re.M)
    for argument in data:
        i = 0
        pattern = re.compile(r'(?:as\s)(python\sdna.py\sdatabases/[a-zA-Z]+\.csv\ssequences/[0-9]+\.txt)')
        command = pattern.finditer(argument)
        namept = re.compile(r'(No\s)?[a-zA-Z]+\.$')
        name = namept.search(argument)
        name = name.group(0).replace(".", "")
        for arg in command:
            command = arg.group(1)
        stream = os.popen(command)
        output = stream.read()
        if output != name:
            print("error at", i)
        i += 1

The Make File:
Run your program as python dna.py databases/small.csv sequences/1.txt. Your program should output Bob.
Run your program as python dna.py databases/small.csv sequences/2.txt. Your program should output No match.
Run your program as python dna.py databases/small.csv sequences/3.txt. Your program should output No match.
Run your program as python dna.py databases/small.csv sequences/4.txt. Your program should output Alice.
Run your program as python dna.py databases/large.csv sequences/5.txt. Your program should output Lavender.
Run your program as python dna.py databases/large.csv sequences/6.txt. Your program should output Luna.
Run your program as python dna.py databases/large.csv sequences/7.txt. Your program should output Ron.
Run your program as python dna.py databases/large.csv sequences/8.txt. Your program should output Ginny.
Run your program as python dna.py databases/large.csv sequences/9.txt. Your program should output Draco.
Run your program as python dna.py databases/large.csv sequences/10.txt. Your program should output Albus.
Run your program as python dna.py databases/large.csv sequences/11.txt. Your program should output Hermione.
Run your program as python dna.py databases/large.csv sequences/12.txt. Your program should output Lily.
Run your program as python dna.py databases/large.csv sequences/13.txt. Your program should output No match.
Run your program as python dna.py databases/large.csv sequences/14.txt. Your program should output Severus.
Run your program as python dna.py databases/large.csv sequences/15.txt. Your program should output Sirius.
Run your program as python dna.py databases/large.csv sequences/16.txt. Your program should output No match.
Run your program as python dna.py databases/large.csv sequences/17.txt. Your program should output Harry.
Run your program as python dna.py databases/large.csv sequences/18.txt. Your program should output No match.
Run your program as python dna.py databases/large.csv sequences/19.txt. Your program should output Fred.
Run your program as python dna.py databases/large.csv sequences/20.txt. Your program should output No match.

The error:
SyntaxError: invalid syntax
error at 0
  File "dna.py", line 34
    regex = re.findall(f'(?:{cats})+', sequence)
                                    ^

dna.py
from sys import argv, exit
import csv
import re

if len(argv) != 3:
    print("missing argument. usage: python dna.py [DATABASE] [SEQUENCE]")
    exit(1)

database = argv[1]
sequence = argv[2]

with open(database, "r") as file:
    literal = list()
    data = [dict()]
    csv_reader = csv.reader(file, delimiter=",")
    for row in csv_reader:
        literal = row.copy()
        break
    file.seek(0)
    csv_reader = csv.DictReader(file)
    for row in csv_reader:
        data.append(row)
    data.pop(0)

iteration = dict()
for item in literal:
    iteration.update({item: 0})

with open(sequence, "r") as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        sequence = "".join(row)
    for cats in literal:
        regex = re.findall(f'(?:{cats})+', sequence)
        res = 0 if not regex else round(len(max(regex)) / len(cats))
        iteration[cats] = res

for i in range(len(data)):
    error = 0
    for cats in literal:
        if cats != 'name':
            if int(data[i][cats]) != iteration[cats]:
                error += 1
    if error is 0:
        iteration['name'] = data[i]['name']
        break
    else:
        iteration['name'] = "No Match"

print(iteration['name'])

Note that the commands extracted with REGEX work when I copy it myself to the terminal.

A: So the problem with the code ended up being the lack of support for formatted strings in Python 2.x.x despite the fact that this code is called from within Python 3.7.9. To get around this, I had to separate my regex calls into groups so that I can change pythonto python3. The new code looks something like this:
pattern = re.compile(r'(?:as\s)(python)(\sdna.py\sdatabases/[a-zA-Z]+\.csv\ssequences/[0-9]+\.txt)')

for arg in command:
            command = arg.group(1) + "3" + arg.group(2)


text:
Q: Using boost::shared_ptr with WSACleanup I would like to use a boost::shared_ptr in order for WSACleanup() to be called when my function goes out of scope, like this:
void DoSomething() {
    WSAStartup(...);
    boost::shared_ptr<void> WSACleaner(static_cast<void*>(0), WSACleanup);
}

This does not compile,
Error  1   error C2197: 'int (__stdcall *)(void)' : too many arguments for call    C:\projects\svn-5.3\ESA\Common\include\boost\detail\shared_count.hpp    116

any thoughts?

A: From the docs: "The expression d(p) must be well-formed" (i.e. WSACleanup(static_cast<void*>(0) must be well-formed.)
One possible solution:
boost::shared_ptr<void> WSACleaner(static_cast<void*>(0),
                                   [](void* dummy){WSACleanup();});

A: You can create a class Awhich destructor invoques WSACleanup and instance of shared_ptr with it:
class A
{
    public:
        ~A() { WSACleanup(...); }
}

....

void DoSomething() {
    WSAStartup(...);
    boost::shared_ptr<A> x(new A);
}


text:
Q: How to Initialize 8 hours in DataTime formate I want to initialize 8 hours in DateTime format.I tried like this
DateTime stayingTime = 8;
TimeSpan span = (stayingTime-runningTime);

I will get runningTime from some other source. I want to subtract that runningTime with 8 hours and display the answer in following format hh:mm

A: You are looking for the TimeSpan-structure:
TimeSpan stayingTime = TimeSpan.FromHours(8);
TimeSpan span = stayingTime - runningTime;

If you need it as DateTime you could use the TimeOfDay property:
DateTime stayingTime = new DateTime().AddHours(8);
TimeSpan span = stayingTime.TimeOfday - runningTime;

If you want to output it with hh:mm-format use TimeSpan.ToString:
span.ToString("hh':'mm")


text:
Q: The this keyword in the code reference to in the jquery plugin below? I found this code on the web and was wondering what each "this" keyword reference to? This code has 7 reference to "this" keyword and wondering what each one of them reference to.. I'm assuming it reference to some DOM element but can't make the connection in mind how this is done...
(function($) {

   $.watermark = function(element, options) {
      // what does this keyword reference to
      this.options = {};

      // what does this keyword reference to
      element.data('watermark', this);

      // what does this keyword reference to
      this.init = function(element, options) {

      // what does this keyword reference to
         this.options = $.extend({}, $.watermark.defaultOptions, options);

         //Manipulate element here ...
      };

      //Public function
      // what does this keyword reference to

      this.greet = function(name) {
         console.log('Hello, ' + name + ', welcome to Script Junkies!');
      };

      // what does this keyword reference to
      this.init(element, options);
   };

   $.fn.watermark = function(options) { //Using only one method off of $.fn
      return this.each(function() {
         (new $.watermark($(this), options));
      });
   };

   $.watermark.defaultOptions = {
      class: 'watermark',
      text: 'Enter Text Here'
   }
})(jQuery);

A: I have labeled them inline, below:
(function($) {

   $.watermark = function(element, options) {
      // referencing the caller of plugin (which is acting like an object)
      this.options = {}; //  this.options is a property

      element.data('watermark', this); //referencing the caller of the plugin

      // referencing the caller plugin and init() is a function of the "object"
      this.init = function(element, options) {

      // referencing the caller of the plugin again, and it's options property
      this.options = $.extend({}, $.watermark.defaultOptions, options);

         //Manipulate element here ...
      };

      //Public function
      //referencing the caller plugin again, which is an object
      this.greet = function(name) {
         console.log('Hello, ' + name + ', welcome to Script Junkies!');
      };

      // referencing the caller of the plugin again
      this.init(element, options); //calling the init function of the object
   };

   $.fn.watermark = function(options) { //Using only one method off of $.fn
      //referencing the caller of the plugin again
      return this.each(function() {
         // representing the current element in the iteration
         (new $.watermark($(this), options));
      });
   };

   $.watermark.defaultOptions = {
      class: 'watermark',
      text: 'Enter Text Here'
   }
})(jQuery);

A: It refers to the object that this function is a method of
window <---- this (could be a button or textbox, etc.) ------- function()
in this case karl is correct, watermark.


text:
Q: Putting output into a variable I am trying to make a batch file that sets the JAVA_HOME.
Now I have the following code that looks for if a path exists.
If that is the case I would like to store the complete name in a variable.
set javaLoc=
set javaLoc=$(dir "C:\Program Files (x86)\Java\jre1.8*" /s/b)
echo %javaLoc%

But the echo returns me:
$(dir "C:\Program Files (x86)\Java\jre1.8*" /s/b)

While I would like to capture the output (C:\Program Files (x86)\Java\jre1.8.0_40) from it in "javaLoc".
I also tried:
dir "C:\Program Files (x86)\Java\jre1.8*" /s/b > javaLoc

But also that doesn't work.
Can anyone help me on what I am doing wrong?

A: I see you're coming in with experience from bash (or possibly kornshell). Sadly, batch is a bit more limited than it's *nix counterpart, so you can't directly store the output of a command in a variable.
You can, however, run the command through a for /F loop and store the result in a variable that way, like this:
for /F %%A in ('dir "C:\Program Files (x86)\Java\jre1.8*" /s /b') do (
    set javaLoc=%%A
)

Although it should be noted that if there is more than one item returned by this command, javaLoc will be set to the last one in the list.


text:
Q: Will this code return UIView as its return type I have read this in a code
the code is as follows
- (UIView *)headerView
{

// your code for the function

}

in this code the what is the return type of the function?
is it UIView...?

A: Yes it will return the UIView
For Example:
write in any class in your viewDidAppear method
UIView *view = [self returnView];

and the returnView function is:
-(UIView *) returnView{
// your function code
// for now you may test it as
return self.view;
}


text:
Q: How can I create a table with images that adjust to fit the size of the  box? I am working on a mobile version of a spa website for a friend, and I have been able to get the images to fit to the screen size properly, but there is always room left over in each table cell that I want the image to utilize instead of wasting space.
 Here is the relevant HTML/CSS I'm using:

table.wide {
width: 100%;
margin: auto;
display: block;}

img.service-4-pics {
margin: auto;
width: 100%;
height: auto;
display: block;}

A: You also should set the width of the  cells:
CSS:
table.wide td {
    width: 33%;
}

OR, HTML:


text:
Q: How can i get coordinates in the route path in google map? if using the link like this
http://maps.google.com/maps?f=d&hl=en&saddr=25.04202,121.534761
&daddr=25.05202,121.554761&ie=UTF8&0&om=0&output=kml

it will return the value of coordinates as below:

121.534760,25.042040,0.000000
  121.533650,25.042190,0.000000 121.532950,25.042430,0.000000 121.532950,25.042430,0.000000 121.532980,25.044400,0.000000 121.532980,25.044400,0.000000 121.534000,25.044670,0.000000 121.534400,25.044820,0.000000 121.535690,25.045690,0.000000 121.536400,25.045990,0.000000 121.540510,25.046700,0.000000 121.543860,25.047490,0.000000 121.546430,25.048160,0.000000 121.549130,25.048140,0.000000 121.549130,25.048140,0.000000 121.550770,25.048110,0.000000 121.552570,25.048140,0.000000 121.552570,25.048140,0.000000 121.552700,25.049850,0.000000 121.552750,25.051440,0.000000 121.552650,25.051540,0.000000 121.552640,25.051680,0.000000 121.552640,25.051680,0.000000 121.552660,25.052280,0.000000 121.552660,25.052280,0.000000 121.553770,25.052260,0.000000 121.553770,25.052260,0.000000 121.554770,25.052240,0.000000

but in my javascript, it returned roughly just a few coordinates, 5-6 coordinates
Here is my code to get coordinates :
function route(FromPlace,ToPlace){
if(!FromPlace&&!ToPlace){
    FromPlace = new google.maps.LatLng(13.692941, 100.750723);
    ToPlace = document.getElementById("endPoint").value;
}
    //directionsService = new google.maps.DirectionsService();
     var request = {
            origin: FromPlace,
            destination: ToPlace,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK)
        {

            directionsDisplay.setDirections(response);
     for (var i = 0; i < response.routes[0].legs.length; i++) {
             for (var j = 0; j < response.routes[0].legs[i].steps.length; j++) {
                 if(j == response.routes[0].legs[i].steps.length-1){

                    addressRoute = addressRoute+response.routes[0].legs[i].steps[j].end_point.lat()+","
                      +response.routes[0].legs[i].steps[j].end_point.lng()+"";
                    latitude = response.routes[0].legs[i].steps[j].end_point.lat();
                    longitude = response.routes[0].legs[i].steps[j].end_point.lng();
                    destinationDB = latitude +","+ longitude;
                    }else{

                    addressRoute = addressRoute+response.routes[0].legs[i].steps[j].end_point.lat()+","
                      +response.routes[0].legs[i].steps[j].end_point.lng()+"|";

                    }
                 }
            }
            //document.getElementById("textLocation").innerHTML = addressRoute;
        }
      });
   }

How can i improve my code to get coordinates more specific like the link above?
is there any suggestion? :)

A: what you need is not the steps[j].start_point and steps[j].end_point but the path object contained in each step object. that is to say:
route.legs.forEach(function(leg){
    leg.steps.forEach(function(step){
        step.path.forEach(function(point){
            debug_panel.innerHTML+=point+"<br/>";
        });
    });
});

you want to get each and every point in all of your steps' paths as well, not only the start and end points.
hope that helps


text:
Q: JPype error: import jpype ModuleNotFoundError: No module named 'jpype' I installed JPype in a correct way and anything is fine and my instalation was succeed but when i run my refactor.py from command prompt i have error that i pointed in title.
i hope you can help me for solving this problem.
also i have to point that i am beginner in python3.
here is my code:
  import urllib.request
        import os
        import tempfile
        import sys
        import fileinput
        import logging
        import jpype

   logging.basicConfig(filename="ERROR.txt", level= logging.ERROR)
try:
    logging.debug('we are in the main try loop')
    jpype.startJVM("C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest.java", "-ea")
    test_class = jpype.JClass("ClassWithTest")
    a = testAll()
    file_java_class = open("OUTPUT.txt", "w")
    file_java_class.write(a)
except Exception as e1:
        logging.error(str(e1))
        jpype.shutdownJVM()

A: startJVM() function takes the path to the JVM which is like this - C:\\Program Files\\Java\\jdk-10.0.2\\bin\\server\\jvm.dll. You could use the getDefaultJVMPath() function to get the JVM path on your PC. So you can just start the JVM this way:
startJVM(getDefaultJVMPath(), "-ea")

Hope that helps!


text:
Q: How to create a file in informatica with header and footer when there is no data coming from source? I have the following scenario.
In informatica, for a process flow which takes 2 input files, do union#1, derive the header and footer and do another union and load the Union#2 output to the target file.
But, even in case of blank file from source., I need to generate the file with header and footer(footer with the count as 2).
Expected content in target file, if we get blank sources:
HYYYYMMDDCODE1315           (header)
TYYYYMMDDCODE1315 0000002   (trailer with no.of records)
Can anyone please help?
Thanks in Advance!

A: You can use a 3rd input file - a dummy file with 1 column and 1 row. Full outer join this dummy file with the output of first union before deriving header/footer. Use a dummy column with the same value as in the file in the join condition (e.g. 1 = 1)
This way, there will be at least 1 row coming out of the joiner even if the actual input files does not have any data. Later you can filter out the dummy record by checking if the actual source fields are NULL.

A: You can use a pre-session command that will echo a header line to a file. Then in the session just append the data to an existing file (check the Append if Exists box).
Use post-session to append a footer line.

A: Instead of all this complex processes, I was able to get this using the following command in post session command in informatica.
if [ ! -s $PMTargetFileDir/$OutputFile1 ];then echo "H""$(date +"%Y%m%d")""$(date +"%Y%m%d")""XXX"""> $PMTargetFileDir/$OutputFile1;echo "T""$(date +"%Y%m%d")""$(date +"%Y%m%d")""XXX""""00000000002""" >> $PMTargetFileDir/$OutputFile1;fi;
Thank you all for your inputs!


text:
Q: Get elements by tag from inside an element using Selenium Webdriver in Jmeter I want to retrieve all the  elements, in a another  element which I have fetched By.id.
var pieCharts = WDS.browser.findElement(pkg.By.id("queueStatsGraphs"));

Now, i want to retrieve all the div elements inside pieCharts. This is the html code:

Some Info

Some Another Info

Some Info

Some Another Info

Now I want to retrieve all these div(s)inside the div with id 'queueStatsGraphs'.
How could i do that? Could anyone please me with this?

A: Your pieCharts is an instance of a WebElement which in its turn provides findElements() function so you can access these inner "divs" like:
var children = pieCharts.findElements(org.openqa.selenium.By.className("col-md-6"))

Some example code:
WDS.sampleResult.sampleStart()
WDS.browser.get('/path/to/your/page')
var pieCharts = WDS.browser.findElement(org.openqa.selenium.By.id("queueStatsGraphs"))
var children = pieCharts.findElements(org.openqa.selenium.By.className("col-md-6"))
children.forEach(myFunction);
function myFunction(child) {
  WDS.log.info(child.getText());
}
WDS.sampleResult.sampleEnd()

Demo:

More information: The WebDriver Sampler: Your Top 10 Questions Answered


text:
Q: Angular (v12) detect browser triggered navigation to send Google analytics call Having 'ga' call in app.component.ts in router event works only when we navigate from the app, if you enter a path in the browser search bar directly the event is not triggered.
app.component.ts
ngAfterViewInit() {
    this.router.events.subscribe((event: any) => {
      if(event instanceof NavigationEnd) {
        ga('set', 'page', event.urlAfterRedirects);
        ga('send', 'pageview');
      }
    })
  }

Navigating directly to a path from browser like https://example.com/some-path does not trigger the above event.
Having 'ga' call in ngOnInit() in every route is a solution but its redundant. Any effective solution for this?
And also having the above ga code in ngOnInit() instead of ngAfterViewInit() also does not help.

A: Just in case if someone is having the same problem, like the question says in local when you do ng s GA does not work on browser triggered navigation, but in the production server, since we configure nginx/apache to serve angular app we redirect 404 pages to root of the app and from there angular handles redirections to specified route or a 404 page, this is treated as in app navigation and GA works.
nginx config:
try_files $uri $uri/ /index.html;


text:
Q: crosscompile can't find header files for net-snmp (i686/mips64) I'm currently trying to cross compile onto mips64 using a shared object library, when I run the following command:
toby@cbmFinal:~/x-tools/mips64-n64-linux-gnu/bin$ ./mips64-n64-linux-gnu-gcc -I /home/toby/Downloads/net-snmp-5.5.2.1/include/net-snmp/ -L /usr/lib64/libnetsnmp.so ~/BsDiagnostics/snmpdemoapp.c -o snmpdemoapp

It throws an error saying it can't find the header files:
/home/toby/BsDiagnostics/snmpdemoapp.c:1:38: error: net-snmp/net-snmp-config.h: No such file or directory
/home/toby/BsDiagnostics/snmpdemoapp.c:2:40: error: net-snmp/net-snmp-includes.h: No such file or directory
/home/toby/BsDiagnostics/snmpdemoapp.c: In function 'main':
/home/toby/BsDiagnostics/snmpdemoapp.c:14: error: 'netsnmp_session' undeclared (first use in this function)
/home/toby/BsDiagnostics/snmpdemoapp.c:14: error: (Each undeclared identifier is reported only once
/home/toby/BsDiagnostics/snmpdemoapp.c:14: error: for each function it appears in.)
/home/toby/BsDiagnostics/snmpdemoapp.c:14: error: expected ';' before 'session'

etc etc
I have checked the dir and they're all there, I can also do them each manually using -include but then have a bunch of other headers I can't all -include.
toby@cbmFinal:~/Downloads/net-snmp-5.5.2.1/include/net-snmp$ ls
agent             definitions.h  mib_api.h.gch         output_api.h   session_api.h.gch  utilities.h
config_api.h      library        net-snmp-config.h     pdu_api.h      snmpv3_api.h       varbind_api.h
config_api.h.gch  machine        net-snmp-config.h.in  pdu_api.h.gch  system             varbind_api.h.gch
data_access       mib_api.h      net-snmp-includes.h   session_api.h  types.h            version.h

Any help would be appreciated. Thanks!

A: Fixed, was a syntax error.
Correct command was:
toby@cbmFinal:~/x-tools/mips64-n64-linux-gnu/bin$ ./mips64-n64-linux-gnu-gcc -I/home/toby/Downloads/net-snmp-5.5.2.1/include/ -L/usr/lib64 -lnetsnmp ~/BsDiagnostics/snmpdemoapp.c -o snmpdemoapp