问:
What is the difference between a service account and a context in Kubernetes?
What are the practical differences between the two? When should I choose one over the other?

For example if I'd like to give a developer in my project access to just view the logs of a pod. It seems both a service account or a context could be assigned these permissions via a RoleBinding.

答:
What is Service Account?

From Docs

User accounts are for humans. Service accounts are for processes,
  which run in pods.

User accounts are intended to be global...Service
  accounts are namespaced.

Context

context related to kubeconfig file(~/.kube/config). As you know kubeconfig file is a yaml file, the section context holds your user/token and cluster references. context is really usefull when you have multiple cluster, you can define all your clusters and users in single kubeconfig file, then you can switch between them with help of context (Example: kubectl config --kubeconfig=config-demo use-context dev-frontend)

From Docs

```<code>apiVersion: v1
clusters:
- cluster:
    certificate-authority: fake-ca-file
    server: https://1.2.3.4
  name: development
- cluster:
    insecure-skip-tls-verify: true
    server: https://5.6.7.8
  name: scratch
contexts:
- context:
    cluster: development
    namespace: frontend
    user: developer
  name: dev-frontend
- context:
    cluster: development
    namespace: storage
    user: developer
  name: dev-storage
- context:
    cluster: scratch
    namespace: default
    user: experimenter
  name: exp-scratch
current-context: ""
kind: Config
preferences: {}
users:
- name: developer
  user:
    client-certificate: fake-cert-file
    client-key: fake-key-file
- name: experimenter
  user:
    password: some-password
    username: exp
</code>```

You can above, there are 3 contexts, holds references of cluster and user.

..if I'd like to give a developer in my project access to just view the
  logs of a pod. It seems both a service account or a context could be
  assigned these permissions via a RoleBinding.

That correct, you need to create service account, Role(or ClusterRole), RoleBinding(or ClusterRoleBinding) and generate kubeconfig file that contains service account token and give it your developer.

I have a script to generate kubconfig file, takes service account name argument. Feel free to check out

UPDATE:

If you want to create Role and RoleBinding, this might help

Body:
What is Service Account?

From Docs

User accounts are for humans. Service accounts are for processes,
  which run in pods.

User accounts are intended to be global...Service
  accounts are namespaced.

Context

context related to kubeconfig file(~/.kube/config). As you know kubeconfig file is a yaml file, the section context holds your user/token and cluster references. context is really usefull when you have multiple cluster, you can define all your clusters and users in single kubeconfig file, then you can switch between them with help of context (Example: kubectl config --kubeconfig=config-demo use-context dev-frontend)

From Docs

apiVersion: v1
clusters:
- cluster:
    certificate-authority: fake-ca-file
    server: https://1.2.3.4
  name: development
- cluster:
    insecure-skip-tls-verify: true
    server: https://5.6.7.8
  name: scratch
contexts:
- context:
    cluster: development
    namespace: frontend
    user: developer
  name: dev-frontend
- context:
    cluster: development
    namespace: storage
    user: developer
  name: dev-storage
- context:
    cluster: scratch
    namespace: default
    user: experimenter
  name: exp-scratch
current-context: ""
kind: Config
preferences: {}
users:
- name: developer
  user:
    client-certificate: fake-cert-file
    client-key: fake-key-file
- name: experimenter
  user:
    password: some-password
    username: exp

You can above, there are 3 contexts, holds references of cluster and user.

..if I'd like to give a developer in my project access to just view the
  logs of a pod. It seems both a service account or a context could be
  assigned these permissions via a RoleBinding.

That correct, you need to create service account, Role(or ClusterRole), RoleBinding(or ClusterRoleBinding) and generate kubeconfig file that contains service account token and give it your developer.

I have a script to generate kubconfig file, takes service account name argument. Feel free to check out

UPDATE:

If you want to create Role and RoleBinding, this might help


来源: stackexchange

