问:
How to open new activity by clicking on SearchView
I created an Android project in which I use search view. I want to open a new activity by clicking the SearchView. When I click icon of SearchView it work perfectly, but when I click in the empty space of the SearchView the keyboard pops up and the new activity is not opening up.

My java code:

```<code>searchView=root.findViewById(R.id.search);
searchView.setIconifiedByDefault(true);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent searchIntent=new Intent(getActivity(),Notification_activity.class);
        getActivity().startActivity(searchIntent);
    }
});
</code>```

My XML:

```<code><SearchView
    android:id="@+id/search"
    android:layout_width="333dp"
    android:layout_height="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/search_round_corner"
    android:iconifiedByDefault="false"
    android:queryHint="Enter text to search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</SearchView>
</code>```

答:
you should use the query listener for this purpose because after type single word then it will goes to the second activity when you submit the button from keyboard and perform search view functionality. here is the code </p>

```<code> searchView.OnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            String text = s;
            if (text.length() > 0) {
                startActivity(new Intent(Class A Context, Sceond Class B));
            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            return false;
        }
    });
</code>```

Body:
I created an Android project in which I use search view. I want to open a new activity by clicking the SearchView. When I click icon of SearchView it work perfectly, but when I click in the empty space of the SearchView the keyboard pops up and the new activity is not opening up.

My java code:

searchView=root.findViewById(R.id.search);
searchView.setIconifiedByDefault(true);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent searchIntent=new Intent(getActivity(),Notification_activity.class);
        getActivity().startActivity(searchIntent);
    }
});

My XML:

<SearchView
    android:id="@+id/search"
    android:layout_width="333dp"
    android:layout_height="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/search_round_corner"
    android:iconifiedByDefault="false"
    android:queryHint="Enter text to search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</SearchView>

Body:
you should use the query listener for this purpose because after type single word then it will goes to the second activity when you submit the button from keyboard and perform search view functionality. here is the code

 searchView.OnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            String text = s;
            if (text.length() > 0) {
                startActivity(new Intent(Class A Context, Sceond Class B));
            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            return false;
        }
    });


来源: stackexchange

问:
Cakephp 3.x Table Beforefind, unable to stop event
Per the documentation on the website of CakePHP: (https://book.cakephp.org/3/en/orm/table-objects.html#beforefind) stopping the event or supplying a return value should stop the find operation.

I'm using the following code in the Beforefind:

```<code>$event->stopPropagation();
return false;
</code>```

But this doesn't seem to have any effect.

答:
The docs need some fixing there, as there's various things wrong with it, returning data won't make any difference, as the return value is never used, also you can't really use the beforeFind event for configuring caching, it's limited to the point of it not being useful, as the event is only being triggered for non-cached queries, and for those it's triggered after the cache is being checked.

That being said, stopping the find operation is possible by providing custom results, not by returning data, but by setting it via Query::setResult(), which expects an instance of \Cake\Datasource\ResultSetInterface.

An example would be:

```<code>$results = [];
$resultSet = new \Cake\Datasource\ResultSetDecorator($results);
$query->setResult($results);
$event->stopPropagation();
</code>```

That would make the query return an empty result set (ResultSetDecorator is just a collection that implements ResultSetInterface), which is the closest you can come to "stopping" the query.

ContentLicense: CC BY-SA 4.0

Body:
Per the documentation on the website of CakePHP: (https://book.cakephp.org/3/en/orm/table-objects.html#beforefind) stopping the event or supplying a return value should stop the find operation.

I'm using the following code in the Beforefind:

$event->stopPropagation();
return false;

But this doesn't seem to have any effect.

Body:
The docs need some fixing there, as there's various things wrong with it, returning data won't make any difference, as the return value is never used, also you can't really use the beforeFind event for configuring caching, it's limited to the point of it not being useful, as the event is only being triggered for non-cached queries, and for those it's triggered after the cache is being checked.

That being said, stopping the find operation is possible by providing custom results, not by returning data, but by setting it via Query::setResult(), which expects an instance of \Cake\Datasource\ResultSetInterface.

An example would be:

$results = [];
$resultSet = new \Cake\Datasource\ResultSetDecorator($results);
$query->setResult($results);
$event->stopPropagation();

That would make the query return an empty result set (ResultSetDecorator is just a collection that implements ResultSetInterface), which is the closest you can come to "stopping" the query.


问:
Send redirect url with @ResponseStatus(value = HttpStatus.MOVED_PERMANENTLY)
I am using an exception class for @ResponseStatus , but I am not able to figure out how do I send redirect URL in case of 301 Permanently Moved error ?

Exception class:

```<code>@ResponseStatus(value = HttpStatus.MOVED_PERMANENTLY)
public class ResourceMovedPermanentlyException extends RuntimeException{

}
</code>```

答:
The question is not very clear. I suppose you want to redirect to a page in case of ResourceMovedPermanentlyException being thrown. In that case you could use the ExceptionHandler annotation:

```<code>@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final Exception e) {
    return "redirect:/the/target/page";
}
</code>```

Alternative implementation:

```<code>@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final RuntimeException e,
                  final HttpServletRequest request, // this can be omitted if not needed
                  final HttpServletResponse response) throws IOException
    response.sendRedirect("/the/page/or/url/you/need/to/redirect");
}
</code>```

You also could store the redirect URL into the exception:

```<code>@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final ResourceMovedPermanentlyException e,
                  final HttpServletResponse response) throws IOException
    response.sendRedirect(e.getRedirectUrl());
}
</code>```

See the ExceptionHandler JavaDoc for more details about the options available for the exception handler method.

ContentLicense: CC BY-SA 3.0

Body:
I am using an exception class for @ResponseStatus , but I am not able to figure out how do I send redirect URL in case of 301 Permanently Moved error ?

Exception class:

@ResponseStatus(value = HttpStatus.MOVED_PERMANENTLY)
public class ResourceMovedPermanentlyException extends RuntimeException{

}

Body:
The question is not very clear. I suppose you want to redirect to a page in case of ResourceMovedPermanentlyException being thrown. In that case you could use the ExceptionHandler annotation:

@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final Exception e) {
    return "redirect:/the/target/page";
}

Alternative implementation:

@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final RuntimeException e,
                  final HttpServletRequest request, // this can be omitted if not needed
                  final HttpServletResponse response) throws IOException
    response.sendRedirect("/the/page/or/url/you/need/to/redirect");
}

You also could store the redirect URL into the exception:

@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final ResourceMovedPermanentlyException e,
                  final HttpServletResponse response) throws IOException
    response.sendRedirect(e.getRedirectUrl());
}

See the ExceptionHandler JavaDoc for more details about the options available for the exception handler method.


问:
using qTip inside asp.net listview itemtemplate
I am trying to use qTip inside an ASP.NET ListView. The page uses a MasterPage. There is an Image in each Item which will show a DataBound value when hovered.

Below is my ItemTemplate code:

```<code><ItemTemplate>

    <p>
        <%# Eval("Name")%>

        <asp:Image ID="imgInfo" runat="server"
                   align="right"
                   ImageUrl="~/App_Themes/Default/images/question.png" />
    </p>

    <asp:TextBox ID="txtValue" runat="server"
                 TextMode="MultiLine"
                 Rows="4"
                 SkinID="dummy"
                 Text='<%# Bind("Value") %>' />

    <asp:Label ID="lblHelpText" runat="server"
               Text='<%# Eval("HelpText")%>'
               Visible="false" />

    <script language="javascript" type="text/javascript">

        $('[#ContentPlaceHolder1_lvStep1_imgInfo_0]').qtip({

            content: 'the tooltip text, I want text of lblHelpText here',
            style: { name: 'blue' }

        });

    </script>

</ItemTemplate>
</code>```

My Questions:

This way the Id has been hard
coded, so works just on one item. I
could not find a selector that would
select the Ids for me.

I need the lblHelpText.Text or
<%# Eval("HelpText")%> as the
tooltip text (content : )

Since the script is within the
ItemTemplate, it would be created as
many times the number of items. Is
there a way I can achieve all this
by having script at one place
(outside ItemTemplate)?

Your help will be most appreciated,

Ali

答:
You could simply assign a class to your images and then bind the help text into the title attribute of the image.

ItemTemplate:

```<code><asp:Image ID="imgInfo" runat="server"
    CssClass="listViewImage" align="right"
    ImageUrl="~/App_Themes/Default/images/question.png" />
</code>```

Binding:

```<code>((Image)MyListView.Controls.Find("imgInfo")).Title = HelpText;
</code>```

You could also do this in your markup if you prefer if you're not binding via code:

```<code><asp:Image ID="imgInfo" runat="server"
    CssClass="listViewImage" align="right"
    Title='<%# Eval("HelpText")%>'
    ImageUrl="~/App_Themes/Default/images/question.png" />
</code>```

qTip Init (qTip uses title tag if present as content by default):

```<code>$('img.listViewImage').qtip({
    style: {
        name: 'blue'
    }
});
</code>```

If you don't want to use the title tag, you could use the "alt" or "rel" attribute, which would be performed the same way.  Alternatively, you could contain the text in a hidden element.  That'd be a bit more complex and might be done something like this:

ItemTemplate:

```<code><span class="listViewImage">
    <asp:Image ID="imgInfo" runat="server"
        align="right"
        ImageUrl="~/App_Themes/Default/images/question.png" />
    <span class="helpText" style="display: none;"><%# Eval("HelpText")%></span>
</span>
</code>```

qTip Init (qTip uses title tag if present as content by default):