问:
Parsing xml and extract specific attribute of child element in groovy
I have the following xml as string: (using groovy playground for fast executions here: https://groovy-playground.appspot.com/)

```<code>#!groovy
import groovy.util.XmlParser
import groovy.json.JsonSlurper
import groovy.JCIFS.*
import groovy.SmbFile.*

string = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<machine osBit="x64" osVersion="5.6" platform="linux" ip="A.A.A.A" lastTimeIdentified="1553611375772" name="AGENT_NAME" xsi:schemaLocation="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ssh xsi:type="sshContext" password="root12" user="root"/>
    <interfaces>
        <interface alias="false" ipAddress="A.A.A.A" name="eth0"/>
    </interfaces>
    <bsx_msi teradataVersionImperva="NOT_TD" uekVersionImperva="NOT_UEK" uname_m="x86_64" uname_n="AGENT_NAME" uname_r="2.6.32-100.26.2.el5" uname_s="Linux" uname_v="#1 SMP Tue Jan 18 20:11:49 EST 2011"/>
    <services>
        <service dbHomePath="/opt/oracle/app/oracle/product/11.2.0/db" dbName="orcl" dbPassword="barbapapa" dbUser="system" dbVersion="11.2.0.1.0" isMariaDB="false" sshPassword="oracle" sshUser="oracle" enabled="true" serviceName="defaultService" **type="Oracle"**>
            <channels>
                <channel xsi:type="machineIdentifierChannelDbAlias" channelType="OracleBEQ" enabled="true">
                    <connections>
                        <connection xsi:type="localConnection" platform="linux" sshPassword="oracle" sshUser="oracle" channelType="OracleBEQ" connectionType="Local" dbName="orcl" dbPassword="barbapapa" dbUser="system" host="A.A.A.A" serviceType="Oracle"/>
                    </connections>
                </channel>
            </channels>
        </service>
    </services>
    <zoneConfiguration/>
</machine>
"""
</code>```

And i want to extract the type "oracle" from the tag "service", which is an attribute of the tag, always getting an error, this is the code i am trying to run:

```<code>def xmlParser = new XmlParser().parseText(string)
agentPlatform = xmlParser.services.service.attribute("type")
println agentPlatform
</code>```

What is the correct form of doing so?

答:
Found an answer: </p>

```<code>def xmlParser = new XmlParser().parseText(string)

results = xmlParser.services[0].service[0].@type
println results //Oracle
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following xml as string: (using groovy playground for fast executions here: https://groovy-playground.appspot.com/)

#!groovy
import groovy.util.XmlParser
import groovy.json.JsonSlurper
import groovy.JCIFS.*
import groovy.SmbFile.*

string = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<machine osBit="x64" osVersion="5.6" platform="linux" ip="A.A.A.A" lastTimeIdentified="1553611375772" name="AGENT_NAME" xsi:schemaLocation="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ssh xsi:type="sshContext" password="root12" user="root"/>
    <interfaces>
        <interface alias="false" ipAddress="A.A.A.A" name="eth0"/>
    </interfaces>
    <bsx_msi teradataVersionImperva="NOT_TD" uekVersionImperva="NOT_UEK" uname_m="x86_64" uname_n="AGENT_NAME" uname_r="2.6.32-100.26.2.el5" uname_s="Linux" uname_v="#1 SMP Tue Jan 18 20:11:49 EST 2011"/>
    <services>
        <service dbHomePath="/opt/oracle/app/oracle/product/11.2.0/db" dbName="orcl" dbPassword="barbapapa" dbUser="system" dbVersion="11.2.0.1.0" isMariaDB="false" sshPassword="oracle" sshUser="oracle" enabled="true" serviceName="defaultService" **type="Oracle"**>
            <channels>
                <channel xsi:type="machineIdentifierChannelDbAlias" channelType="OracleBEQ" enabled="true">
                    <connections>
                        <connection xsi:type="localConnection" platform="linux" sshPassword="oracle" sshUser="oracle" channelType="OracleBEQ" connectionType="Local" dbName="orcl" dbPassword="barbapapa" dbUser="system" host="A.A.A.A" serviceType="Oracle"/>
                    </connections>
                </channel>
            </channels>
        </service>
    </services>
    <zoneConfiguration/>
</machine>
"""

And i want to extract the type "oracle" from the tag "service", which is an attribute of the tag, always getting an error, this is the code i am trying to run:

def xmlParser = new XmlParser().parseText(string)
agentPlatform = xmlParser.services.service.attribute("type")
println agentPlatform

What is the correct form of doing so?

Body:
Found an answer:

def xmlParser = new XmlParser().parseText(string)

results = xmlParser.services[0].service[0].@type
println results //Oracle


问:
how to get values from dynamic inputs in Angular?
I have a text that depends on a dropdown list.If I check 1 element I will see a text field. if i check 2 i will have 2 input  ...
the drop-down list is dynamic and I do not know the number of its members each time.
 so can you help me get the input values and associates to the id values from the drop-down list because they are linked and put them in a list that contains the id and value of the input and thanks.</p>

```<code>
//this is the dropdown
<ng-multiselect-dropdown [data]="serviceModalite.list"
    name="modaliteDemande"
    [settings]="dropdownSettingsModalite"
    [(ngModel)]="selectedItemsModalite"
    (onSelect)="onItemSelectModalite($event)"
    (onDeSelect)="OnItemDeSelectModalite($event)"
    (onSelectAll)="onSelectAllModalite($event)"
    (onDeSelectAll)="onDeSelectAllModalite($event)">
</ng-multiselect-dropdown>

//this is the dynamic input that i want to put its values in a list
<div *ngFor="let M of selectedItemsModalite">
      <label>Tarif {{M.NameModalite}}</label>
      <input placeholder="price">
</div>
</code>```

答:
For dynamic form items, you'll need a FormArray field in your FormGroup definition. Check out this article.

Define your form:

```<code>ngOnInit() {
  this.orderForm = this.formBuilder.group({
    customerName: '',
    email: '',
    items: this.formBuilder.array([])
  });
}
</code>```

Use formArrayName and formGroupName to work with the dynamic form entries. Most of the time, the index will be your group name. Use formControlName to simply bind to a name.

```<code><div formArrayName="items"
  *ngFor="let item of orderForm.get('items').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="name" placeholder="Item name">
    <input formControlName="description" placeholder="Item description">
    <input formControlName="price" placeholder="Item price">
  </div>

  Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
</div>
</code>```

Whenever any of the dynamic form items change, update your form definition as well.

```<code>createItem(): FormGroup {
  return this.formBuilder.group({
    name: '',
    description: '',
    price: ''
  });
}

addItem(): void {
  this.items = this.orderForm.get('items') as FormArray;
  this.items.push(this.createItem());
}
</code>```

Body:
I have a text that depends on a dropdown list.If I check 1 element I will see a text field. if i check 2 i will have 2 input  ...
the drop-down list is dynamic and I do not know the number of its members each time.
 so can you help me get the input values and associates to the id values from the drop-down list because they are linked and put them in a list that contains the id and value of the input and thanks.

//this is the dropdown
<ng-multiselect-dropdown [data]="serviceModalite.list"
    name="modaliteDemande"
    [settings]="dropdownSettingsModalite"
    [(ngModel)]="selectedItemsModalite"
    (onSelect)="onItemSelectModalite($event)"
    (onDeSelect)="OnItemDeSelectModalite($event)"
    (onSelectAll)="onSelectAllModalite($event)"
    (onDeSelectAll)="onDeSelectAllModalite($event)">
</ng-multiselect-dropdown>

//this is the dynamic input that i want to put its values in a list

      Tarif {{M.NameModalite}}
      <input placeholder="price">

Body:
For dynamic form items, you'll need a FormArray field in your FormGroup definition. Check out this article.

Define your form:

ngOnInit() {
  this.orderForm = this.formBuilder.group({
    customerName: '',
    email: '',
    items: this.formBuilder.array([])
  });
}

Use formArrayName and formGroupName to work with the dynamic form entries. Most of the time, the index will be your group name. Use formControlName to simply bind to a name.

<div formArrayName="items"
  *ngFor="let item of orderForm.get('items').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="name" placeholder="Item name">
    <input formControlName="description" placeholder="Item description">
    <input formControlName="price" placeholder="Item price">
  </div>

  Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
</div>

Whenever any of the dynamic form items change, update your form definition as well.

createItem(): FormGroup {
  return this.formBuilder.group({
    name: '',
    description: '',
    price: ''
  });
}

addItem(): void {
  this.items = this.orderForm.get('items') as FormArray;
  this.items.push(this.createItem());
}


问:
How to fix: Empty IP Address for nginx-ingress on digital-ocean
In my k8s cluster the ingress does not work on the k8s cluster of digital ocean. I don't get an external ip and so it is not available. Locally there seems to be no problem.

I already searched a lot and tried some tutorials, f.e. https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes.
But it seems that it is an older version and the solution (and even the links) does not work anymore.

The nginx-ingress should call the service of a website backend which is on port 8080.

I stripped down my ingress code to the following one:

```<code>kind: Ingress
metadata:
  name: test-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: website
          servicePort: 8080
</code>```

With kubectl get ing I see the ingress, but it has no address. It looks like this

```<code>NAME           HOSTS   ADDRESS   PORTS   AGE
test-ingress   *                 80      50s
</code>```

Can anyone help me out and tell me what I have to do to get my k8s cluster running?

Thanks
peter

答:
Firstly, if you are using Nginx Ingress Controller, you don't need to see ingress address.

When you install Nginx Ingress Controller to your k8s cluster, it creates Load Balancer to handle all incoming requests. Make sure that below part completed as explained in Step 2 of guide you posted and you are able to see LoadBalancer External ip address.

```<code>$ kubectl get svc --namespace=ingress-nginx
</code>```

You should see an external IP address, corresponding to the IP address of the DigitalOcean Load Balancer:

```<code>Output
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP       PORT(S)                      AGE
ingress-nginx   LoadBalancer   10.245.247.67   203.0.113.0   80:32486/TCP,443:32096/TCP   20h
</code>```

In above case, after deploying your ingress resource, if you hit http://203.0.113.0 you will get your website:8080 backend service.

Hope it helps!

Body:
In my k8s cluster the ingress does not work on the k8s cluster of digital ocean. I don't get an external ip and so it is not available. Locally there seems to be no problem.

I already searched a lot and tried some tutorials, f.e. https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes.
But it seems that it is an older version and the solution (and even the links) does not work anymore.

The nginx-ingress should call the service of a website backend which is on port 8080.

I stripped down my ingress code to the following one:

kind: Ingress
metadata:
  name: test-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: website
          servicePort: 8080

With kubectl get ing I see the ingress, but it has no address. It looks like this

NAME           HOSTS   ADDRESS   PORTS   AGE
test-ingress   *                 80      50s

Can anyone help me out and tell me what I have to do to get my k8s cluster running?

Thanks
peter

Body:
Firstly, if you are using Nginx Ingress Controller, you don't need to see ingress address.

When you install Nginx Ingress Controller to your k8s cluster, it creates Load Balancer to handle all incoming requests. Make sure that below part completed as explained in Step 2 of guide you posted and you are able to see LoadBalancer External ip address.

$ kubectl get svc --namespace=ingress-nginx

You should see an external IP address, corresponding to the IP address of the DigitalOcean Load Balancer:

Output
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP       PORT(S)                      AGE
ingress-nginx   LoadBalancer   10.245.247.67   203.0.113.0   80:32486/TCP,443:32096/TCP   20h

In above case, after deploying your ingress resource, if you hit http://203.0.113.0 you will get your website:8080 backend service.

Hope it helps!


问:
Cannot render "create" and "edit" page as it returns Error 500 in mvc .net framework
I'm about to develop an ASP.NET MVC application using AdminLTE template. For the CRUD operation, I used new scaffolded item using create "MVC 5 Controller with views, using Entity Framework". The edit and delete works just fine but "create" and "edit" operation did not work out as an error 500 appears after I run these methods.

This is the code for my controller:

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using test2.Models;

namespace test2.Views
{
    public class CasesController : Controller
    {
        private eLawDBModel db = new eLawDBModel();

        // GET: Cases
        public async Task<ActionResult> Index()
        {
            return View(await db.Cases.ToListAsync());
        }

        // GET: Cases/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Case @case = await db.Cases.FindAsync(id);

            if (@case == null)
            {
                return HttpNotFound();
            }

            return View(@case);
        }

        // GET: Cases/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Cases/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "caseID,caseName")] Case @case)
        {
            if (ModelState.IsValid)
            {
                db.Cases.Add(@case);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(@case);
        }

        // GET: Cases/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Case @case = await db.Cases.FindAsync(id);

            if (@case == null)
            {
                return HttpNotFound();
            }

            return View(@case);
        }

        // POST: Cases/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "caseID,caseName")] Case @case)
        {
            if (ModelState.IsValid)
            {
                db.Entry(@case).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(@case);
        }

        // GET: Cases/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Case @case = await db.Cases.FindAsync(id);

            if (@case == null)
            {
                return HttpNotFound();
            }

            return View(@case);
        }

        // POST: Cases/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            Case @case = await db.Cases.FindAsync(id);
            db.Cases.Remove(@case);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

</code>```

This is the view markup of create operation:

```<code>@model test2.Models.Case

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Case</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.caseName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.caseName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.caseName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

</code>```

and this is the view markup for edit operation:

```<code>@model test2.Models.Case

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Case</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.caseID)

        <div class="form-group">
            @Html.LabelFor(model => model.caseName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.caseName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.caseName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

</code>```

The page shows this error after I run the create operation:

[ERROR 500]

  Oops! Something went wrong.

  There was an error processing your request. Please, try again.

  If the problem persists, contact support.

The server I am using right now is IIS Windows version 10.0.

答: As you know sometimes [ValidateAntiForgeryToken] making the problem with there browser compatibility, so first remove the [ValidateAntiForgeryToken] tag from controller and remove @Html.AntiForgeryToken() from view as well.</p>

Body:
I'm about to develop an ASP.NET MVC application using AdminLTE template. For the CRUD operation, I used new scaffolded item using create "MVC 5 Controller with views, using Entity Framework". The edit and delete works just fine but "create" and "edit" operation did not work out as an error 500 appears after I run these methods.

This is the code for my controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using test2.Models;

namespace test2.Views
{
    public class CasesController : Controller
    {
        private eLawDBModel db = new eLawDBModel();

        // GET: Cases
        public async Task<ActionResult> Index()
        {
            return View(await db.Cases.ToListAsync());
        }

        // GET: Cases/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Case @case = await db.Cases.FindAsync(id);

            if (@case == null)
            {
                return HttpNotFound();
            }

            return View(@case);
        }

        // GET: Cases/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Cases/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "caseID,caseName")] Case @case)
        {
            if (ModelState.IsValid)
            {
                db.Cases.Add(@case);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(@case);
        }

        // GET: Cases/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Case @case = await db.Cases.FindAsync(id);

            if (@case == null)
            {
                return HttpNotFound();
            }

            return View(@case);
        }

        // POST: Cases/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "caseID,caseName")] Case @case)
        {
            if (ModelState.IsValid)
            {
                db.Entry(@case).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(@case);
        }

        // GET: Cases/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Case @case = await db.Cases.FindAsync(id);

            if (@case == null)
            {
                return HttpNotFound();
            }

            return View(@case);
        }

        // POST: Cases/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            Case @case = await db.Cases.FindAsync(id);
            db.Cases.Remove(@case);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

This is the view markup of create operation:

@model test2.Models.Case

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Case

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.caseName, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.caseName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.caseName, "", new { @class = "text-danger" })

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

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

and this is the view markup for edit operation:

@model test2.Models.Case

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Case

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.caseID)

            @Html.LabelFor(model => model.caseName, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.caseName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.caseName, "", new { @class = "text-danger" })

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

The page shows this error after I run the create operation:

[ERROR 500]

  Oops! Something went wrong.

  There was an error processing your request. Please, try again.

  If the problem persists, contact support.

The server I am using right now is IIS Windows version 10.0.


问:
Changes made in .subscribe() method not reflected out of it or in the template
I am using a Subject to add edit functionality to a basic phonebook app.
The changes that I make to component class variables inside of the subscribe callback are not reflected out of it or in the template.

I have tried the solutions listed in the answers to the following question:
Angular 2 View will not update after variable change in subscribe

in service.ts:

```<code>startedEditing= new Subject<number>();
</code>```

in details.component.ts(where the data is passed on fu):

```<code>onEdit(){
    this.contactsService.startedEditing.next(this.id);
  }
</code>```

in edit-component.ts(in ngOnInit):

```<code>this.subscription=this.contactsService.startedEditing.subscribe(
      (index:number)=>{
        this.editMode=true;
        this.editedItemIndex=index;
        this.editItem=this.contactsService.getContact(this.editedItemIndex);
          this.editForm.setValue({
            address:this.editItem.address,
            name: this.editItem.name,
            phone:this.editItem.phone,
            profession:this.editItem.profession
          });
          console.log("in subscribe: "+this.editedItemIndex);

      }
    );
    console.log("out of it :" + this.editedItemIndex);
  }
</code>```

output on the console:

```<code>in subscribe: 0
out of it : undefined
</code>```

expected result:

```<code>in subscribe: 0
out of it :0
</code>```

答:
The console.log("out of it :") will run only when your component is initialized, and at this moment this.editedItemIndex is undefined because startedEditing didn't change so the line this.editedItemIndex=index has not been triggered.

It's asynchronous ! If you do a startedEditing.subscribe() it's because you are waiting something (Ex: a value). If you try to get the value outside the subscribe, it will not wait for the value and will show undefined.

And if you try your code, the real output should be :

```<code>out of it : undefined
in subcribe : 0
</code>```

Body:
I am using a Subject to add edit functionality to a basic phonebook app.
The changes that I make to component class variables inside of the subscribe callback are not reflected out of it or in the template.

I have tried the solutions listed in the answers to the following question:
Angular 2 View will not update after variable change in subscribe

in service.ts:

startedEditing= new Subject<number>();

in details.component.ts(where the data is passed on fu):

onEdit(){
    this.contactsService.startedEditing.next(this.id);
  }

in edit-component.ts(in ngOnInit):

this.subscription=this.contactsService.startedEditing.subscribe(
      (index:number)=>{
        this.editMode=true;
        this.editedItemIndex=index;
        this.editItem=this.contactsService.getContact(this.editedItemIndex);
          this.editForm.setValue({
            address:this.editItem.address,
            name: this.editItem.name,
            phone:this.editItem.phone,
            profession:this.editItem.profession
          });
          console.log("in subscribe: "+this.editedItemIndex);

      }
    );
    console.log("out of it :" + this.editedItemIndex);
  }

output on the console:

in subscribe: 0
out of it : undefined

expected result:

in subscribe: 0
out of it :0

Body:
The console.log("out of it :") will run only when your component is initialized, and at this moment this.editedItemIndex is undefined because startedEditing didn't change so the line this.editedItemIndex=index has not been triggered.

It's asynchronous ! If you do a startedEditing.subscribe() it's because you are waiting something (Ex: a value). If you try to get the value outside the subscribe, it will not wait for the value and will show undefined.

And if you try your code, the real output should be :

out of it : undefined
in subcribe : 0


问:
Remove a list of provided letters from the start of the string
I have a dataframe-df with column "Names" as below :

```<code>Names
AL GHAITHA & AL MOOSA
AL ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
THE MAX
</code>```

Code :

```<code>remove_letters = ['AL ', 'THE ']

# my function below :

def remove_start_words(df, col, letters):
    for l in letters:
        for i in df.index:
            x = df.at[i, col]
            if x.startswith(l):
                df.at[i, col] = x[len(l):]
            else:
                df.at[i, col] = x

def remove_strings(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

def remove_end_digits(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        df.at[i, col] = x.rstrip(string.digits)

# calling my function
remove_start_words(df=df, col='Names',
                          letters=remove_letters)

remove_strings(df=df, col='Names')
remove_end_digits(df=df, col='Names')
</code>```

Now the problem is i have a dataframe of more than 1 million column values.
My code is not well optimized ? How to get a optimized solution ?

Issue 1 :
I can understand i have used 2 loops ( 1 for remove_letters and other for all the column values) that is causing slowness.

Is there a better way ? where i can check if the column values start with the letters mentioned in remove_letters list and strip them at one shot ?

Issue 2 & 3 :
What is objective of the function - "remove_strings" :
Get only the 2 strings from the column names. For eg : ASEEL ELECTRONICS T
output will be : ASEEL ELECTRONICS

Is there a faster way for the functions : remove_strings,remove_end_digits

Main issue : Can all this 3 functions can be done at one shot all together ?

Expected dataframe:

```<code>Names
GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET
EMARAT-AL SAFIYAH
LULU CENTRE
MAX
</code>```

NOTE : The function "remove_start_words" should check if any of the mentioned letters are starting in the "Names" if so, remove them.
For eg : "AL THEMAX" should be "THEMAX" not as "MAX" (removing both AL and THE)

Thanks in advance.

答:
You can use the replace method like this:</p>

```<code>import pandas as pd

file_path = 'file3.xlsx'

df = pd.read_excel(file_path)

words_to_remove = ["THE", "AL"]

for word in words_to_remove:
    df.Names = df.Names.str.replace(word, "")

print(df)
</code>```

Body:
I have a dataframe-df with column "Names" as below :

Names
AL GHAITHA & AL MOOSA
AL ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
THE MAX

Code :

remove_letters = ['AL ', 'THE ']

# my function below :

def remove_start_words(df, col, letters):
    for l in letters:
        for i in df.index:
            x = df.at[i, col]
            if x.startswith(l):
                df.at[i, col] = x[len(l):]
            else:
                df.at[i, col] = x