```<code>$('span.listViewImage img').each(function() {
    $(this).qtip({
        content: $(this).find('span.helpText').html(),
        style: {
            name: 'blue'
        }
    });
});
</code>```

Edit:

Forgot to mention, with these solutions, you'd move the javascript outside of your item template.

Body:
I am trying to use qTip inside an ASP.NET ListView. The page uses a MasterPage. There is an Image in each Item which will show a DataBound value when hovered.

Below is my ItemTemplate code:

<ItemTemplate>

        <%# Eval("Name")%>

        <asp:Image ID="imgInfo" runat="server"
                   align="right"
                   ImageUrl="~/App_Themes/Default/images/question.png" />

    <asp:TextBox ID="txtValue" runat="server"
                 TextMode="MultiLine"
                 Rows="4"
                 SkinID="dummy"
                 Text='<%# Bind("Value") %>' />

    <asp:Label ID="lblHelpText" runat="server"
               Text='<%# Eval("HelpText")%>'
               Visible="false" />

</ItemTemplate>

My Questions:

This way the Id has been hard
coded, so works just on one item. I
could not find a selector that would
select the Ids for me.

I need the lblHelpText.Text or
<%# Eval("HelpText")%> as the
tooltip text (content : )

Since the script is within the
ItemTemplate, it would be created as
many times the number of items. Is
there a way I can achieve all this
by having script at one place
(outside ItemTemplate)?

Your help will be most appreciated,

Ali

Body:
You could simply assign a class to your images and then bind the help text into the title attribute of the image.

ItemTemplate:

<asp:Image ID="imgInfo" runat="server"
    CssClass="listViewImage" align="right"
    ImageUrl="~/App_Themes/Default/images/question.png" />

Binding:

((Image)MyListView.Controls.Find("imgInfo")).Title = HelpText;

You could also do this in your markup if you prefer if you're not binding via code:

<asp:Image ID="imgInfo" runat="server"
    CssClass="listViewImage" align="right"
    Title='<%# Eval("HelpText")%>'
    ImageUrl="~/App_Themes/Default/images/question.png" />

qTip Init (qTip uses title tag if present as content by default):

$('img.listViewImage').qtip({
    style: {
        name: 'blue'
    }
});

If you don't want to use the title tag, you could use the "alt" or "rel" attribute, which would be performed the same way.  Alternatively, you could contain the text in a hidden element.  That'd be a bit more complex and might be done something like this:

ItemTemplate:

<span class="listViewImage">
    <asp:Image ID="imgInfo" runat="server"
        align="right"
        ImageUrl="~/App_Themes/Default/images/question.png" />
    <span class="helpText" style="display: none;"><%# Eval("HelpText")%></span>
</span>

qTip Init (qTip uses title tag if present as content by default):

$('span.listViewImage img').each(function() {
    $(this).qtip({
        content: $(this).find('span.helpText').html(),
        style: {
            name: 'blue'
        }
    });
});

Edit:

Forgot to mention, with these solutions, you'd move the javascript outside of your item template.


问:
How to stop single node kubernetes cluster gracefully
I've set up single node kubernetes  according to [official tutorial][1].

In addition to official documentation I've set-up single node cluster:

```<code>kubectl taint nodes --all node-role.kubernetes.io/master-
</code>```

Disabled eviction limit:

```<code>cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet
</code>```

And set systemd driver for Docker:

```<code>cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker
</code>```