def remove_strings(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

def remove_end_digits(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        df.at[i, col] = x.rstrip(string.digits)

# calling my function
remove_start_words(df=df, col='Names',
                          letters=remove_letters)

remove_strings(df=df, col='Names')
remove_end_digits(df=df, col='Names')

Now the problem is i have a dataframe of more than 1 million column values.
My code is not well optimized ? How to get a optimized solution ?

Issue 1 :
I can understand i have used 2 loops ( 1 for remove_letters and other for all the column values) that is causing slowness.

Is there a better way ? where i can check if the column values start with the letters mentioned in remove_letters list and strip them at one shot ?

Issue 2 & 3 :
What is objective of the function - "remove_strings" :
Get only the 2 strings from the column names. For eg : ASEEL ELECTRONICS T
output will be : ASEEL ELECTRONICS

Is there a faster way for the functions : remove_strings,remove_end_digits

Main issue : Can all this 3 functions can be done at one shot all together ?

Expected dataframe:

Names
GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET
EMARAT-AL SAFIYAH
LULU CENTRE
MAX

NOTE : The function "remove_start_words" should check if any of the mentioned letters are starting in the "Names" if so, remove them.
For eg : "AL THEMAX" should be "THEMAX" not as "MAX" (removing both AL and THE)

Thanks in advance.

Body:
You can use the replace method like this:

import pandas as pd

file_path = 'file3.xlsx'

df = pd.read_excel(file_path)

words_to_remove = ["THE", "AL"]

for word in words_to_remove:
    df.Names = df.Names.str.replace(word, "")

print(df)


问:
Qt - What is meant by those lines of code
In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:

```<code>#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
dialog->show();
return app.exec();
}
</code>```

Can you just describe those lines of code?

```<code>    Ui::GoToCellDialog ui;
    QDialog *dialog = new QDialog;
    ui.setupUi(dialog);
</code>```

Thanks.

答: "ui_gotocelldialog.h" is a file generated automatically based on the file "gotocelldialog.ui" which contains the GUI for the dialog. Ui::GoToCellDialog::setupUi() must be called for the UI to be initialized.</p>

ContentLicense: CC BY-SA 3.0

Body:
In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:

#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
dialog->show();
return app.exec();
}

Can you just describe those lines of code?

    Ui::GoToCellDialog ui;
    QDialog *dialog = new QDialog;
    ui.setupUi(dialog);

Thanks.


问:
Unable to set AudioSession inactive with AVPlayer
I am using an AVPlayer to playback audio in my iOS app (because the audio files I'm playing are not local), and when my track finishes, I want to hide the InfoCenter controls, but I get this error:

AVAudioSession.mm:1079:-[AVAudioSession setActive:withOptions:error:]: Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.

I am however pausing my AVPlayer before.

This is my code:

player.pause()
player.replaceCurrentItem(with: nil)

MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
try? audioSession.setActive(false, options: .notifyOthersOnDeactivation)
```

Due to this error, the native controls remain visible, but don't work anymore.

答:
Try This</p>

```<code>player.pause()
player.replaceCurrentItem(with: nil)
player = nil
</code>```

Body:
I am using an AVPlayer to playback audio in my iOS app (because the audio files I'm playing are not local), and when my track finishes, I want to hide the InfoCenter controls, but I get this error:

AVAudioSession.mm:1079:-[AVAudioSession setActive:withOptions:error:]: Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.

I am however pausing my AVPlayer before.

This is my code:

player.pause()
player.replaceCurrentItem(with: nil)

MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
try? audioSession.setActive(false, options: .notifyOthersOnDeactivation)

Due to this error, the native controls remain visible, but don't work anymore.

Body:
Try This

player.pause()
player.replaceCurrentItem(with: nil)
player = nil


问:
Find better way to see if object has filled fields
I got the filter in Vue.

Template:

```<code><b-button v-if="filterFilled()" @click="clearFilter">
    Clear
</b-button>
</code>```

Data:

```<code>data () {
      return {
        filter: {
          price_from: '',
          price_to: '',
          surface_from: '',
          surface_to: '',
          floor: '',
          type: '',
          structure: '',
        },
      }
    },
</code>```

And my method where I check is filter dirty:

```<code>filterFilled(){
        return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from ||
          this.filter.floor || this.filter.type || this.filter.structure)
      },
</code>```

This works fine, but my question is, does it exists better way to ask if object has filled props?

答:
You could check if this.filter has at least one truthy value using some

```<code>filterFilled() {
  return Object.values(this.filter).some(v => v)
}
</code>```

Body:
I got the filter in Vue.

Template:

    Clear

Data:

data () {
      return {
        filter: {
          price_from: '',
          price_to: '',
          surface_from: '',
          surface_to: '',
          floor: '',
          type: '',
          structure: '',
        },
      }
    },

And my method where I check is filter dirty:

filterFilled(){
        return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from ||
          this.filter.floor || this.filter.type || this.filter.structure)
      },

This works fine, but my question is, does it exists better way to ask if object has filled props?

Body:
You could check if this.filter has at least one truthy value using some

filterFilled() {
  return Object.values(this.filter).some(v => v)
}


问:
How to select from table one with all records from table 2
I am trying to display all records that table 1 contains, each record with all the records from table 2 :</p>

```<code>Table 1

company  adress
------------------
 A        AdressX
 B        AdressY
 C        AdressZ

Table 2

Product   Price
----------------
 P1        50
 P2        60

Result :

company  Product
----------------
 A        P1
 A        P2
 B        P1
 B        P2
 C        P1
 C        P2
</code>```

答:
That would be a cross join.</p>

```<code>SELECT t1.company,
       t2.product
       FROM [table 1] t1
            CROSS JOIN [table 2] t2
       ORDER BY t1.company,
                t2.product;
</code>```

Body:
I am trying to display all records that table 1 contains, each record with all the records from table 2 :

Table 1

company  adress
------------------
 A        AdressX
 B        AdressY
 C        AdressZ

Table 2

Product   Price
----------------
 P1        50
 P2        60

Result :

company  Product
----------------
 A        P1
 A        P2
 B        P1
 B        P2
 C        P1
 C        P2

Body:
That would be a cross join.

SELECT t1.company,
       t2.product
       FROM [table 1] t1
            CROSS JOIN [table 2] t2
       ORDER BY t1.company,
                t2.product;


问:
Getting all the dates of a month when a date is provided using angularjs
I want to get all the dates of a month when a date is provided by the user. I am a newbie to angularjs. How can I achieve this ?</p>

答:
Steps to achieve this...

take a date as input from user;

calculate first and last dates of that month;

run a loop which gets all the dates in between and stores in an array;

print the array on screen

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  $scope.particularDate;
  $scope.relevantMonth;
  $scope.relevantYear;
  $scope.relevantFirstDate;
  $scope.relevantLastDate;

  $scope.calcDate = function() {
    if ($scope.selectedDate) {
      $scope.yearPart = $scope.selectedDate.toString().substring(11, 15);
      $scope.particularDate = new Date($scope.selectedDate.toString().substring(0, 10));
      $scope.particularDate.setYear($scope.yearPart);

      $scope.relevantMonth = $scope.particularDate.getMonth() + 1;
      $scope.relevantYear = $scope.particularDate.getFullYear();

      $scope.relevantLastDate = new Date($scope.relevantYear, $scope.relevantMonth, 0);
      $scope.relevantFirstDate = new Date($scope.relevantYear, $scope.relevantMonth - 1, 1);
      $scope.fillAllDays();
    }
  }

  $scope.fillAllDays = function() {
    $scope.monthArray = [];

    var t = $scope.relevantFirstDate;
    $scope.monthArray.push(t.toLocaleDateString());

    for (var i = $scope.relevantFirstDate.getDate(); i < $scope.relevantLastDate.getDate(); i++) {
      t.setDate(t.getDate() + 1);
      $scope.monthArray.push(t.toLocaleDateString());
    }
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  Date: <input type='date' ng-model='selectedDate' ng-change='calcDate()' /> <br>
  <hr/>
  <p ng-repeat='x in monthArray'>{{x}}</p>
</div></code>```

Body:
Steps to achieve this...

take a date as input from user;

calculate first and last dates of that month;

run a loop which gets all the dates in between and stores in an array;

print the array on screen

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  $scope.particularDate;
  $scope.relevantMonth;
  $scope.relevantYear;
  $scope.relevantFirstDate;
  $scope.relevantLastDate;

  $scope.calcDate = function() {
    if ($scope.selectedDate) {
      $scope.yearPart = $scope.selectedDate.toString().substring(11, 15);
      $scope.particularDate = new Date($scope.selectedDate.toString().substring(0, 10));
      $scope.particularDate.setYear($scope.yearPart);

      $scope.relevantMonth = $scope.particularDate.getMonth() + 1;
      $scope.relevantYear = $scope.particularDate.getFullYear();

      $scope.relevantLastDate = new Date($scope.relevantYear, $scope.relevantMonth, 0);
      $scope.relevantFirstDate = new Date($scope.relevantYear, $scope.relevantMonth - 1, 1);
      $scope.fillAllDays();
    }
  }

  $scope.fillAllDays = function() {
    $scope.monthArray = [];

    var t = $scope.relevantFirstDate;
    $scope.monthArray.push(t.toLocaleDateString());

    for (var i = $scope.relevantFirstDate.getDate(); i < $scope.relevantLastDate.getDate(); i++) {
      t.setDate(t.getDate() + 1);
      $scope.monthArray.push(t.toLocaleDateString());
    }
  }

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  Date: <input type='date' ng-model='selectedDate' ng-change='calcDate()' /> <br>
  <hr/>
  <p ng-repeat='x in monthArray'>{{x}}</p>
</div>


答:
It is normal that this.editedItemIndex is undefined in console.log("out of it :" + this.editedItemIndex);
The code above this part is asynchronous so when console.log("out of it :" + this.editedItemIndex); is run, the code inside the subscribe is not yet executed and this.editedItemIndex is not yet initialized.
Now the ngOnInit is the first method that is called in your component so in the other methods or in the template, this.editedItemIndex should be already initialized and not undefined. may be you can share your html code or the other places where it is undefined so the answer can be more precise.

Title: Changes made in .subscribe() method not reflected out of it or in the template


问:
Multiplying a pd.Series vector against a multindex pd.Dataframe
I have a pandas Series and a pandas multiindex Dataframe.

Here is a simplistic example of the situation:

```<code>iterables = [['milk', 'honey', 'dates'], ['jan', 'feb', 'mar', 'apr']]
i = pd.MultiIndex.from_product(iterables, names=['good', 'month'])
xf = pd.DataFrame(index = i)
xf['price'] = np.random.randint(1, 25, xf.shape[0])

allocation_vector = pd.Series([0.3, 0.6, 0.1], index = ['milk', 'honey', 'dates'])
</code>```

This dataframe represents 'price of three products in each month jan through apr'  The allocation_vector represents some fractional share of prices.

What I want to  achieve is  multiplying the allocation vector times my dataframe resulting in a series with index 'jan', 'feb', 'mar', 'apr' and the value equaling the dotproduct in that month (IE:  jan_date_price*date_pct + jan_milk_price*milk_pct + jan_honey_price*jan_pct for each of jan, feb, mar, apr)

I've only been able to solve this with nasty iterative hacky solutions. I figure there must be a much more pythonic way to do this, and where I don't have to worry about vector columns being in the wrong order for the multiplication against the dataframe columns etc.  Of course the actual dataframe has more columns that aren't involved in the calculation.

答:
You can achieve what you want using a combination of join and groupby as shown below:

```<code>allocation_vector.name = 'pct'
xf = xf.join(allocation_vector, on='good')
xf['dotproduct'] = xf.price * xf.pct

print(xf)
</code>```

The resulting dataframe is:

```<code>             price  pct  dotproduct
good  month
milk  jan       19  0.3         5.7
      feb        8  0.3         2.4
      mar        7  0.3         2.1
      apr       15  0.3         4.5
honey jan        9  0.6         5.4
      feb       10  0.6         6.0
      mar        7  0.6         4.2
      apr       11  0.6         6.6
dates jan        2  0.1         0.2
      feb       14  0.1         1.4
      mar       12  0.1         1.2
      apr        7  0.1         0.7
</code>```

And then you can get the result you need using:

```<code>print(xf.groupby('month')['dotproduct'].sum())
</code>```

The output is:

```<code>month
apr    11.8
feb     9.8
jan    11.3
mar     7.5
</code>```

Body:
I have a pandas Series and a pandas multiindex Dataframe.

Here is a simplistic example of the situation:

iterables = [['milk', 'honey', 'dates'], ['jan', 'feb', 'mar', 'apr']]
i = pd.MultiIndex.from_product(iterables, names=['good', 'month'])
xf = pd.DataFrame(index = i)
xf['price'] = np.random.randint(1, 25, xf.shape[0])

allocation_vector = pd.Series([0.3, 0.6, 0.1], index = ['milk', 'honey', 'dates'])

This dataframe represents 'price of three products in each month jan through apr'  The allocation_vector represents some fractional share of prices.

What I want to  achieve is  multiplying the allocation vector times my dataframe resulting in a series with index 'jan', 'feb', 'mar', 'apr' and the value equaling the dotproduct in that month (IE:  jan_date_price*date_pct + jan_milk_price*milk_pct + jan_honey_price*jan_pct for each of jan, feb, mar, apr)

I've only been able to solve this with nasty iterative hacky solutions. I figure there must be a much more pythonic way to do this, and where I don't have to worry about vector columns being in the wrong order for the multiplication against the dataframe columns etc.  Of course the actual dataframe has more columns that aren't involved in the calculation.

Body:
You can achieve what you want using a combination of join and groupby as shown below:

allocation_vector.name = 'pct'
xf = xf.join(allocation_vector, on='good')
xf['dotproduct'] = xf.price * xf.pct

print(xf)

The resulting dataframe is:

             price  pct  dotproduct
good  month
milk  jan       19  0.3         5.7
      feb        8  0.3         2.4
      mar        7  0.3         2.1
      apr       15  0.3         4.5
honey jan        9  0.6         5.4
      feb       10  0.6         6.0
      mar        7  0.6         4.2
      apr       11  0.6         6.6
dates jan        2  0.1         0.2
      feb       14  0.1         1.4
      mar       12  0.1         1.2
      apr        7  0.1         0.7

And then you can get the result you need using:

print(xf.groupby('month')['dotproduct'].sum())

The output is:

month
apr    11.8
feb     9.8
jan    11.3
mar     7.5


问:
How to run Selenium tests with CI (Continuous Integration)?
I'm using Selenium for automated testing my websites. I have around 100 test cases and I want to run them every day by making Test Suite automatically. I had written my test cases in Selenium 1 (Selenium RC) and now it is not very easy to migrate to selenium 2 (WebDriver). Is there any way or application out there that can load and execute the Selenium 1 scripts automatically?

Thanks very much for the help.

答:
You don't need to convert your tests to Selenium 2 to be able to run them.  Selenium 2 contains all the code for Selenium 1 and Selenium merged with webdriver.  Your existing scripts should run fine with the latest version of selenium.

From the questions above I am assuming that you have recorded your scripts in Selenium IDE and want to run them using Selenium Server, if so have a look at the following:

```<code>Run Selenese Directly Within the Server Using -htmlSuite

You can run Selenese html files directly within the Selenium Server by passing the html file to the server’s command line. For instance:

java -jar selenium-server.jar -htmlSuite "*firefox" "http://www.google.com" "c:\absolute\path\to\my\HTMLSuite.html" "c:\absolute\path\to\my\results.html"

This will automatically launch your HTML suite, run all the tests and save a nice HTML report with the results.

Note

When using this option, the server will start the tests and wait for a specified number of seconds for the test to complete; if the test doesn’t complete within that amount of time, the command will exit with a non-zero exit code and no results file will be generated.

This command line is very long so be careful when you type it. Note this requires you to pass in an HTML Selenese suite, not a single test. Also be aware the -htmlSuite option is incompatible with -interactive You cannot run both at the same time.
</code>```

The above is taken from http://seleniumhq.org/docs/05_selenium_rc.html

As others have said you can also set up cron jobs or scheduled tasks to automate the running of scripts at set times, although I would suggest investigating a CI server like Jenkins CI (formally Hudson) that can either run tests at a set time or be triggered to run tests based on code commits.

Body:
You don't need to convert your tests to Selenium 2 to be able to run them.  Selenium 2 contains all the code for Selenium 1 and Selenium merged with webdriver.  Your existing scripts should run fine with the latest version of selenium.

From the questions above I am assuming that you have recorded your scripts in Selenium IDE and want to run them using Selenium Server, if so have a look at the following:

Run Selenese Directly Within the Server Using -htmlSuite

You can run Selenese html files directly within the Selenium Server by passing the html file to the server’s command line. For instance:

java -jar selenium-server.jar -htmlSuite "*firefox" "http://www.google.com" "c:\absolute\path\to\my\HTMLSuite.html" "c:\absolute\path\to\my\results.html"

This will automatically launch your HTML suite, run all the tests and save a nice HTML report with the results.

Note

When using this option, the server will start the tests and wait for a specified number of seconds for the test to complete; if the test doesn’t complete within that amount of time, the command will exit with a non-zero exit code and no results file will be generated.

This command line is very long so be careful when you type it. Note this requires you to pass in an HTML Selenese suite, not a single test. Also be aware the -htmlSuite option is incompatible with -interactive You cannot run both at the same time.

The above is taken from http://seleniumhq.org/docs/05_selenium_rc.html

As others have said you can also set up cron jobs or scheduled tasks to automate the running of scripts at set times, although I would suggest investigating a CI server like Jenkins CI (formally Hudson) that can either run tests at a set time or be triggered to run tests based on code commits.


问:
Why am I getting "Unable to locate the server named localhost" error in Postman?
I get the following error:

```<code>    <B>
Description: Unable to locate the server named "
        <em>localhost</em>" --- the server does not have a DNS entry.  Perhaps there is a misspelling in the server name, or the server no longer exists.  Double-check the name and try again.
    </B>
</code>```

When I try to access the following url:

```<code>http://localhost:8812/
</code>```

I think it might have something to do with my proxy settings, but I am very new to these kind of things, so I am unsure

答: You could try accessing it via http://127.0.0.1:8812/ instead, seems like your local DNS resolver doesn't work properly.</p>

Body:
I get the following error:

Description: Unable to locate the server named "
        localhost" --- the server does not have a DNS entry.  Perhaps there is a misspelling in the server name, or the server no longer exists.  Double-check the name and try again.

When I try to access the following url:

http://localhost:8812/

I think it might have something to do with my proxy settings, but I am very new to these kind of things, so I am unsure


问:
Unable to add custom Sizer as parent to its children widgets in wxPython
I am currently trying to make a GUI in wxPython. The layout is a panel on the right side of the GUI with 3 StaticBoxSizers. One of them is much more complex than the others, with the ability to add more elements to it by clicking a button, so I decided to break up the GUI file and create a custom class for it to try and make the code a bit more clear.

The current initialiser of the class looks like this:

class MonitorBox(wx.StaticBoxSizer):
    def __init__(self, monitors, pins, devices, *args, **kw):
        super().__init__(*args, **kw)
        self.monitors = monitors
        self.pin_choices = pins
        self.dev_choices = devices
        self.InitUI()

    def InitUI(self):
        monList = wx.FlexGridSizer(cols=4, vgap=5, hgap=5)
        add_monitor = wx.Button(self, wx.ID_ANY, "Add Monitor")
        add_monitor.Bind(wx.EVT_BUTTON, self.on_add_button)

        # create list headings
        nametxt = wx.StaticText(self, wx.ID_ANY, "Name:")
        devtxt = wx.StaticText(self, wx.ID_ANY, "Device:")
        pintxt = wx.StaticText(self, wx.ID_ANY, "Pin:")
        blnktxt = wx.StaticText(self, wx.ID_ANY, "")

        # Add Headings to sizer
        monList.AddMany([nametxt, devtxt, pintxt, blnktxt])
        self.monitor_rows = {}  # dictionary to store references to all the widgets

        # Create a row for each item in the mons dictionary
        for monitor, dev in self.mons.items():
            del_mon_button = wx.Button(self, wx.ID_ANY, '-', name=monitor, style=wx.BU_EXACTFIT)
            del_mon_button.Bind(wx.EVT_BUTTON, self.on_del_monitor)
            mon_name = wx.TextCtrl(self, wx.ID_ANY, monitor,
                                   style=wx.TE_PROCESS_ENTER,
                                   name=monitor)
            dev_name = wx.ComboBox(self, wx.ID_ANY, choices=self.dev_choices,
                                   style=wx.CB_READONLY, value=dev[0],
                                   name=monitor)
            pin_name = wx.ComboBox(self, wx.ID_ANY, choices=self.pin_choices[dev[0]],
                                   style=wx.CB_READONLY, value=dev[1],
                                   name=monitor)

            dev_name.Bind(wx.EVT_COMBOBOX, self.on_dev_choice)
            pin_name.Bind(wx.EVT_COMBOBOX, self.on_pin_choice)
            self.monitor_rows[monitor] = [mon_name, dev_name, pin_name, del_mon_button]
            monList.AddMany(self.monitor_rows[monitor])
        # TODO: make sure all the combo boxes are the same size
        self.monList = monList
        self.Add(monList, 1, wx.ALL, 5)
        self.Add(add_monitor, 0, wx.ALL, 5)
```

<p>However when I try and run the GUI I get an error:</p>

```add_monitor = wx.Button(self, wx.ID_ANY, "Add Monitor")
TypeError: Button(): arguments did not match any overloaded call:
  overload 1: too many arguments
  overload 2: argument 1 has unexpected type 'MonitorBox'
```

I believe this is because I am trying to use my custom class as the parent for all the widgets inside it, but I am confused as to why this is happenning?

I am very new to creating GUIs (this is my first project) but I am currently in the process of going through and fixing all the references to parents etc. So it is hard for me to know the correct terms to search to see if others have had this issue.

My original code was just the InitUI(self) function called from the main wx.Frame of the GUI and creating monBox as a StaticBoxSizer which adds all the children widgets too directly. As mentioned at the start the reason I wanted to split this up is because there are a number of event handlers and additional diaglog boxes created by this panel that I wanted to keep in a seperate file to help keep the code readable.

The original code (not split up into a separate class) generates the Monitors panel that can be seen in the figure:

答:
The problem is that you are deriving your MonitorBox class from wx.StaticBoxSizer and a wx.Button can only be a child of a window (wx.Frame, wx.Panel, etc) not a sizer (wx.StaticBoxSizer).

If you want to separate the code then your MonitorBox class should come from wx.Panel. See the code (and its comments) below for a way to do this.

```<code>import wx

class MonitorBox(wx.Panel):
    """
    This is the class with all the widgets in your MonitorBox class.
    You need to arrange the widget in a sizer here.
    """
    def __init__(self, parent):
        super().__init__(parent=parent)

        #### Parent panel
        # No need to define a parent panel because the class itself is already a
        # panel. So self refers to a panel.

        #### Widgets
        # Here self is a panel not a sizer like in your question. So no problem
        # adding the button.
        self.add_monitor = wx.Button(self, wx.ID_ANY, "Add Monitor")
        #### Sizers
        self.sizer = wx.BoxSizer()
        #### Add widgets to sizer
        self.sizer.Add(self.add_monitor, flag=wx.CENTER)
        #### Add sizer to panel
        self.SetSizer(self.sizer)
        self.Fit()

class Main(wx.Frame):
    def __init__(self):
        super().__init__(None, title='Panel 3 comes from a different class',
                         size=(500, 500))
        #### Parent panel
        self.panel = wx.Panel(self)

        #### Some widgets
        ## The Static Box widget
        self.monitorsBox = wx.StaticBox(self.panel, label="Monitors")

        self.panelB = wx.Panel(self.panel, size=(200, 100))
        self.panelB.SetBackgroundColour((0, 0, 255))
        self.panelR = wx.Panel(self.panel, size=(200, 100))
        self.panelR.SetBackgroundColour((255, 0, 0))
        ## Add panel 3 as a child of the wx.StaticBox!!!
        self.panel3 = MonitorBox(self.monitorsBox)

        #### Sizers
        ## Main sizer
        self.sizer = wx.FlexGridSizer(3, 1, 5, 5)
        ## Sizers for the static box
        # The static box sizer
        self.monitorsBoxSizer = wx.StaticBoxSizer(self.monitorsBox, wx.VERTICAL)
        # Sizer for the content of the static box
        self.monitorsBoxSizerContent = wx.BoxSizer()

        #### Add widgets to sizers
        ## Static box content
        self.monitorsBoxSizerContent.Add(self.panel3, flag=wx.EXPAND)
        self.monitorsBoxSizer.Add(self.monitorsBoxSizerContent)
        ## Add everything to the main sizer
        self.sizer.Add(self.panelB, flag=wx.EXPAND|wx.ALL, border=10)
        self.sizer.Add(self.panelR, flag=wx.EXPAND|wx.ALL, border=10)
        self.sizer.Add(self.monitorsBoxSizer, flag=wx.EXPAND|wx.ALL, border=10)

        #### Add sizer to self.panel
        self.panel.SetSizer(self.sizer)
        self.panel.Fit()

if __name__ == '__main__':
    app = wx.App()
    frame = Main()
    frame.Show()
    app.MainLoop()
</code>```

Most probably in the original code the main class was derived from wx.Frame, right? If not, ignore the rest. That is why it worked. Because you were  making the button a child of a frame not a sizer.

Body:
I am currently trying to make a GUI in wxPython. The layout is a panel on the right side of the GUI with 3 StaticBoxSizers. One of them is much more complex than the others, with the ability to add more elements to it by clicking a button, so I decided to break up the GUI file and create a custom class for it to try and make the code a bit more clear.

The current initialiser of the class looks like this:

class MonitorBox(wx.StaticBoxSizer):
    def __init__(self, monitors, pins, devices, *args, **kw):
        super().__init__(*args, **kw)
        self.monitors = monitors
        self.pin_choices = pins
        self.dev_choices = devices
        self.InitUI()

    def InitUI(self):
        monList = wx.FlexGridSizer(cols=4, vgap=5, hgap=5)
        add_monitor = wx.Button(self, wx.ID_ANY, "Add Monitor")
        add_monitor.Bind(wx.EVT_BUTTON, self.on_add_button)

        # create list headings
        nametxt = wx.StaticText(self, wx.ID_ANY, "Name:")
        devtxt = wx.StaticText(self, wx.ID_ANY, "Device:")
        pintxt = wx.StaticText(self, wx.ID_ANY, "Pin:")
        blnktxt = wx.StaticText(self, wx.ID_ANY, "")

        # Add Headings to sizer
        monList.AddMany([nametxt, devtxt, pintxt, blnktxt])
        self.monitor_rows = {}  # dictionary to store references to all the widgets

        # Create a row for each item in the mons dictionary
        for monitor, dev in self.mons.items():
            del_mon_button = wx.Button(self, wx.ID_ANY, '-', name=monitor, style=wx.BU_EXACTFIT)
            del_mon_button.Bind(wx.EVT_BUTTON, self.on_del_monitor)
            mon_name = wx.TextCtrl(self, wx.ID_ANY, monitor,
                                   style=wx.TE_PROCESS_ENTER,
                                   name=monitor)
            dev_name = wx.ComboBox(self, wx.ID_ANY, choices=self.dev_choices,
                                   style=wx.CB_READONLY, value=dev[0],
                                   name=monitor)
            pin_name = wx.ComboBox(self, wx.ID_ANY, choices=self.pin_choices[dev[0]],
                                   style=wx.CB_READONLY, value=dev[1],
                                   name=monitor)

            dev_name.Bind(wx.EVT_COMBOBOX, self.on_dev_choice)
            pin_name.Bind(wx.EVT_COMBOBOX, self.on_pin_choice)
            self.monitor_rows[monitor] = [mon_name, dev_name, pin_name, del_mon_button]
            monList.AddMany(self.monitor_rows[monitor])
        # TODO: make sure all the combo boxes are the same size
        self.monList = monList
        self.Add(monList, 1, wx.ALL, 5)
        self.Add(add_monitor, 0, wx.ALL, 5)

However when I try and run the GUI I get an error:

add_monitor = wx.Button(self, wx.ID_ANY, "Add Monitor")
TypeError: Button(): arguments did not match any overloaded call:
  overload 1: too many arguments
  overload 2: argument 1 has unexpected type 'MonitorBox'

I believe this is because I am trying to use my custom class as the parent for all the widgets inside it, but I am confused as to why this is happenning?

I am very new to creating GUIs (this is my first project) but I am currently in the process of going through and fixing all the references to parents etc. So it is hard for me to know the correct terms to search to see if others have had this issue.

My original code was just the InitUI(self) function called from the main wx.Frame of the GUI and creating monBox as a StaticBoxSizer which adds all the children widgets too directly. As mentioned at the start the reason I wanted to split this up is because there are a number of event handlers and additional diaglog boxes created by this panel that I wanted to keep in a seperate file to help keep the code readable.

The original code (not split up into a separate class) generates the Monitors panel that can be seen in the figure:

Body:
The problem is that you are deriving your MonitorBox class from wx.StaticBoxSizer and a wx.Button can only be a child of a window (wx.Frame, wx.Panel, etc) not a sizer (wx.StaticBoxSizer).

If you want to separate the code then your MonitorBox class should come from wx.Panel. See the code (and its comments) below for a way to do this.

import wx

class MonitorBox(wx.Panel):
    """
    This is the class with all the widgets in your MonitorBox class.
    You need to arrange the widget in a sizer here.
    """
    def __init__(self, parent):
        super().__init__(parent=parent)

        #### Parent panel
        # No need to define a parent panel because the class itself is already a
        # panel. So self refers to a panel.

        #### Widgets
        # Here self is a panel not a sizer like in your question. So no problem
        # adding the button.
        self.add_monitor = wx.Button(self, wx.ID_ANY, "Add Monitor")
        #### Sizers
        self.sizer = wx.BoxSizer()
        #### Add widgets to sizer
        self.sizer.Add(self.add_monitor, flag=wx.CENTER)
        #### Add sizer to panel
        self.SetSizer(self.sizer)
        self.Fit()

class Main(wx.Frame):
    def __init__(self):
        super().__init__(None, title='Panel 3 comes from a different class',
                         size=(500, 500))
        #### Parent panel
        self.panel = wx.Panel(self)

        #### Some widgets
        ## The Static Box widget
        self.monitorsBox = wx.StaticBox(self.panel, label="Monitors")

        self.panelB = wx.Panel(self.panel, size=(200, 100))
        self.panelB.SetBackgroundColour((0, 0, 255))
        self.panelR = wx.Panel(self.panel, size=(200, 100))
        self.panelR.SetBackgroundColour((255, 0, 0))
        ## Add panel 3 as a child of the wx.StaticBox!!!
        self.panel3 = MonitorBox(self.monitorsBox)

        #### Sizers
        ## Main sizer
        self.sizer = wx.FlexGridSizer(3, 1, 5, 5)
        ## Sizers for the static box
        # The static box sizer
        self.monitorsBoxSizer = wx.StaticBoxSizer(self.monitorsBox, wx.VERTICAL)
        # Sizer for the content of the static box
        self.monitorsBoxSizerContent = wx.BoxSizer()

        #### Add widgets to sizers
        ## Static box content
        self.monitorsBoxSizerContent.Add(self.panel3, flag=wx.EXPAND)
        self.monitorsBoxSizer.Add(self.monitorsBoxSizerContent)
        ## Add everything to the main sizer
        self.sizer.Add(self.panelB, flag=wx.EXPAND|wx.ALL, border=10)
        self.sizer.Add(self.panelR, flag=wx.EXPAND|wx.ALL, border=10)
        self.sizer.Add(self.monitorsBoxSizer, flag=wx.EXPAND|wx.ALL, border=10)

        #### Add sizer to self.panel
        self.panel.SetSizer(self.sizer)
        self.panel.Fit()

if __name__ == '__main__':
    app = wx.App()
    frame = Main()
    frame.Show()
    app.MainLoop()

Most probably in the original code the main class was derived from wx.Frame, right? If not, ignore the rest. That is why it worked. Because you were  making the button a child of a frame not a sizer.


问:
Match Multiple Columns In Two Files - Output Only Those That Match Fully
File 1:

```<code>1075908|2178412|brown_eyeshorty@att.net|Claude|Desmangles
175908|2178412|naim.kazi@webtv.net|Naim|Kazi
175972|212946872418|gil_maynard@hotmail.com|Munster|Herman
175972|212946872418|meghanj4@lycos.com|Meghan|Judge
175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
176086|2480881|lourdsneil@gmail.com|Lourds|Herman
</code>```

File 2:

```<code>89129090|Sadiq|Islam
212946872418|Anna|Balint
255875|Charlene|Johnson
89234902|Bob|Brown
09123789|Fabio|Vanetti
</code>```

I would like to extract lines where ALL values match on the following basis:

Column 2 in File 1 matches with Column 1 in File 2.

Column 4 in File 1 matches with Column 2 in File 2.

Column 5 in File 1 matches with Column 3 in File 2.

The expected output for the example is:

```<code>175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
</code>```

The two inputs I'm working with are both very large (11Gb and 3Gb respectively).

The only potential (messy) workaround I can think of is to combine the values to be joined into a single additional column and then use Join (I'm very new to this).

答:
```<code>grep -f <(sed 's,|,|[^|]*|,' file2) file1
</code>```

Returns

```<code>175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
</code>```

Explanations :

First command :

```<code>sed 's,|,|[^|]*|,' file2
</code>```

Transforms file2 into a list of patterns to search in file 1 and returns :

```<code>89129090|[^|]*|Sadiq|Islam
212946872418|[^|]*|Anna|Balint
255875|[^|]*|Charlene|Johnson
89234902|[^|]*|Bob|Brown
09123789|[^|]*|Fabio|Vanetti
</code>```

Second command :

```<code>grep -f <(command1) file1
</code>```

Searchs patterns in file1

Body:
File 1:

1075908|2178412|brown_eyeshorty@att.net|Claude|Desmangles
175908|2178412|naim.kazi@webtv.net|Naim|Kazi
175972|212946872418|gil_maynard@hotmail.com|Munster|Herman
175972|212946872418|meghanj4@lycos.com|Meghan|Judge
175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
176086|2480881|lourdsneil@gmail.com|Lourds|Herman

File 2:

89129090|Sadiq|Islam
212946872418|Anna|Balint
255875|Charlene|Johnson
89234902|Bob|Brown
09123789|Fabio|Vanetti

I would like to extract lines where ALL values match on the following basis:

Column 2 in File 1 matches with Column 1 in File 2.

Column 4 in File 1 matches with Column 2 in File 2.

Column 5 in File 1 matches with Column 3 in File 2.

The expected output for the example is:

175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson

The two inputs I'm working with are both very large (11Gb and 3Gb respectively).

The only potential (messy) workaround I can think of is to combine the values to be joined into a single additional column and then use Join (I'm very new to this).

Body:
grep -f <(sed 's,|,|[^|]*|,' file2) file1

Returns

175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson

Explanations :

First command :

sed 's,|,|[^|]*|,' file2

Transforms file2 into a list of patterns to search in file 1 and returns :

89129090|[^|]*|Sadiq|Islam
212946872418|[^|]*|Anna|Balint
255875|[^|]*|Charlene|Johnson
89234902|[^|]*|Bob|Brown
09123789|[^|]*|Fabio|Vanetti

Second command :

grep -f <(command1) file1

Searchs patterns in file1


问:
How to count not-empty rows of each column in one datagridview and show numbers of rows in the second datagridview?
I have 2 datagridviews:

1 - Shows data from database.

2 - Has to show number of not-empty rows of each column in the first datagridview.

I tried this code, but it count every row:

```<code>     var count = dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !(row.Cells[0].Value == null || row.Cells[0].Value == DBNull.Value)).Count();
</code>```

The second datagridview has to show distinct not-empty rows.

Please help to solve this problem.

Thank you for helping.

答:
Try following :

```<code>            var count = Enumerable.Range(0, dataGridView1.Columns.Count)
                .Select(x => new { column = x, count = dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !(row.Cells[x].Value == null || row.Cells[x].Value == DBNull.Value)).Count() })
                .ToList();
</code>```

Using a datatable

```<code>            var count1 = Enumerable.Range(0, dt.Columns.Count)
                .Select(x => new { column = x, count = dt.AsEnumerable().Where(row => row[x] != DBNull.Value).Count() })
                .ToList();
</code>```

Creating a datatable with results

```<code>            var count1 = Enumerable.Range(0, dt.Columns.Count)
                .Select(x => new { column = x, count = dt.AsEnumerable().Where(row => row[x] != DBNull.Value).Count() })
                .ToList();

            DataTable dt2 = new DataTable();
            dt2.Columns.Add("Column Name", typeof(string));
            dt2.Columns.Add("Count", typeof(int));

            foreach (var count in count1)
            {
                dt2.Rows.Add(new object[] { dt.Columns[count.column].ColumnName, count.count });
            }
</code>```

Body:
I have 2 datagridviews:

1 - Shows data from database.

2 - Has to show number of not-empty rows of each column in the first datagridview.

I tried this code, but it count every row:

     var count = dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !(row.Cells[0].Value == null || row.Cells[0].Value == DBNull.Value)).Count();

The second datagridview has to show distinct not-empty rows.

Please help to solve this problem.

Thank you for helping.

Body:
Try following :

            var count = Enumerable.Range(0, dataGridView1.Columns.Count)
                .Select(x => new { column = x, count = dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !(row.Cells[x].Value == null || row.Cells[x].Value == DBNull.Value)).Count() })
                .ToList();

Using a datatable

            var count1 = Enumerable.Range(0, dt.Columns.Count)
                .Select(x => new { column = x, count = dt.AsEnumerable().Where(row => row[x] != DBNull.Value).Count() })
                .ToList();

Creating a datatable with results

            var count1 = Enumerable.Range(0, dt.Columns.Count)
                .Select(x => new { column = x, count = dt.AsEnumerable().Where(row => row[x] != DBNull.Value).Count() })
                .ToList();

            DataTable dt2 = new DataTable();
            dt2.Columns.Add("Column Name", typeof(string));
            dt2.Columns.Add("Count", typeof(int));

            foreach (var count in count1)
            {
                dt2.Rows.Add(new object[] { dt.Columns[count.column].ColumnName, count.count });
            }


问:
changing a key name in NSDictionary
I have a method which returns me a nsdictionary with certain keys and values. i need to change the key names from the dictionary to a new key name but the values need to be same for that key,but i am stuck here.need help</p>

答:
Could you not add a new key-value pair using the old value, and then remove the old key-value pair?

This would only work on an NSMutableDictionary.  NSDictionarys are not designed to be changed once they have been created.

Title: changing a key name in NSDictionary


答:
Using CROSS APPLY this exected output is possible:

```<code>SELECT T1.company, T2.Product
FROM Table1 T1
CROSS APPLY Table2  T2
ORDER BY T1.company, T2.Product
</code>```

Demo on db<>fiddle

Demo with sample data:

```<code>DECLARE @Table1 TABLE (company VARCHAR (1), adress VARCHAR (10));