How can I temporary stop Kubernetes cluster (including all it's services, podd, etc)? I've issued systemctl stop kubelet but I stil see some kubernetes stuff among processes

```<code>$ ps -elf | grep kube
4 S root       6032   5914  1  80   0 - 2653148 -    Feb17 ?        00:35:10 etcd --advertise-client-urls=https://192.168.1.111:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd --initial-advertise-peer-urls=https://192.168.1.111:2380 --initial-cluster=ubuntu=https://192.168.1.111:2380 --key-file=/etc/kubernetes/pki/etcd/server.key --listen-client-urls=https://127.0.0.1:2379,https://192.168.1.111:2379 --listen-metrics-urls=http://127.0.0.1:2381 --listen-peer-urls=https://192.168.1.111:2380 --name=ubuntu --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt --peer-client-cert-auth=true --peer-key-file=/etc/kubernetes/pki/etcd/peer.key --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt --snapshot-count=10000 --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
4 S root       7536   7495  0  80   0 - 35026 -      Feb17 ?        00:01:04 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=ubuntu
4 S root       9868   9839  0  80   0 - 34463 -      Feb17 ?        00:00:59 /usr/bin/kube-controllers
4 S root      48394  48375  2  80   0 - 36076 -      13:41 ?        00:01:09 kube-scheduler --authentication-kubeconfig=/etc/kubernetes/scheduler.conf --authorization-kubeconfig=/etc/kubernetes/scheduler.conf --bind-address=127.0.0.1 --kubeconfig=/etc/kubernetes/scheduler.conf --leader-elect=true
4 S root      48461  48436  3  80   0 - 52484 -      13:41 ?        00:01:53 kube-controller-manager --allocate-node-cidrs=true --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf --bind-address=127.0.0.1 --client-ca-file=/etc/kubernetes/pki/ca.crt --cluster-cidr=10.244.0.0/16 --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt --cluster-signing-key-file=/etc/kubernetes/pki/ca.key --controllers=*,bootstrapsigner,tokencleaner --kubeconfig=/etc/kubernetes/controller-manager.conf --leader-elect=true --node-cidr-mask-size=24 --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --root-ca-file=/etc/kubernetes/pki/ca.crt --service-account-private-key-file=/etc/kubernetes/pki/sa.key --service-cluster-ip-range=10.96.0.0/12 --use-service-account-credentials=true
4 S root      52675  52586  7  80   0 - 123895 -     14:00 ?        00:02:01 kube-apiserver --advertise-address=192.168.1.111 --allow-privileged=true --authorization-mode=Node,RBAC --client-ca-file=/etc/kubernetes/pki/ca.crt --enable-admission-plugins=NodeRestriction --enable-bootstrap-token-auth=true --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key --etcd-servers=https://127.0.0.1:2379 --insecure-port=0 --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key --requestheader-allowed-names=front-proxy-client --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group --requestheader-username-headers=X-Remote-User --secure-port=6443 --service-account-key-file=/etc/kubernetes/pki/sa.pub --service-cluster-ip-range=10.96.0.0/12 --tls-cert-file=/etc/kubernetes/pki/apiserver.crt --tls-private-key-file=/etc/kubernetes/pki/apiserver.key
</code>```

答:
There are two questions asked in one:

Stop kubernetes cluster and

Temporarily stop

I will answer keeping both in mind. Also it is not clear how you created your cluster but it seems like you used kubeadm.

Steps:

As mentioned by @arghya-sadhu & @henry, gracefull shutdown is recommended but not mandatory if this is a test cluster and you don't care about the workloads (pods,etc)

kubectl cordon <node name>

kubectl drain <node name>

kubeadm hosts master plane pods as static pods ref! mv /etc/kubernetes/manifests/ /tmp as explained here

Body:
I've set up single node kubernetes  according to [official tutorial][1].

In addition to official documentation I've set-up single node cluster:

kubectl taint nodes --all node-role.kubernetes.io/master-

Disabled eviction limit:

cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet

And set systemd driver for Docker:

cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker

How can I temporary stop Kubernetes cluster (including all it's services, podd, etc)? I've issued systemctl stop kubelet but I stil see some kubernetes stuff among processes

$ ps -elf | grep kube
4 S root       6032   5914  1  80   0 - 2653148 -    Feb17 ?        00:35:10 etcd --advertise-client-urls=https://192.168.1.111:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd --initial-advertise-peer-urls=https://192.168.1.111:2380 --initial-cluster=ubuntu=https://192.168.1.111:2380 --key-file=/etc/kubernetes/pki/etcd/server.key --listen-client-urls=https://127.0.0.1:2379,https://192.168.1.111:2379 --listen-metrics-urls=http://127.0.0.1:2381 --listen-peer-urls=https://192.168.1.111:2380 --name=ubuntu --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt --peer-client-cert-auth=true --peer-key-file=/etc/kubernetes/pki/etcd/peer.key --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt --snapshot-count=10000 --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
4 S root       7536   7495  0  80   0 - 35026 -      Feb17 ?        00:01:04 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=ubuntu
4 S root       9868   9839  0  80   0 - 34463 -      Feb17 ?        00:00:59 /usr/bin/kube-controllers
4 S root      48394  48375  2  80   0 - 36076 -      13:41 ?        00:01:09 kube-scheduler --authentication-kubeconfig=/etc/kubernetes/scheduler.conf --authorization-kubeconfig=/etc/kubernetes/scheduler.conf --bind-address=127.0.0.1 --kubeconfig=/etc/kubernetes/scheduler.conf --leader-elect=true
4 S root      48461  48436  3  80   0 - 52484 -      13:41 ?        00:01:53 kube-controller-manager --allocate-node-cidrs=true --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf --bind-address=127.0.0.1 --client-ca-file=/etc/kubernetes/pki/ca.crt --cluster-cidr=10.244.0.0/16 --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt --cluster-signing-key-file=/etc/kubernetes/pki/ca.key --controllers=*,bootstrapsigner,tokencleaner --kubeconfig=/etc/kubernetes/controller-manager.conf --leader-elect=true --node-cidr-mask-size=24 --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --root-ca-file=/etc/kubernetes/pki/ca.crt --service-account-private-key-file=/etc/kubernetes/pki/sa.key --service-cluster-ip-range=10.96.0.0/12 --use-service-account-credentials=true
4 S root      52675  52586  7  80   0 - 123895 -     14:00 ?        00:02:01 kube-apiserver --advertise-address=192.168.1.111 --allow-privileged=true --authorization-mode=Node,RBAC --client-ca-file=/etc/kubernetes/pki/ca.crt --enable-admission-plugins=NodeRestriction --enable-bootstrap-token-auth=true --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key --etcd-servers=https://127.0.0.1:2379 --insecure-port=0 --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key --requestheader-allowed-names=front-proxy-client --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group --requestheader-username-headers=X-Remote-User --secure-port=6443 --service-account-key-file=/etc/kubernetes/pki/sa.pub --service-cluster-ip-range=10.96.0.0/12 --tls-cert-file=/etc/kubernetes/pki/apiserver.crt --tls-private-key-file=/etc/kubernetes/pki/apiserver.key


问:
is there any way to convert string with hypen into integer in java(Android sdk)
I am trying below code to convert string into Int but it is showing exception

```<code>String ID = "37f6c80-2d5-44c-82f-0001a40cf4"
int boardid = Integer.parseInt(ID);
</code>```

Exception is :

```<code>java.lang.NumberFormatException: For input string:
</code>```

I can handle exception by writing it in try and catch, but the problem is there any way I can convert it into int?

答: You can get rid of all the non-number characters with this regex pattern ID = ID.replaceAll("\\D+",""); and you can then convert it into int with your int boardid = Integer.parseInt(ID);. I would probably go for long though.

Body:
I am trying below code to convert string into Int but it is showing exception

String ID = "37f6c80-2d5-44c-82f-0001a40cf4"
int boardid = Integer.parseInt(ID);

Exception is :

java.lang.NumberFormatException: For input string:

I can handle exception by writing it in try and catch, but the problem is there any way I can convert it into int?


问:
I get a 504 timeout error when importing excel to a db (Laravel)
I'm trying to import 10,000 records in excel with the library "Maatwebsite / Laravel-Excel" in Laravel, but when importing 10,000 records, the page returns a 504 timeout error (the odd thing is that it keeps inserting data in the db after that). Well then, I show you my code to see if you can help me, thanks.

This is the Import Inventory, where I programmed everything I should do with the data to be imported into the db.

```<code>class InventarioImport implements ToCollection, WithChunkReading
{
    use Importable;
    /**
     * @param array $row
     *
     * @return User|null
     */

    public function chunkSize(): int
    {
        return 250;
    }

    public function collection(collection $rows)
    {
         foreach ($rows as $row)
        {

        $almacenes = Almacen::where('tienda_id', \Session::get('tienda_id'))->get();
        $codigos = Codigo::where('tienda_id', \Session::get('tienda_id'))->get();
        $contc=-1;
        $conta=0;

        foreach ($codigos as $codigo) {
            $contc++;
        }
        foreach ($almacenes as $almacen) {
            $conta++;
        }
        if($row[$contc+1]=="DESCRIPCION") {
                continue 1;

            }

        $idmarca = Marca::where('nombre_marca', $row[$contc+2])->where('tienda_id', \Session::get('tienda_id'))->first();

        if ($idmarca==null) {
           $marcaid= Marca::create([
           'nombre_marca'     => $row[$contc+2],
           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",

        ])->id;
}
else {
  $marcaid = $idmarca->id;
}
$buscarcategoria = Categoria::where('nombre_categoria', $row[$contc+3])->where('tienda_id', \Session::get('tienda_id'))->first();
        if ($buscarcategoria==null) {
           Categoria::create([
           'nombre_categoria'     => $row[$contc+3],
           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",

        ]);
}
$i=0;
       $buscaritem = Item::where('nombre_item', $row[$contc+1])->where('tienda_id', \Session::get('tienda_id'))->first();

 $buscarunidad = Unidad::where('nombre_unidad', $row[$contc+4])->first();

   $buscarmoneda = ConfiguracionMoneda::where('abreviacion_moneda', $row[$conta+3+$contc+4])->where('tienda_id', \Session::get('tienda_id'))->first();
    $itemid= Item::create([
            'marca_id' => $marcaid,
           'nombre_item'     => $row[$contc+1],
           'unidad_id'     => $buscarunidad->id,
           'stock_minimo'     => $row[$conta+1+$contc+4],
           'stock_maximo'     => $row[$conta+2+$contc+4],
           'moneda_id'     => $buscarmoneda->id,
           'precio'     => $row[$conta+4+$contc+4],
           'impuesto'     => $row[$conta+5+$contc+4],
           'margen_final'     => $row[$conta+6+$contc+4],
           'margen_inicio'     => $row[$conta+7+$contc+4],
           'notas'     => $row[$conta+8+$contc+4],
           'estado'     => "A",
           'tienda_id'     => \Session::get('tienda_id'),

        ])->id;
        $a=$contc+4;
        $j=$a+1;
        foreach ($almacenes as $almacen) {

       $buscaralmacen = Almacen::where('nombre_almacen', $almacen->nombre_almacen)->where('tienda_id', \Session::get('tienda_id'))->first();

          ItemStock::create([
           'item_id'     => $itemid,
           'almacen_id' => $buscaralmacen->id,
           'detalle' => "Saldo Inicial",
            'cantidad' => $row[$j],
            'tipo' => "M",

           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",
        ]);

        $kardex = new Kardex();
                $kardex->item_id = $itemid;
                $kardex->fecha = date("Y/m/d");
                $kardex->operacion = "Inicial";
 $kardex->tipo = "";
 $kardex->serie = "";
 $kardex->numero = "";

                $kardex->almacen_id = $buscaralmacen->id;
                $kardex->tienda_id = \Session::get('tienda_id');
                $kardex->saldocantidad = $row[$j];
                $kardex->saldocosto = $row[$conta+4+$contc+4];
                $kardex->saldototal = $row[$conta+4+$contc+4]*$row[$j];

                $kardex->save();
                $j++;
 }

  foreach ($codigos as $codigo) {

       $buscarcodigo = Codigo::where('nombre_codigo', $codigo->nombre_codigo)->where('tienda_id', \Session::get('tienda_id'))->first();
       $buscaritem = Item::where('nombre_item', $row[$contc+1])->where('tienda_id', \Session::get('tienda_id'))->first();

          ItemCodigo::create([
           'item_codigo'     => $row[$i],
           'codigo_id' => $buscarcodigo->id,
           'item_id' => $buscaritem->id,
           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",
        ]);
        $i++;

 }

    }
    }
}
</code>```

This is my function in Controller, which I do the import as indicated in the previous script.

```<code>public function subirinventario(Request $request)
    {
        $title = 'Inventario subido';

        $contarr= $request->contarr;
  $arrayitems = Excel::import(new InventarioImport, $request->path);
        return view('item.finalizar', compact('contarr','title'));
    }
</code>```

That would be all, I missed the routes and the views, but it works fine with few records, I have to emphasize that I have increased the runtime of nginx, restarted and nothing.

This is an image with the preview of the data and columns, only 10 are shown, but more than 10 thousand were detected.

答:
You can try to put this 2 lines in the start of your method/function:

```<code>    ini_set('memory_limit','1024M');
    set_time_limit(3000000); //You can use 0 to remove limits
</code>```

As I stated above you can use 0 inside the set_time_limit method, but i don't recommend this, because losing all the control of your execution is not worth in most cases

Hope it works!

Body:
I'm trying to import 10,000 records in excel with the library "Maatwebsite / Laravel-Excel" in Laravel, but when importing 10,000 records, the page returns a 504 timeout error (the odd thing is that it keeps inserting data in the db after that). Well then, I show you my code to see if you can help me, thanks.

This is the Import Inventory, where I programmed everything I should do with the data to be imported into the db.

class InventarioImport implements ToCollection, WithChunkReading
{
    use Importable;
    /**
     * @param array $row
     *
     * @return User|null
     */

    public function chunkSize(): int
    {
        return 250;
    }

    public function collection(collection $rows)
    {
         foreach ($rows as $row)
        {

        $almacenes = Almacen::where('tienda_id', \Session::get('tienda_id'))->get();
        $codigos = Codigo::where('tienda_id', \Session::get('tienda_id'))->get();
        $contc=-1;
        $conta=0;

        foreach ($codigos as $codigo) {
            $contc++;
        }
        foreach ($almacenes as $almacen) {
            $conta++;
        }
        if($row[$contc+1]=="DESCRIPCION") {
                continue 1;

            }

        $idmarca = Marca::where('nombre_marca', $row[$contc+2])->where('tienda_id', \Session::get('tienda_id'))->first();

        if ($idmarca==null) {
           $marcaid= Marca::create([
           'nombre_marca'     => $row[$contc+2],
           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",

        ])->id;
}
else {
  $marcaid = $idmarca->id;
}
$buscarcategoria = Categoria::where('nombre_categoria', $row[$contc+3])->where('tienda_id', \Session::get('tienda_id'))->first();
        if ($buscarcategoria==null) {
           Categoria::create([
           'nombre_categoria'     => $row[$contc+3],
           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",

        ]);
}
$i=0;
       $buscaritem = Item::where('nombre_item', $row[$contc+1])->where('tienda_id', \Session::get('tienda_id'))->first();

 $buscarunidad = Unidad::where('nombre_unidad', $row[$contc+4])->first();

   $buscarmoneda = ConfiguracionMoneda::where('abreviacion_moneda', $row[$conta+3+$contc+4])->where('tienda_id', \Session::get('tienda_id'))->first();
    $itemid= Item::create([
            'marca_id' => $marcaid,
           'nombre_item'     => $row[$contc+1],
           'unidad_id'     => $buscarunidad->id,
           'stock_minimo'     => $row[$conta+1+$contc+4],
           'stock_maximo'     => $row[$conta+2+$contc+4],
           'moneda_id'     => $buscarmoneda->id,
           'precio'     => $row[$conta+4+$contc+4],
           'impuesto'     => $row[$conta+5+$contc+4],
           'margen_final'     => $row[$conta+6+$contc+4],
           'margen_inicio'     => $row[$conta+7+$contc+4],
           'notas'     => $row[$conta+8+$contc+4],
           'estado'     => "A",
           'tienda_id'     => \Session::get('tienda_id'),

        ])->id;
        $a=$contc+4;
        $j=$a+1;
        foreach ($almacenes as $almacen) {

       $buscaralmacen = Almacen::where('nombre_almacen', $almacen->nombre_almacen)->where('tienda_id', \Session::get('tienda_id'))->first();

          ItemStock::create([
           'item_id'     => $itemid,
           'almacen_id' => $buscaralmacen->id,
           'detalle' => "Saldo Inicial",
            'cantidad' => $row[$j],
            'tipo' => "M",

           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",
        ]);

        $kardex = new Kardex();
                $kardex->item_id = $itemid;
                $kardex->fecha = date("Y/m/d");
                $kardex->operacion = "Inicial";
 $kardex->tipo = "";
 $kardex->serie = "";
 $kardex->numero = "";

                $kardex->almacen_id = $buscaralmacen->id;
                $kardex->tienda_id = \Session::get('tienda_id');
                $kardex->saldocantidad = $row[$j];
                $kardex->saldocosto = $row[$conta+4+$contc+4];
                $kardex->saldototal = $row[$conta+4+$contc+4]*$row[$j];

                $kardex->save();
                $j++;
 }

  foreach ($codigos as $codigo) {

       $buscarcodigo = Codigo::where('nombre_codigo', $codigo->nombre_codigo)->where('tienda_id', \Session::get('tienda_id'))->first();
       $buscaritem = Item::where('nombre_item', $row[$contc+1])->where('tienda_id', \Session::get('tienda_id'))->first();

          ItemCodigo::create([
           'item_codigo'     => $row[$i],
           'codigo_id' => $buscarcodigo->id,
           'item_id' => $buscaritem->id,
           'tienda_id'     => \Session::get('tienda_id'),
           'estado'     => "A",
        ]);
        $i++;

 }

    }
    }
}

This is my function in Controller, which I do the import as indicated in the previous script.

public function subirinventario(Request $request)
    {
        $title = 'Inventario subido';

        $contarr= $request->contarr;
  $arrayitems = Excel::import(new InventarioImport, $request->path);
        return view('item.finalizar', compact('contarr','title'));
    }

That would be all, I missed the routes and the views, but it works fine with few records, I have to emphasize that I have increased the runtime of nginx, restarted and nothing.

This is an image with the preview of the data and columns, only 10 are shown, but more than 10 thousand were detected.

Body:
You can try to put this 2 lines in the start of your method/function:

    ini_set('memory_limit','1024M');
    set_time_limit(3000000); //You can use 0 to remove limits

As I stated above you can use 0 inside the set_time_limit method, but i don't recommend this, because losing all the control of your execution is not worth in most cases

Hope it works!


问:
Optimize group of characters for a cleaner code
I need some help whit the optimization of this group of characters [qwertyuiopasdfghjklzxcvbnmàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ] obviously it is really big so I need it smaller so I can use it into a regex, like this:

```<code>let N = /^N1\d{14}[^qwertyuiopasdfghjklzxcvbnmàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]{78}$/;
</code>```

I tried examples from other sites and this one too but didn't work as expected, can some one help me?

This regex is supposed to match a type of register like this one:

Register

```<code>N108258594000135255240708     315370        BLABLA BLABLABL BLAB BLA
</code>```

答:
Why are you negating the character group ? Isn't it better to enumerate the characters that can appear instead of those that mustn't ?

This would be a much cleaner regex:

```<code>let N = /^N1\d{14}[ 0-9A-Z]{78}$/;
</code>```

Body:
I need some help whit the optimization of this group of characters [qwertyuiopasdfghjklzxcvbnmàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ] obviously it is really big so I need it smaller so I can use it into a regex, like this:

let N = /^N1\d{14}[^qwertyuiopasdfghjklzxcvbnmàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]{78}$/;

I tried examples from other sites and this one too but didn't work as expected, can some one help me?

This regex is supposed to match a type of register like this one:

Register

N108258594000135255240708     315370        BLABLA BLABLABL BLAB BLA

Body:
Why are you negating the character group ? Isn't it better to enumerate the characters that can appear instead of those that mustn't ?

This would be a much cleaner regex:

let N = /^N1\d{14}[ 0-9A-Z]{78}$/;


问:
How to send AutoCAD Commands through VBA?
I'm trying to do the following but through VBA:

Open Object

Send CTRL+0 (_CleanScreenON)

Send MouseClick * 2 = (._ZOOM All)

Save and close document returning to Access.

But really, all I need to understand is how to open a drawing and send commands to it. I haven't been successfull.

I'm aware of the AutoCAD Document Object Documentation and I've experimented with SendCommand and PostCommand but I'm getting Object doesn't support Automation errors... Can someone shed some light on what I'm doing wrong?

Thanks in advance, Rafael.

EDIT:
This is the code I was experimenting with:

```<code>Private Sub CenterDWG_Click()
'Me.DrawingFrame.Object.Open
Me.DrawingFrame.Object.SendCommand ("_CleanScreenON")
Me.DrawingFrame.Object.SendCommand ("._ZOOM All")
'Me.DrawingFrame.Object.Regen acAllViewports
End Sub
</code>```

答:
I know this is old, but I have an application that I have developed for this. Below, I have taken some of the code and added it for reference. I tried to clean it up as best as possible, but I am sure there are missing functions in here. If you have any additional questions, don't hesitate to ask.

The application that this code comes from is an access database that we developed here. It holds records for each of our evergreen AutoCAD drawings. It has sub tables to store revision entries with supporting documentation (PDF redlines), block reference information, block attribute reference information, custom drawing properties, and layer information. It does much more than this, but that's another topic.

I have also used late binding instead of a direct reference to AutoCAD as we have users on different versions. This is more difficult to code, but accomplishes the same goal.

Lastly, I am a self-taught programmer and I know that my code is not perfect, but it serves as a great solution for what we needed. Any suggestions are appreciated and welcomed. I hope this helps whoever finds this topic.

Button Click to Open Drawing

```<code>Private Sub TxtSketchURL_Click()

On Error GoTo ErrorHandler

SketchPath = "C:\Test.dwg" '<---Provide your autocad path here

Call getCadDwg(SketchPath)

'-------------------------------------------------------
ExitHere:
    On Error Resume Next

    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure TxtSketchURL_Click of VBA Document Form_Sketch", vbOKOnly
    GoTo ExitHere
End Sub
</code>```

Sub to Open the drawing

```<code>Public Sub getCadDwg(Dwgpath As String)
On Error GoTo ErrorHandler
Dim strMsg As String
Dim booYouHaveItOpen As Boolean
Set CADApp = GetCad
Dim booFileOpen As Boolean
booFileOpen = isFileOpen(Dwgpath)
Dim booFileExists As Boolean

Dim objfso As New Scripting.FileSystemObject
booFileExists = objfso.fileExists(Dwgpath)

'See if the file exists and then exit if it doesn't
If booFileExists = False Then
    MsgBox "A file at the below path does not exist." & vbCr & vbCr & vbCr & Dwgpath, vbOKOnly, "File Missing"
End If

If booFileOpen = True Then
    'Search to see if it is the current user that has it opened
    If CADApp.Documents.Count > 0 Then
        For Each myDwg In CADApp.Documents
            'Test to see if one of the current drawing has the same path, then bring it to the front.
            If Dwgpath = myDwg.FullName Or GetUNC(Dwgpath) = myDwg.FullName Then
            booYouHaveItOpen = True
                If myDwg.active = False Then
                    myDwg.Activate
                    Call bringCADToFront
                    Exit For

                End If
            End If
        Next myDwg
    End If

    If booYouHaveItOpen = False Then
                MsgBox "Drawing file is already opened by another user." _
                    , vbInformation + vbOKOnly _
                    , "Drawing Opened Already!"
    End If

    GoTo ExitHere

    Else
        'Open the AutoCAD drawing
        Set myDwg = CADApp.Documents.Open(Dwgpath)

        CADApp.ZoomExtents
        CADApp.Visible = True

End If

'-------------------------------------------------------
ExitHere:
    On Error Resume Next

    Call bringCADToFront
    Set CADApp = Nothing
    Set myDwg = Nothing

    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure getCadDwg of Module mCadLateBind", vbOKOnly

    GoTo ExitHere
End Sub
</code>```

GetCAD Function

```<code>Public Function GetCad() As Object

On Error Resume Next

'Check to see if AutoCAD is open
'Set GetCad = GetObject(, "AutoCAD.Application.19")
Set GetCad = GetObject(, "AutoCAD.Application")

'If AutoCAD is NOT open and error number will be produced
If Err.Number <> 0 Then
    Err.Clear

    'Open an instance of AutoCAD
    'Set GetCad = CreateObject("AutoCAD.Application.19")
    Set GetCad = CreateObject("AutoCAD.Application")

End If

'Make AutoCAD visible
GetCad.Visible = True

End Function
</code>```

GetUNCPath Function

```<code>Public Function GetUNC(strMappedDrive As String) As String
    Dim objfso As FileSystemObject
    Dim objDrive As Drive
    Dim strDrive As String
    Dim strShare As String

On Error GoTo ErrorHandler

    Set objfso = New FileSystemObject

'Get the Drive Name
    strDrive = objfso.GetDriveName(strMappedDrive)
    Set objDrive = objfso.GetDrive(strDrive)
    'find the UNC share name from the mapped letter
    strShare = objDrive.ShareName
    'Replace the MappedDrive With the UNC share name
    GetUNC = Replace(strMappedDrive, strDrive, strShare)

'-------------------------------------------------------
ExitHere:
    On Error Resume Next
    Set objfso = Nothing 'Destroy the object
    Set objDrive = Nothing  'Destroy the object
    Exit Function

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure GetUNC of Module mFunctions", vbOKOnly

    GoTo ExitHere
End Function
</code>```

BringCADtoFront

```<code>Public Sub bringCADToFront()
    On Error GoTo ErrorHandler

Dim CADApp As Variant
Dim lngHwnd As Long
Dim lngMDIHwnd As Long

On Error GoTo ErrorHandler

Set CADApp = GetCad

lngHwnd = FindWindow(vbNullString, CADApp.Caption)

SetFocusAPI lngHwnd

'-------------------------------------------------------
ExitHere:
    On Error Resume Next
        Set CADApp = Nothing
    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure bringCADToFront of Sub mAutoCADsubs", vbOKOnly
    GoTo ExitHere
End Sub
</code>```

Save the AutoCAD drawing

```<code>myDwg.Close True 'True to save the drawing, False for no save
</code>```

Body:
I'm trying to do the following but through VBA:

Open Object

Send CTRL+0 (_CleanScreenON)

Send MouseClick * 2 = (._ZOOM All)

Save and close document returning to Access.

But really, all I need to understand is how to open a drawing and send commands to it. I haven't been successfull.

I'm aware of the AutoCAD Document Object Documentation and I've experimented with SendCommand and PostCommand but I'm getting Object doesn't support Automation errors... Can someone shed some light on what I'm doing wrong?

Thanks in advance, Rafael.

EDIT:
This is the code I was experimenting with:

Private Sub CenterDWG_Click()
'Me.DrawingFrame.Object.Open
Me.DrawingFrame.Object.SendCommand ("_CleanScreenON")
Me.DrawingFrame.Object.SendCommand ("._ZOOM All")
'Me.DrawingFrame.Object.Regen acAllViewports
End Sub

Body:
I know this is old, but I have an application that I have developed for this. Below, I have taken some of the code and added it for reference. I tried to clean it up as best as possible, but I am sure there are missing functions in here. If you have any additional questions, don't hesitate to ask.

The application that this code comes from is an access database that we developed here. It holds records for each of our evergreen AutoCAD drawings. It has sub tables to store revision entries with supporting documentation (PDF redlines), block reference information, block attribute reference information, custom drawing properties, and layer information. It does much more than this, but that's another topic.

I have also used late binding instead of a direct reference to AutoCAD as we have users on different versions. This is more difficult to code, but accomplishes the same goal.

Lastly, I am a self-taught programmer and I know that my code is not perfect, but it serves as a great solution for what we needed. Any suggestions are appreciated and welcomed. I hope this helps whoever finds this topic.

Button Click to Open Drawing

Private Sub TxtSketchURL_Click()

On Error GoTo ErrorHandler

SketchPath = "C:\Test.dwg" '<---Provide your autocad path here

Call getCadDwg(SketchPath)

'-------------------------------------------------------
ExitHere:
    On Error Resume Next

    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure TxtSketchURL_Click of VBA Document Form_Sketch", vbOKOnly
    GoTo ExitHere
End Sub

Sub to Open the drawing

Public Sub getCadDwg(Dwgpath As String)
On Error GoTo ErrorHandler
Dim strMsg As String
Dim booYouHaveItOpen As Boolean
Set CADApp = GetCad
Dim booFileOpen As Boolean
booFileOpen = isFileOpen(Dwgpath)
Dim booFileExists As Boolean

Dim objfso As New Scripting.FileSystemObject
booFileExists = objfso.fileExists(Dwgpath)

'See if the file exists and then exit if it doesn't
If booFileExists = False Then
    MsgBox "A file at the below path does not exist." & vbCr & vbCr & vbCr & Dwgpath, vbOKOnly, "File Missing"
End If

If booFileOpen = True Then
    'Search to see if it is the current user that has it opened
    If CADApp.Documents.Count > 0 Then
        For Each myDwg In CADApp.Documents
            'Test to see if one of the current drawing has the same path, then bring it to the front.
            If Dwgpath = myDwg.FullName Or GetUNC(Dwgpath) = myDwg.FullName Then
            booYouHaveItOpen = True
                If myDwg.active = False Then
                    myDwg.Activate
                    Call bringCADToFront
                    Exit For

                End If
            End If
        Next myDwg
    End If

    If booYouHaveItOpen = False Then
                MsgBox "Drawing file is already opened by another user." _
                    , vbInformation + vbOKOnly _
                    , "Drawing Opened Already!"
    End If

    GoTo ExitHere

    Else
        'Open the AutoCAD drawing
        Set myDwg = CADApp.Documents.Open(Dwgpath)

        CADApp.ZoomExtents
        CADApp.Visible = True

End If

'-------------------------------------------------------
ExitHere:
    On Error Resume Next

    Call bringCADToFront
    Set CADApp = Nothing
    Set myDwg = Nothing

    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure getCadDwg of Module mCadLateBind", vbOKOnly

    GoTo ExitHere
End Sub

GetCAD Function

Public Function GetCad() As Object

On Error Resume Next

'Check to see if AutoCAD is open
'Set GetCad = GetObject(, "AutoCAD.Application.19")
Set GetCad = GetObject(, "AutoCAD.Application")

'If AutoCAD is NOT open and error number will be produced
If Err.Number <> 0 Then
    Err.Clear

    'Open an instance of AutoCAD
    'Set GetCad = CreateObject("AutoCAD.Application.19")
    Set GetCad = CreateObject("AutoCAD.Application")

End If

'Make AutoCAD visible
GetCad.Visible = True

End Function

GetUNCPath Function

Public Function GetUNC(strMappedDrive As String) As String
    Dim objfso As FileSystemObject
    Dim objDrive As Drive
    Dim strDrive As String
    Dim strShare As String

On Error GoTo ErrorHandler

    Set objfso = New FileSystemObject

'Get the Drive Name
    strDrive = objfso.GetDriveName(strMappedDrive)
    Set objDrive = objfso.GetDrive(strDrive)
    'find the UNC share name from the mapped letter
    strShare = objDrive.ShareName
    'Replace the MappedDrive With the UNC share name
    GetUNC = Replace(strMappedDrive, strDrive, strShare)

'-------------------------------------------------------
ExitHere:
    On Error Resume Next
    Set objfso = Nothing 'Destroy the object
    Set objDrive = Nothing  'Destroy the object
    Exit Function

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure GetUNC of Module mFunctions", vbOKOnly

    GoTo ExitHere
End Function

BringCADtoFront

Public Sub bringCADToFront()
    On Error GoTo ErrorHandler

Dim CADApp As Variant
Dim lngHwnd As Long
Dim lngMDIHwnd As Long

On Error GoTo ErrorHandler

Set CADApp = GetCad

lngHwnd = FindWindow(vbNullString, CADApp.Caption)

SetFocusAPI lngHwnd

'-------------------------------------------------------
ExitHere:
    On Error Resume Next
        Set CADApp = Nothing
    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure bringCADToFront of Sub mAutoCADsubs", vbOKOnly
    GoTo ExitHere
End Sub

Save the AutoCAD drawing

myDwg.Close True 'True to save the drawing, False for no save


问:
What is the most efficent way to get a Range "set difference" in Excel Automation?
Given a pair of ranges, where one is known to contain elements of another:

```<code>src = ActiveSheet.UsedRange
sel = src.SpecialCells(xlCellTypeVisible)
</code>```

what is the most efficient way to get a new range that represents the set difference
between these two ranges, i.e., the cells in src that are not in sel?

This can be done using a loop over the cells in src, but this requires m * n Automation calls for an m by n range, which does not have very good performance, and I'm hoping for something that involves fewer remote API calls.

答:
Have you tried using Excel's built-in formulas to filter the data?  For example, the following formula will print "Yes" if the value in cell A2 is found in column D.  In your case, you could simply grab all the cells which do not have the corresponding "Yes".</p>

```<code>=IF(MATCH(A2,D:D, 0)>0,"Yes","No")
</code>```

OwnerDisplayName: Christopher Currie

ContentLicense: CC BY-SA 2.5

Body:
Given a pair of ranges, where one is known to contain elements of another:

src = ActiveSheet.UsedRange
sel = src.SpecialCells(xlCellTypeVisible)

what is the most efficient way to get a new range that represents the set difference
between these two ranges, i.e., the cells in src that are not in sel?

This can be done using a loop over the cells in src, but this requires m * n Automation calls for an m by n range, which does not have very good performance, and I'm hoping for something that involves fewer remote API calls.

Body:
Have you tried using Excel's built-in formulas to filter the data?  For example, the following formula will print "Yes" if the value in cell A2 is found in column D.  In your case, you could simply grab all the cells which do not have the corresponding "Yes".

=IF(MATCH(A2,D:D, 0)>0,"Yes","No")

OwnerDisplayName: Tom E


问:
Listview TwoWay Binding With ObservableCollection
:::::::::: ObservableCollection ::::::::::

```<code>    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );
</code>```

:::::::::: InitializeFriends ::::::::::

```<code>        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }
</code>```

:::::::::: Friend ::::::::::

```<code>    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }
</code>```

:::::::::: ListView ::::::::::

```<code>        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</code>```

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG

答:
When you have a problem with XAML bindings the first thing to do is run up your program under visual studio and look in your output window for any errors or warnings that mention XAML or Bindings. If there is a problem it will likely show up there.

Your output window can be opened by selecting View->Output from the main menu (or typing Ctrl+W, O). If you're not seeing anything then select Debug in the "Show Output From" combobox.

If you're still not seeing anything then you might need to change your WPF trace level. You can do this by selecting Debug from the main menu and choose “Options and Settings…”. Expand the Debugging node and select “Output Window”. Now in the right hand pane set the “Data Binding” value in "WPF Trace Settings" to at least Warning. You should see some info in the output window next time you run the app under VS.

If you’re still not getting enough information you can alter the trace level (in .Net 3.5 and above) in XAML by adding the System.Diagnostics namespace to your XAML file:

```<code> xmlns:diagnostics=”clr-namespace:System.Diagnostics;assembly=WindowsBase”
</code>```

and setting the trace level in the binding of interest like this:

```<code><ListView Name="Panel"
      Width="Auto"
      Margin="0,200,0,0"
      HorizontalAlignment="Stretch"
      VerticalAlignment="Stretch"
      Background="{x:Null}"
      BorderThickness="0"
      ItemsSource="{Binding Path=Friends,
                            Mode=TwoWay,
                            diagnostics:PresentationTraceSources.TraceLevel=High}"
      ScrollViewer.HorizontalScrollBarVisibility="Disabled"
      SelectionMode="Single">
</code>```

Body:
:::::::::: ObservableCollection ::::::::::

    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );

:::::::::: InitializeFriends ::::::::::

        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }

:::::::::: Friend ::::::::::

    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }

:::::::::: ListView ::::::::::

        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG

Body:
When you have a problem with XAML bindings the first thing to do is run up your program under visual studio and look in your output window for any errors or warnings that mention XAML or Bindings. If there is a problem it will likely show up there.

Your output window can be opened by selecting View->Output from the main menu (or typing Ctrl+W, O). If you're not seeing anything then select Debug in the "Show Output From" combobox.

If you're still not seeing anything then you might need to change your WPF trace level. You can do this by selecting Debug from the main menu and choose “Options and Settings…”. Expand the Debugging node and select “Output Window”. Now in the right hand pane set the “Data Binding” value in "WPF Trace Settings" to at least Warning. You should see some info in the output window next time you run the app under VS.

If you’re still not getting enough information you can alter the trace level (in .Net 3.5 and above) in XAML by adding the System.Diagnostics namespace to your XAML file:

 xmlns:diagnostics=”clr-namespace:System.Diagnostics;assembly=WindowsBase”

and setting the trace level in the binding of interest like this:

<ListView Name="Panel"
      Width="Auto"
      Margin="0,200,0,0"
      HorizontalAlignment="Stretch"
      VerticalAlignment="Stretch"
      Background="{x:Null}"
      BorderThickness="0"
      ItemsSource="{Binding Path=Friends,
                            Mode=TwoWay,
                            diagnostics:PresentationTraceSources.TraceLevel=High}"
      ScrollViewer.HorizontalScrollBarVisibility="Disabled"
      SelectionMode="Single">