INSERT INTO @Table1 (company, adress) VALUES
('A', 'AdressX'),
('B', 'AdressY'),
('C', 'AdressZ');

DECLARE @Table2 TABLE (Product VARCHAR (2),   Price INT);

INSERT INTO @Table2 (Product, Price) VALUES
('P1', 50),
('P2', 60);

SELECT T1.company, T2.Product
FROM @Table1 T1
CROSS APPLY @Table2  T2
ORDER BY T1.company, T2.Product
</code>```

Output:

```<code>company Product
---------------
A       P1
A       P2
B       P1
B       P2
C       P1
C       P2
</code>```

Title: How to select from table one with all records from table 2

Body:
Using CROSS APPLY this exected output is possible:

SELECT T1.company, T2.Product
FROM Table1 T1
CROSS APPLY Table2  T2
ORDER BY T1.company, T2.Product

Demo on db<>fiddle

Demo with sample data:

DECLARE @Table1 TABLE (company VARCHAR (1), adress VARCHAR (10));

INSERT INTO @Table1 (company, adress) VALUES
('A', 'AdressX'),
('B', 'AdressY'),
('C', 'AdressZ');

DECLARE @Table2 TABLE (Product VARCHAR (2),   Price INT);

INSERT INTO @Table2 (Product, Price) VALUES
('P1', 50),
('P2', 60);

SELECT T1.company, T2.Product
FROM @Table1 T1
CROSS APPLY @Table2  T2
ORDER BY T1.company, T2.Product

Output:

company Product
---------------
A       P1
A       P2
B       P1
B       P2
C       P1
C       P2


问:
Pycharm not running Anaconda environment
I´m using an Anaconda environment with Pandas, Tensorflow, Keras and Matplotlib.

When I run a code in the Anaconda Prompt it works preftly, but when I try to run it in Pycharm I get an error message saying it can´t find the dependencies.

The error message

```<code> File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Lia love/TestAi/Test1.py", line 1, in <module>
    import pandas as pd
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.3\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 20, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "D:\Anaconda\envs\scikit_env\lib\site-packages\pandas\__init__.py", line 19, in <module>
    "Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']