问:
Prevent shiny app from breaking a while loop
I am trying to run a shiny app within a while loop. Upon exiting the app, the while loop breaks. Is there a way to stay within the loop upon exiting the app?

Here is an example of the problem. The app.R file is the app created upon creating a new shiny app.

```<code>library(shiny)

x <- 1

while(x<=5){

  runApp("app.R")

  x <- x+1

}
</code>```

答:
The "standard" way to stop a Shiny application is to simply stop the R process that's serving it. You need a way to close the app without breaking. The stopApp() function does that, returning control of the thread back to the main flow of your script.

This example is from the help page at ?runApp, and I've made two additions commented below.

```<code>library(shiny)

x <- 1
while (x <= 5) {
  runApp(list(
    ui = bootstrapPage(
      numericInput('n', 'Number of obs', 100),
      plotOutput('plot'),
      actionButton("done", "close")         # added a close button
    ),
    server = function(input, output) {
      output$plot <- renderPlot({ hist(runif(input$n)) })
      observeEvent(input$done, stopApp())   # added an observer to the close button
    }
  ))
  x <- x+1
}
</code>```

You can also put an argument from the logic of the Shiny app inside stopApp(), so that you can use the result in your other calculations. For this example, if we wanted to know what the user input for n, we could use stopApp(input$n), and the whole app would return that value, like below.