</code>```

I selected the same environmet as the project interpreter in Pycharm. I see the required packages in the list.

I don´t understand what I´m missing here.

Project´s interpreter packages

```<code>Keras   2.2.4   2.2.4
Keras-Applications  1.0.7   1.0.7
Keras-Preprocessing 1.0.9   1.0.9
Markdown    3.1 3.1.1
PyYAML  5.1 5.1
Werkzeug    0.15.2  0.15.4
absl-py 0.7.1   0.7.1
astor   0.7.1   0.8.0
certifi 2019.3.9    2019.3.9
cycler  0.10.0  0.10.0
gast    0.2.2   0.2.2
grpcio  1.16.1  1.21.1
h5py    2.9.0   2.9.0
joblib  0.13.2  0.13.2
kiwisolver  1.1.0   1.1.0
matplotlib  3.0.3   3.1.0
mkl-fft 1.0.12  1.0.6
mkl-random  1.0.2   1.0.1.1
mock    2.0.0   3.0.5
numpy   1.16.3  1.16.3
pandas  0.24.2  0.24.2
pbr 5.1.3   5.2.0
pip 19.1.1  19.1.1
protobuf    3.7.1   3.7.1
pyparsing   2.4.0   2.4.0
pyreadline  2.1 2.1
python-dateutil 2.8.0   2.8.0
pytz    2019.1  2019.1
scikit-learn    0.21.1  0.21.2
scipy   1.2.1   1.3.0
setuptools  41.0.1  41.0.1
six 1.12.0  1.12.0
tensorboard 1.13.1  1.13.1
tensorflow  1.13.1  1.13.1
tensorflow-estimator    1.13.0  1.13.0
termcolor   1.1.0   1.1.0
tornado 6.0.2   6.0.2
wheel   0.33.4  0.33.4
wincertstore    0.2 0.2
</code>```

Thanks!

答: Try installing the latest 2019.1.3 RC build. It contains a bunch of relevant fixes for Anaconda support in PyCharm (e.g. https://youtrack.jetbrains.com/issue/PY-35141). The problem with "Missing required dependencies" should be addressed there as well.</p>

Body:
I´m using an Anaconda environment with Pandas, Tensorflow, Keras and Matplotlib.

When I run a code in the Anaconda Prompt it works preftly, but when I try to run it in Pycharm I get an error message saying it can´t find the dependencies.

The error message

 File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Lia love/TestAi/Test1.py", line 1, in <module>
    import pandas as pd
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.3\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 20, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "D:\Anaconda\envs\scikit_env\lib\site-packages\pandas\__init__.py", line 19, in <module>
    "Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']

I selected the same environmet as the project interpreter in Pycharm. I see the required packages in the list.

I don´t understand what I´m missing here.

Project´s interpreter packages

Keras   2.2.4   2.2.4
Keras-Applications  1.0.7   1.0.7
Keras-Preprocessing 1.0.9   1.0.9
Markdown    3.1 3.1.1
PyYAML  5.1 5.1
Werkzeug    0.15.2  0.15.4
absl-py 0.7.1   0.7.1
astor   0.7.1   0.8.0
certifi 2019.3.9    2019.3.9
cycler  0.10.0  0.10.0
gast    0.2.2   0.2.2
grpcio  1.16.1  1.21.1
h5py    2.9.0   2.9.0
joblib  0.13.2  0.13.2
kiwisolver  1.1.0   1.1.0
matplotlib  3.0.3   3.1.0
mkl-fft 1.0.12  1.0.6
mkl-random  1.0.2   1.0.1.1
mock    2.0.0   3.0.5
numpy   1.16.3  1.16.3
pandas  0.24.2  0.24.2
pbr 5.1.3   5.2.0
pip 19.1.1  19.1.1
protobuf    3.7.1   3.7.1
pyparsing   2.4.0   2.4.0
pyreadline  2.1 2.1
python-dateutil 2.8.0   2.8.0
pytz    2019.1  2019.1
scikit-learn    0.21.1  0.21.2
scipy   1.2.1   1.3.0
setuptools  41.0.1  41.0.1
six 1.12.0  1.12.0
tensorboard 1.13.1  1.13.1
tensorflow  1.13.1  1.13.1
tensorflow-estimator    1.13.0  1.13.0
termcolor   1.1.0   1.1.0
tornado 6.0.2   6.0.2
wheel   0.33.4  0.33.4
wincertstore    0.2 0.2

Thanks!


问:
Need to speed up very slow loop for image manipulation on Python
I am currently completing a program in Pyhton (3.6) as per internal requirement. As part of it, I am having to loop through a colour image (3 bytes per pixel, R, G & B) and distort the image  pixel by pixel.

I have the same code in other languages (C++, C#), and non-optimized code executes in about two seconds, while optimized code executes in less than a second. By non-optimized code I mean that the matrix multiplication is performed by a 10 line function I implemented. The optimized version just uses external libraries for multiplication.

In Python, this code takes close to 300 seconds. I can´t think of a way to vectorize this logic or speed it up, as there are a couple of "if"s inside the nested loop. Any help would be greatly appreciated.

import numpy as np

#for test purposes:
#roi = rect.rect(0, 0, 1200, 1200)
#input = DCImage.DCImage(1200, 1200, 3)
#correctionImage = DCImage.DCImage(1200,1200,3)
#siteToImage= np.zeros((3,3), np.float32)
#worldToSite= np.zeros ((4, 4))
#r11 = r12 = r13 = r21 = r22 = r23 = r31 = r32 = r33 = 0.0
#xMean = yMean = zMean = 0
#tx = ty = tz = 0
#epsilon = np.finfo(float).eps
#fx = fy = cx = cy = k1 = k2 = p1 = p2 = 0

for i in range (roi.x, roi.x + roi.width):
    for j in range (roi.y , roi.y + roi.height):
        if ( (input.pixels [i] [j] == [255, 0, 0]).all()):
            #Coordinates conversion
            siteMat = np.matmul(siteToImage, [i, j, 1])
            world =np.matmul(worldToSite, [siteMat[0], siteMat[1], 0.0, 1.0])

            xLocal = world[0] - xMean
            yLocal = world[1] - yMean
            zLocal = z_ortho - zMean
            #From World to camera
            xCam = r11*xLocal + r12*yLocal + r13*zLocal + tx
            yCam = r21*xLocal + r22*yLocal + r23*zLocal + ty
            zCam = r31*xLocal + r32*yLocal + r33*zLocal + tz
            if (zCam > epsilon or zCam < -epsilon):
                xCam = xCam / zCam
                yCam = yCam / zCam

            #// DISTORTIONS
            r2 = xCam*xCam + yCam*yCam
            a1 = 2*xCam*yCam
            a2 = r2 + 2*xCam*xCam
            a3 = r2 + 2*yCam*yCam
            cdist = 1 + k1*r2 + k2*r2*r2
            u = int((xCam * cdist + p1 * a1 + p2 * a2) * fx + cx + 0.5)
            v = int((yCam * cdist + p1 * a3 + p2 * a1) * fy + cy + 0.5)

            if (u>=0 and u<correctionImage.width and v>=0 and v < correctionImage.height):
                input.pixels [i] [j] =  correctionImage.pixels [u][v]
```