```<code>x <- 1
while (x <= 5) {
  user_input <- runApp(<code from above>)
  x <- x+1
}
</code>```

The important thing is to make it obvious to your users that they need to use your "close" button within the app, instead of closing the browser window or using the "Stop" button in RStudio. Either of those actions will interrupt your main script.

Edited to add:

There are actually some functions builtin to {shiny} to listen for a user's session ending (i.e. closing the browser window), onStop() and onSessionEnded(). You should check out the help page for them, but replacing my observeEvent(...) line with onStop(stopApp) (or onSessionEnded(stopApp)) seems to work just fine. Then you can remove the Close button from the UI.

Body:
I am trying to run a shiny app within a while loop. Upon exiting the app, the while loop breaks. Is there a way to stay within the loop upon exiting the app?

Here is an example of the problem. The app.R file is the app created upon creating a new shiny app.

library(shiny)

x <- 1

while(x<=5){

  runApp("app.R")

  x <- x+1

}

Body:
The "standard" way to stop a Shiny application is to simply stop the R process that's serving it. You need a way to close the app without breaking. The stopApp() function does that, returning control of the thread back to the main flow of your script.

This example is from the help page at ?runApp, and I've made two additions commented below.

library(shiny)

x <- 1
while (x <= 5) {
  runApp(list(
    ui = bootstrapPage(
      numericInput('n', 'Number of obs', 100),
      plotOutput('plot'),
      actionButton("done", "close")         # added a close button
    ),
    server = function(input, output) {
      output$plot <- renderPlot({ hist(runif(input$n)) })
      observeEvent(input$done, stopApp())   # added an observer to the close button
    }
  ))
  x <- x+1
}

You can also put an argument from the logic of the Shiny app inside stopApp(), so that you can use the result in your other calculations. For this example, if we wanted to know what the user input for n, we could use stopApp(input$n), and the whole app would return that value, like below.

x <- 1
while (x <= 5) {
  user_input <- runApp(<code from above>)
  x <- x+1
}

The important thing is to make it obvious to your users that they need to use your "close" button within the app, instead of closing the browser window or using the "Stop" button in RStudio. Either of those actions will interrupt your main script.

Edited to add:

There are actually some functions builtin to {shiny} to listen for a user's session ending (i.e. closing the browser window), onStop() and onSessionEnded(). You should check out the help page for them, but replacing my observeEvent(...) line with onStop(stopApp) (or onSessionEnded(stopApp)) seems to work just fine. Then you can remove the Close button from the UI.


问:
Python Beautifulsoup img tag parsing
I am using beautifulsoup to parse all img tags which is present in 'www.youtube.com'

The code is

```<code>import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://www.youtube.com/')
soup = BeautifulSoup(page)
tags=soup.findAll('img')
</code>```

But am not getting all img tags.The getting img tags are invalid also.

The img tags which i got after parsing is different from the page source img tags. Some attributes are missing.

I need to get all video img tags in youtube.com

Please help

答:
in my case some images didn't contain src.

so i did this to avoid keyError exception:

```<code>art_imgs = set(img['src'] for img in article.find_all('img') if img.has_attr('src'))
</code>```

Title: Python Beautifulsoup img tag parsing

Body:
I am using beautifulsoup to parse all img tags which is present in 'www.youtube.com'

The code is

import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://www.youtube.com/')
soup = BeautifulSoup(page)
tags=soup.findAll('img')

But am not getting all img tags.The getting img tags are invalid also.

The img tags which i got after parsing is different from the page source img tags. Some attributes are missing.

I need to get all video img tags in youtube.com

Please help

Body:
in my case some images didn't contain src.

so i did this to avoid keyError exception:

art_imgs = set(img['src'] for img in article.find_all('img') if img.has_attr('src'))


问:
Bottom line in SVG image is missing
I am new to SVG and I am trying to get a better understanding of the SVG attributes.
For this problem, I am trying to understand why the bottom line can't appear. I think it has something to do with viewBox, but i can't seem to get it right. It looks like there is a restriction within a fixed view (width and height) so that when it crosses the fixed width and height it will not display the shapes. How can I extent the width and height? I tried changing the percentages but that isn't correct either.

<svg xmlns="http://www.w3.org/2000/svg" width="50%" height="50%" >

    <svg viewBox="-10 -10 2700 2700">

      <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
        fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

      <circle cx="450" cy="150" r="30" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
    </svg>

    <svg viewBox="-960 -10 2700 2700">

      <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
        fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

      <circle cx="750" cy="750" r="50" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
    </svg>

    <svg viewBox="-1930 -10 2700 2700">

        <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
          fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

        <circle cx="450" cy="450" r="70" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
      </svg>

    <svg viewBox="-10 -950 2700 2700">

      <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
        fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

      <circle cx="450" cy="150" r="30" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
    </svg>

    <svg viewBox="-960 -950 2700 2700">

      <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
        fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

      <circle cx="750" cy="750" r="50" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
    </svg>

    <svg viewBox="-1920 -950 2700 2700">

        <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
          fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

        <circle cx="450" cy="450" r="70" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
      </svg>

    <svg viewBox="-10 -1900 2700 2700">

      <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
        fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

      <circle cx="450" cy="150" r="30" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
    </svg>

    <svg viewBox="-960 -1900 2700 2700">

      <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
        fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

      <circle cx="750" cy="750" r="50" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
    </svg>