答:
After much testing, the only way to speed the function without writing it in C++ was dissassembling it and vectorizing it. The way to do it in this particular instance is to create an array with the valid indexes at the beginning of the funcion and use them as tuples to index the final solution.

subArray[roi.y:roi.y+roi.height,roi.x:roi.x+roi.width,] = input.pixels[roi.y:roi.y+roi.height,roi.x:roi.x+roi.width,]

#Calculate valid XY indexes
y_index, x_index = np.where(np.all(subArray== np.array([255,0,0]), axis=-1))

#....
#do stuff
#....

#Join result values with XY indexes
ij_xy = np.column_stack((i, j, y_index, x_index))

#Only keep valid ij values
valids_ij_xy = ij_xy [(ij_xy [:,0] >= 0) & (ij_xy [:,0] < correctionImage.height) & (ij_xy [:,1] >= 0) & (ij_xy [:,1] < correctionImage.width)]

#Assign values
input.pixels [tuple(np.array(valids_ij_xy [:,2:]).T)] = correctionImage.pixels[tuple(np.array(valids_ij_xy [:,:2]).T)]
```


问:
Site layout splitted into rows and columns - alignment problem
I would like to create a layout that will split my page into rows and modules.

Row is just a whole width flex div that contains other elements which I call modules, like in the picture below:

As you can also see, when I have one column, content is centered - but it's not the rule. But I want to be able to center the content (it may be anything).

When I have two columns, the left one should be right-aligned and the right one should be left aligned. With some margin "in the center".

The problem is that, when I was playing with css sandbox, it looks like I got what I wanted. But, when I move it to my project, it doesn't work. Mainly the left column is not right aligned as it should be. What's wrong?

Oh, of course everything should be responsive :)

:root {
--default-padding: 20px;
--default-margin: 20px;
--double-margin: calc(var(--default-margin) * 2);
--double-padding: calc(var(--default-padding) * 2);
}

.row {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: top;
    width: 100%
  }

.row > div {
   flex-grow: 1;
   width: 0px;
   min-width: 200px; /* it makes flex responsive */
}

.row > div:first-child > * {
   margin-left: auto;
   margin-right: var(--default-margin);
   text-align: right;
}

.row > div:last-child > * {
   margin-left: var(--default-margin);
}

img {
    max-width: 100%;
    height: auto; /* responsive image */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
    <div>
        <h1 style="text-align: center">Centered content</h1>
    </div>
</div>

<div class="row">
    <div>
        <img src="img.jpg" id="main_img"/>
    </div>

    <div>
      <p>
        <h1>Some header</h1>
        <ul>
          <li>list item</li>
          <li>list item</li>
        </ul>
      </p>
      <button class="cta module-right">ZAMÓW TERAZ</button>
    </div>
</div></code>```

So, what's wrong with this code? (these are my beginnings in css, I am mostly desktop and backend programmer)

答:
The best way to achieve this is by display: flex;. If you are not familiar with it I would recommend you to learn about it from here https://css-tricks.com/snippets/css/a-guide-to-flexbox/ since it would make it a lot easier for you. I have done a sample code of what you want to achieve using flex. Hope this helps

HTML

```<code><div class="d-flex flex-row justify-content-center">
  <h1>Centered content</h1>
</div>

<div class="d-flex flex-row justify-content-center">

  <div class="img-box">
    <img src="https://via.placeholder.com/150" />
  </div>

  <div class="flex-column">
    <div>
      <h1 class="no-margin">Some header</h1>
      <ul>
        <li>list item</li>
        <li>list item</li>
      </ul>
    </div>
    <div>
      <button>ZAMÓW TERAZ</button>
    </div>
  </div>

</div>
</code>```

CSS

```<code>.d-flex {
  display: flex;
}

.flex-row {
  flex-direction: row;
}

.flex-column {
  flex-direction: column;
}

.justify-content-center {
  justify-content: center;
}

.img-box {
  margin-right: 1rem;
}

.no-margin {
  margin: 0;
}
</code>```

JS Fiddle Link : https://jsfiddle.net/SJ_KIllshot/gh6d5uzy/1/

Body:
I would like to create a layout that will split my page into rows and modules.

Row is just a whole width flex div that contains other elements which I call modules, like in the picture below:

As you can also see, when I have one column, content is centered - but it's not the rule. But I want to be able to center the content (it may be anything).

When I have two columns, the left one should be right-aligned and the right one should be left aligned. With some margin "in the center".

The problem is that, when I was playing with css sandbox, it looks like I got what I wanted. But, when I move it to my project, it doesn't work. Mainly the left column is not right aligned as it should be. What's wrong?

Oh, of course everything should be responsive :)

:root {
--default-padding: 20px;
--default-margin: 20px;
--double-margin: calc(var(--default-margin) * 2);
--double-padding: calc(var(--default-padding) * 2);
}

.row {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: top;
    width: 100%
  }

.row > div {
   flex-grow: 1;
   width: 0px;
   min-width: 200px; /* it makes flex responsive */
}

.row > div:first-child > * {
   margin-left: auto;
   margin-right: var(--default-margin);
   text-align: right;
}

.row > div:last-child > * {
   margin-left: var(--default-margin);
}

img {
    max-width: 100%;
    height: auto; /* responsive image */
}

Centered content

Some header

list item

list item

      <button class="cta module-right">ZAMÓW TERAZ</button>

So, what's wrong with this code? (these are my beginnings in css, I am mostly desktop and backend programmer)

Body:
The best way to achieve this is by display: flex;. If you are not familiar with it I would recommend you to learn about it from here https://css-tricks.com/snippets/css/a-guide-to-flexbox/ since it would make it a lot easier for you. I have done a sample code of what you want to achieve using flex. Hope this helps

HTML

<div class="d-flex flex-row justify-content-center">
  <h1>Centered content</h1>
</div>

<div class="d-flex flex-row justify-content-center">

  <div class="img-box">
    <img src="https://via.placeholder.com/150" />
  </div>

  <div class="flex-column">
    <div>
      <h1 class="no-margin">Some header</h1>
      <ul>
        <li>list item</li>
        <li>list item</li>
      </ul>
    </div>
    <div>
      <button>ZAMÓW TERAZ</button>
    </div>
  </div>

</div>

CSS

.d-flex {
  display: flex;
}

.flex-row {
  flex-direction: row;
}

.flex-column {
  flex-direction: column;
}

.justify-content-center {
  justify-content: center;
}

.img-box {
  margin-right: 1rem;
}

.no-margin {
  margin: 0;
}

JS Fiddle Link : https://jsfiddle.net/SJ_KIllshot/gh6d5uzy/1/


问:
Linter for json schema directory
My team build an API where for all the inputs and outputs use JSON Schema to validate the data, the project is growing and yesterday I detect that we already have 85 JSON files and on each file a JSON schema to validate something, I also detect that I have so many refactors to do on each file, for example, a lot of duplicate code that should be extracted and put it as a single schema and reference this schema on each file. So I tried to google it a library to scan this directory and help me to detect this kind of errors and also a JSON schema linter that helps me to detect other errors, but I couldn't find anything. So I'm posting this question to know if someone is having the same problem and found some tool that resolves it.</p>

答: There is a JSON schema linter available at https://www.json-schema-linter.com/ which also has a WebAPI. It catches some common errors in JSON schema files.

Title: Linter for json schema directory