<svg viewBox="-1920 -1900 2700 2700">

    <rect x="0" y="0" width="900" height="900" stroke="black" fill="rgb(255,255,255)"
      fill-opacity="0" stroke-opacity="1" stroke-width = "10"/>

    <circle cx="450" cy="450" r="70" stroke="black" fill-opacity="0"  stroke-opacity="1" stroke-width = "3" />
  </svg>
</svg>```

答:
Let's look at one of the bottom row viewBoxes.

```<code>viewBox="-1920 -1900 2700 2700"
</code>```

So this says the visible drawing will be y values from y=-1900 to y=2700-1900=800

The rect goes from y=0 to y=900 so the bottom of it is outside the viewBox and you see it clipped off.

Title: Bottom line in SVG image is missing

Body:
Let's look at one of the bottom row viewBoxes.

viewBox="-1920 -1900 2700 2700"

So this says the visible drawing will be y values from y=-1900 to y=2700-1900=800

The rect goes from y=0 to y=900 so the bottom of it is outside the viewBox and you see it clipped off.


问:
Remove scripts from html string using regex
I want to remove

but this won't:

How can I update the regex to fix this?

答: Lazy loading should do the trick

Body:
Lazy loading should do the trick
<script>(.+?)<\/script>


问:
Insert data from Excel sheet with multiple tabs into SQL Server into multiple tables
Suppose there are 5 worksheets for 5 tables in SQL Server, how do I write a single code to insert bulk data from this 5 sheets to 5 tables in SQL Server.</p>

答:
You can do that through SSMS import feature or run query.The question has already answered here :

How to import an Excel file into SQL Server?


问:
Alternative to atomic<variant> in C++
My C++17 code uses an std::atomic<MyVariant>, which is defined as

```<code>using MyVariant = std::variant<std::monostate, bool, unsigned int, int, double, void*>
</code>```

Using a modern clang, is_trivially_copyable<MyVariant> is true, but with some other compilers such as a modern Intel C (19.0.3), it isn't trivially copyable. This means I can't use it in an atomic type. I suppose this has to do with the implementation thereof inside the Intel compiler -- I don't think the standard requires variants to be trivially copyable.

Now I'm considering alternatives. Here's what I need to be able to do (which I'm currently doing now with the above approach):

load a new atomic variable / generic type from a MyVariant without knowing the contained type (e.g., I don't want to extract a specific type with std::get)

perform a compare_exchange_weak on the new alternative type without knowing the contained type

store the resulting value back into a MyVariant variable in the correct type

I'm willing to be a bit unsafe for this piece of code, which will be small and internal.

I tried to implement this following approach but it doesn't compile without a std::get of the contained type:

```<code>MyVariant       val = 42.2;
std::atomic<uint64_t> atomic_v;
atomic_v.store(val);  // fails to compile without a std::get<double>(val)
</code>```

Please let me know your thoughts on how I can both 1) do atomic operations on 64-bit piece of data without caring about the type and 2) later converting it back to a MyVariant without knowing the type. Is there a way to introspect the type of the variant and save it / use it somehow?

If this isn't possible, I will have to change my API.

答:
Using the helpful input from Igor Tandetnik and KamilCuk, here's a solution that works for my needs. It's messy as I need to maintain a parallel union definition as well as the variant that I'm exposing via my API, but I'm willing to do that and this seems to work and allows me to use atomic operations.

Feedback appreciated.

```<code>// run the code with something like: clang++ -std=c++17 main.cpp -o main && ./main

#include <atomic>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <variant>

using MyVariant = std::variant<bool, unsigned int, int, double, void*>;

int main(int argc, char const* argv[]) {

    union MyVariantAtomicUnion {
        std::atomic<bool>         bool_v;
        std::atomic<unsigned int> unsigned_v;
        std::atomic<int>          int_v;
        std::atomic<double>       double_v;
        std::atomic<void*>        void_ptr_v;
        bool                      invalid;
    };

    MyVariantAtomicUnion atomic_test_union;

    struct MyVisitor {
        MyVariantAtomicUnion& atomic_test_union_internal;

        MyVisitor(MyVariantAtomicUnion& u) : atomic_test_union_internal{u} {}

        void operator()(int int_var_val) {
            atomic_test_union_internal.int_v.store(int_var_val);
            printf("int value used\n");
        }
        void operator()(double d_var_val) {
            atomic_test_union_internal.double_v.store(d_var_val);
            printf("double value used\n");
        }
        void operator()(bool bool_v) {
            atomic_test_union_internal.bool_v.store(bool_v);
            printf("bool value used\n");
        }
        void operator()(unsigned int val) {
            atomic_test_union_internal.unsigned_v.store(val);
            printf("unsigned  value used\n");
        }
        void operator()(void* val) {
            atomic_test_union_internal.void_ptr_v.store(val);
            printf("void* value used\n");
        }
    };

    MyVariant d_val = 42.22222;

    MyVisitor my_vis{atomic_test_union};
    std::visit(my_vis, d_val);
    printf("After visitation, value is %lf\n",
           atomic_test_union.double_v.load());

    d_val = 55;
    std::visit(my_vis, d_val);
    printf("After visitation, value is %d\n", atomic_test_union.int_v.load());

    d_val = true;
    std::visit(my_vis, d_val);
    printf("After visitation, bool value is %d\n",
           atomic_test_union.bool_v.load());

    d_val = reinterpret_cast<void*>(0xfeedbeef);
    std::visit(my_vis, d_val);
    printf("After visitation, value is %p\n",
           atomic_test_union.void_ptr_v.load());

    return EXIT_SUCCESS;
}
</code>```

Title: Alternative to atomic<variant> in C++

Body:
My C++17 code uses an std::atomic<MyVariant>, which is defined as

using MyVariant = std::variant<std::monostate, bool, unsigned int, int, double, void*>

Using a modern clang, is_trivially_copyable<MyVariant> is true, but with some other compilers such as a modern Intel C (19.0.3), it isn't trivially copyable. This means I can't use it in an atomic type. I suppose this has to do with the implementation thereof inside the Intel compiler -- I don't think the standard requires variants to be trivially copyable.

Now I'm considering alternatives. Here's what I need to be able to do (which I'm currently doing now with the above approach):

load a new atomic variable / generic type from a MyVariant without knowing the contained type (e.g., I don't want to extract a specific type with std::get)

perform a compare_exchange_weak on the new alternative type without knowing the contained type

store the resulting value back into a MyVariant variable in the correct type

I'm willing to be a bit unsafe for this piece of code, which will be small and internal.

I tried to implement this following approach but it doesn't compile without a std::get of the contained type:

MyVariant       val = 42.2;
std::atomic<uint64_t> atomic_v;
atomic_v.store(val);  // fails to compile without a std::get<double>(val)

Please let me know your thoughts on how I can both 1) do atomic operations on 64-bit piece of data without caring about the type and 2) later converting it back to a MyVariant without knowing the type. Is there a way to introspect the type of the variant and save it / use it somehow?

If this isn't possible, I will have to change my API.

Body:
Using the helpful input from Igor Tandetnik and KamilCuk, here's a solution that works for my needs. It's messy as I need to maintain a parallel union definition as well as the variant that I'm exposing via my API, but I'm willing to do that and this seems to work and allows me to use atomic operations.

Feedback appreciated.

// run the code with something like: clang++ -std=c++17 main.cpp -o main && ./main

#include <atomic>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <variant>

using MyVariant = std::variant<bool, unsigned int, int, double, void*>;

int main(int argc, char const* argv[]) {

    union MyVariantAtomicUnion {
        std::atomic<bool>         bool_v;
        std::atomic<unsigned int> unsigned_v;
        std::atomic<int>          int_v;
        std::atomic<double>       double_v;
        std::atomic<void*>        void_ptr_v;
        bool                      invalid;
    };

    MyVariantAtomicUnion atomic_test_union;

    struct MyVisitor {
        MyVariantAtomicUnion& atomic_test_union_internal;

        MyVisitor(MyVariantAtomicUnion& u) : atomic_test_union_internal{u} {}

        void operator()(int int_var_val) {
            atomic_test_union_internal.int_v.store(int_var_val);
            printf("int value used\n");
        }
        void operator()(double d_var_val) {
            atomic_test_union_internal.double_v.store(d_var_val);
            printf("double value used\n");
        }
        void operator()(bool bool_v) {
            atomic_test_union_internal.bool_v.store(bool_v);
            printf("bool value used\n");
        }
        void operator()(unsigned int val) {
            atomic_test_union_internal.unsigned_v.store(val);
            printf("unsigned  value used\n");
        }
        void operator()(void* val) {
            atomic_test_union_internal.void_ptr_v.store(val);
            printf("void* value used\n");
        }
    };

    MyVariant d_val = 42.22222;

    MyVisitor my_vis{atomic_test_union};
    std::visit(my_vis, d_val);
    printf("After visitation, value is %lf\n",
           atomic_test_union.double_v.load());

    d_val = 55;
    std::visit(my_vis, d_val);
    printf("After visitation, value is %d\n", atomic_test_union.int_v.load());

    d_val = true;
    std::visit(my_vis, d_val);
    printf("After visitation, bool value is %d\n",
           atomic_test_union.bool_v.load());

    d_val = reinterpret_cast<void*>(0xfeedbeef);
    std::visit(my_vis, d_val);
    printf("After visitation, value is %p\n",
           atomic_test_union.void_ptr_v.load());

    return EXIT_SUCCESS;
}


问:
How do I manage/close connections if I can't change max_user_connections variable?
I am using shared hosting that has "max user connections" set to 30. I've contacted them and they said they could not change this value. By surfing through my website I get an exception thrown that says:

```<code>SQLSTATE[42000]: Syntax error or access violation: 1203 User id12578877_odonto already has more than 'max_user_connections' active connections
</code>```

Most of the actions in my web are just repositories (that have been generated with make:crud command) filtering some data. Upon changing between these pages rapidly for like 30s I get this error.

Is there any way I could reduce the number of connections or just basically anything I could do that would help?

Here is an example of how some of the actions in my controller look:

    /**
     * @Route("/", name="pacientai_index", methods={"GET"})
     */
    public function index(PacientaiRepository $pacientaiRepository): Response
    {
        if($this->getUser()==null){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getRole()=="NEW"){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getMiestas()=="London"){
            return $this->redirectToRoute('main');
        }
        return $this->render('pacientai/index.html.twig', [
            'pacientais' => $pacientaiRepository->findByStatus("NEW"),
            'sutarti' => $pacientaiRepository->findByStatus("SUTARTAS"),
        ]);
    }

    /**
     * @Route("/mine", name="pacientai_index_mine", methods={"GET", "POST"})
     */
    public function myPatients(PacientaiRepository $pacientaiRepository, UserRepository $userRepository): Response
    {
        if($this->getUser()==null){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getRole()=="NEW"){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getMiestas()=="London"){
            return $this->redirectToRoute('main');
        }
        $entityManager = $this->getDoctrine()->getManager();
        $entity = $this->getDoctrine()
            ->getRepository(User::class)
            ->find($this->getUser()->getId());
        $entity->setYraNauju(0);
        $entityManager->persist($entity);
        $entityManager->flush();
        return $this->render('pacientai/myPatients.html.twig');
    }
```

Am I doing something wrong here that could cause this?

I got this error while just testing with one user. Would it get even worse if, let's say, 20 users were connected to the website?

If there are too may open connections, how could I make that all requests would be from one connection?

答:
You can, after do whatever you need to do, do this:

$entityManager->getConnection()->close();
```

<p>Or, if you have a class that handles that, you can actually put that code into the __destruct method, then when the garbage collector runs, it will also close the connection, like this:</p>

<pre class="lang-php prettyprint-override"><code>public function __destruct()
{
   $entityManager = $this->getDoctrine()->getManager();
   $entityManager->getConnection()->close();
}
</code>```

Body:
I am using shared hosting that has "max user connections" set to 30. I've contacted them and they said they could not change this value. By surfing through my website I get an exception thrown that says:

SQLSTATE[42000]: Syntax error or access violation: 1203 User id12578877_odonto already has more than 'max_user_connections' active connections

Most of the actions in my web are just repositories (that have been generated with make:crud command) filtering some data. Upon changing between these pages rapidly for like 30s I get this error.

Is there any way I could reduce the number of connections or just basically anything I could do that would help?

Here is an example of how some of the actions in my controller look:

    /**
     * @Route("/", name="pacientai_index", methods={"GET"})
     */
    public function index(PacientaiRepository $pacientaiRepository): Response
    {
        if($this->getUser()==null){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getRole()=="NEW"){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getMiestas()=="London"){
            return $this->redirectToRoute('main');
        }
        return $this->render('pacientai/index.html.twig', [
            'pacientais' => $pacientaiRepository->findByStatus("NEW"),
            'sutarti' => $pacientaiRepository->findByStatus("SUTARTAS"),
        ]);
    }

    /**
     * @Route("/mine", name="pacientai_index_mine", methods={"GET", "POST"})
     */
    public function myPatients(PacientaiRepository $pacientaiRepository, UserRepository $userRepository): Response
    {
        if($this->getUser()==null){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getRole()=="NEW"){
            return $this->redirectToRoute('main');
        }
        if($this->getUser()->getMiestas()=="London"){
            return $this->redirectToRoute('main');
        }
        $entityManager = $this->getDoctrine()->getManager();
        $entity = $this->getDoctrine()
            ->getRepository(User::class)
            ->find($this->getUser()->getId());
        $entity->setYraNauju(0);
        $entityManager->persist($entity);
        $entityManager->flush();
        return $this->render('pacientai/myPatients.html.twig');
    }

Am I doing something wrong here that could cause this?

I got this error while just testing with one user. Would it get even worse if, let's say, 20 users were connected to the website?

If there are too may open connections, how could I make that all requests would be from one connection?

Body:
You can, after do whatever you need to do, do this:

$entityManager->getConnection()->close();

Or, if you have a class that handles that, you can actually put that code into the __destruct method, then when the garbage collector runs, it will also close the connection, like this:

public function __destruct()
{
   $entityManager = $this->getDoctrine()->getManager();
   $entityManager->getConnection()->close();
}


问:
How to patch Dto to Entity?
I have a controller that accepts a dto object. I need to change the fields that are present in the dto object.

```<code>@PatchMapping(value = "/update/{uuid}")
    public ResponseEntity<UserDto> update(
            @RequestBody UserDto userDto,
            @PathVariable("uuid")UUID uuid) throws UserNotFoundException {
        User updatedUser = userService.update(
                userMapper.userDtoToUser(userDto),
                uuid
        );
        return .....
    }
</code>```

But a userService can only accept entities. I need to use mapper dto -> entity. But the entity cannot have empty fields that come in dto (Let's say that you need to change only one field). What to do in this situation? I know that the controller should not contain logic

答:
You could use reflection to check the null properties and BeanUtils for the copying

In Spring that would be the way that I'd to check the empty properties

```<code>public static String[] getNullPropertyNames (Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<>();
    for(PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) emptyNames.add(pd.getName());
    }
    return emptyNames.toArray(new String[0]);
}
</code>```

And then for the copying

```<code>User updatedUser = new User();
BeanUtils.copyProperties(userDto, updatedUser, getNullPropertyNames(userDto));
</code>```

Title: How to patch Dto to Entity?

Body:
I have a controller that accepts a dto object. I need to change the fields that are present in the dto object.

@PatchMapping(value = "/update/{uuid}")
    public ResponseEntity<UserDto> update(
            @RequestBody UserDto userDto,
            @PathVariable("uuid")UUID uuid) throws UserNotFoundException {
        User updatedUser = userService.update(
                userMapper.userDtoToUser(userDto),
                uuid
        );
        return .....
    }

But a userService can only accept entities. I need to use mapper dto -> entity. But the entity cannot have empty fields that come in dto (Let's say that you need to change only one field). What to do in this situation? I know that the controller should not contain logic

Body:
You could use reflection to check the null properties and BeanUtils for the copying

In Spring that would be the way that I'd to check the empty properties

public static String[] getNullPropertyNames (Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<>();
    for(PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) emptyNames.add(pd.getName());
    }
    return emptyNames.toArray(new String[0]);
}

And then for the copying

User updatedUser = new User();
BeanUtils.copyProperties(userDto, updatedUser, getNullPropertyNames(userDto));


问:
Python 3.7 MultiThreading strategy
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

```<code>for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]
</code>```

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4

答:
If your program is CPU bound you will have hard times to do anything else in other threads due to the GIL (global interpreter lock).

Here is a link to an article which might help you to understand the topic: https://opensource.com/article/17/4/grok-gil

Downloading the data in a sub-process is most likely the best approach.

Title: Python 3.7 MultiThreading strategy

Body:
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4


问:
If the sum of the whole column is zero, then change the value of each row in SQL Server
I have a column named Percentage from a temporary table info, which if the sum of the whole column is zero, I want to change the value of each row to 0.5, and if the statement is false just leave it that way.

I have tried to do the following:

```<code>select case when Percentage = 0 then replace(Percentage, 0,0.5) end from ##info
</code>```

I know the above will change the fields whenever they are 0 regardless of the sum of the whole column, and if I do:

```<code>select case when sum(Percentage) = 0 then replace(Percentage, 0,0.5) end from ##info
</code>```

it would throw an error.

Another thing is that I want to replace the temporary table with that column and the above code would only give me the actual column without replacing the original column.

Any suggestions are appreciated

答:
If you want to select it:

```<code>SELECT
    CASE
        WHEN (SELECT SUM(Percentage) FROM ##info) = 0 THEN .5
        ELSE Percentage
    END
FROM ##info
</code>```

If you want to update the values in the table:

```<code> UPDATE ##info
 SET Percentage = .5
 WHERE (SELECT SUM(Percentage) FROM ##info) = 0
</code>```

Body:
I have a column named Percentage from a temporary table info, which if the sum of the whole column is zero, I want to change the value of each row to 0.5, and if the statement is false just leave it that way.

I have tried to do the following:

select case when Percentage = 0 then replace(Percentage, 0,0.5) end from ##info

I know the above will change the fields whenever they are 0 regardless of the sum of the whole column, and if I do:

select case when sum(Percentage) = 0 then replace(Percentage, 0,0.5) end from ##info

it would throw an error.

Another thing is that I want to replace the temporary table with that column and the above code would only give me the actual column without replacing the original column.

Any suggestions are appreciated

Body:
If you want to select it:

SELECT
    CASE
        WHEN (SELECT SUM(Percentage) FROM ##info) = 0 THEN .5
        ELSE Percentage
    END
FROM ##info

If you want to update the values in the table:

 UPDATE ##info
 SET Percentage = .5
 WHERE (SELECT SUM(Percentage) FROM ##info) = 0