qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
47,218,536 | I created a function to compare dates:
```
public function checkExpiredDate($cardDate) : bool
{
$currentDate = new DateTime();
$creditCardDate = new DateTime("{$cardDate->card_expiryYear}-{$cardDate->card_expiryMonth}-*last day from the month*");
echo $creditCardDate->format('Y-m-d'); exit();
return $creditCardDate->getTimestamp() < $currentDate->getTimestamp() ?? true;
}
```
I only have the `month` and `year` , not the `day`. I need to compare today's date with that date using only the `month` and `year` and the `DateTime` class . How can I do that ? Is there a way to get the last day from a month and year using the DateTime class? If I could get it someone using `DateTime` , my function should work . | 2017/11/10 | [
"https://Stackoverflow.com/questions/47218536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3084005/"
] | Set day as the 1st day of the month and then modify to the last
```
$creditCardDate = new DateTime("{$cardDate->card_expiryYear}-{$cardDate->card_expiryMonth}-1");
$creditCardDate->modify('last day of this month');
``` |
206,676 | By default my list of products (grid) shows 9 products, by it is able to be changed to 15 or 30.
Is there a way in which I can choose to display 30 products by default, when someone loads the site?
Here is a picture of the selection: <https://imgur.com/a/fqdvS>
Thanks. | 2017/12/21 | [
"https://magento.stackexchange.com/questions/206676",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/58016/"
] | Yes there is an option for this in admin
* Go to **Store->Configuration** from Menu
* Select **Catalog->Catalog** from left
navigation
* Then under **Storefront** tab there is `Products per Page on Grid Default Value` to set default value |
5,268 | I am making an RGB LED project right now using the Arduino UNO board.
At this point everything is working fine so I would like to transfer this onto a small microcontroller circuit to be put inside the enclosure. Since the enclosure is small, I cannot fit the UNO board inside it, hence I want to make a small circuit on perfboard with minimal components.
I read that you can burn the arduino bootloader on a standalone AVR (hooked up to power, filter caps and 16Mhz crystal) which can then execute Arduino code.
Any idea how can I do this? Also can I do this on an ATmega8l AVR, since my code is small enough to fit in one? No point wasting a 328 if 8L can do the job.
Thanks! | 2014/12/01 | [
"https://arduino.stackexchange.com/questions/5268",
"https://arduino.stackexchange.com",
"https://arduino.stackexchange.com/users/5050/"
] | ### The Bootlader
If you want to burn the bootloader to the standalone AVR that you will be using, you can do so using a programmer like the `USBasp`. Or, you can simply use the *Arduino* itself to do this.
* Open the `ArduinoISP` sketch from *File* > *Examples*.
* Upload it.
* Push `reset` on the Arduino.
### Wire it up
Next, wire up the AVR on a breadboard as shown here: [Arduino ISP](http://arduino.cc/en/Tutorial/ArduinoISP)
* If you are using a variant/derivative, use a crystal that matches the crystal on your board. You might have `not_in_sync()` trouble if you don't.
* Add a 10uF capacitor between `RESET` and `GROUND` on the Arduino, if you are using Uno, or something similar.
### Burning the Bootloader
Then select `Arduino as ISP` as the programmer.
* Goto *Tools* > *Programmer*.
* Select *Arduino as ISP*.
Now click on *Tools* > *Burn Bootloader*.
### Verifying it all works
Once that is done, open the Blink LED example and try uploading it to the AVR. You have to use the `Upload using Programmer` option from *File* > *Upload using Programmer*. You can verify if it is successful, by connecting an LED to `pin 19` of the AVR, and checking if it blinks.
### Notes:
* **Remember** that the pins on an AVR don't map to the corresponding pins on the Arduino, even if they are both the same chips. Search for "AVR to Arduino pin mapping" for your chip on Google. Here's the [ATMega8 to Arduino pin mapping](http://arduino.cc/en/Hacking/PinMapping).
* Don't forget to connect the ground lines of the AVR and the Arduino.
* This worked for me using an ATMega8A-PU. It should work with the 8L too.
* Post here if you have any problems. Glad to help `:)` |
61,116,946 | What happened:
==============
When I applied patch to ConfigMap, it doesn't work well. (`Error from server: v1.ConfigMap.Data: ReadString: expects " or n, but found {, error found in #10 byte of ...|"config":{"template"|..., bigger context ...|{"apiVersion":"v1","data":{"config":{"template":{"containers":[{"lifecycle":{"preStop":|...`)
gsed works fine, but I want to know `kubectl
Command
-------
```
$ kubectl patch configmap/cm-test-toshi -n dev --type merge -p '{
"data":{
"config":{
"template":{
"containers":[{
"name":"istio-proxy",
"lifecycle":{
"preStop":{
"exec":{
"command":[\"/bin/sh\", \"-c\", \"while [ $(netstat -plunt | grep tcp | grep -v envoy | wc -l | xargs) -ne 0]; do sleep 1; done\"]
}
}
}
}]
}
}
}
}'
```
Target CondigMap
----------------
```
apiVersion: v1
data:
config: |-
policy: disabled
alwaysInjectSelector:
[]
neverInjectSelector:
[]
template: |
initContainers:
- name: istio-validation
...
containers:
- name: istio-proxy
{{- if contains "/" (annotation .ObjectMeta `sidecar.istio.io/proxyImage` .Values.global.proxy.image) }}
image: "{{ annotation .ObjectMeta `sidecar.istio.io/proxyImage` .Values.global.proxy.image }}"
{{- else }}
image: "{{ .Values.global.hub }}/{{ .Values.global.proxy.image }}:{{ .Values.global.tag }}"
{{- end }}
ports:
...
```
What you expected to happen:
============================
No error occurs and `data.condif.template.containers[].lifecycle.preStop.exec.command` is applied.
```
apiVersion: v1
data:
config: |-
policy: disabled
alwaysInjectSelector:
[]
neverInjectSelector:
[]
template: |
initContainers:
- name: istio-validation
...
containers:
containers:
- name: istio-proxy
lifecycle: # added
preStop: # added
exec: # added
command: ["/bin/sh", "-c", "while [ $(netstat -plunt | grep tcp | grep -v envoy | wc -l | xargs) -ne 0 ]; do sleep 1; done"] # added
{{- if contains "/" (annotation .ObjectMeta `sidecar.istio.io/proxyImage` .Values.global.proxy.image) }}
image: "{{ annotation .ObjectMeta `sidecar.istio.io/proxyImage` .Values.global.proxy.image }}"
{{- else }}
image: "{{ .Values.global.hub }}/{{ .Values.global.proxy.image }}:{{ .Values.global.tag }}"
{{- end }}
ports:
...
```
How to reproduce it (as minimally and precisely as possible):
=============================================================
1. Create ConfigMap
```
$ kubectl apply -f cm-test-toshi.yaml
```
cm-test-toshi.yaml
```
apiVersion: v1
data:
config: |-
policy: disabled
alwaysInjectSelector:
[]
neverInjectSelector:
[]
template: |
{{- $cniDisabled := (not .Values.istio_cni.enabled) }}
{{- $cniRepairEnabled := (and .Values.istio_cni.enabled .Values.istio_cni.repair.enabled) }}
{{- $enableInitContainer := (or $cniDisabled $cniRepairEnabled .Values.global.proxy.enableCoreDump) }}
rewriteAppHTTPProbe: {{ valueOrDefault .Values.sidecarInjectorWebhook.rewriteAppHTTPProbe false }}
{{- if $enableInitContainer }}
containers:
- name: istio-proxy
{{- if contains "/" (annotation .ObjectMeta `sidecar.istio.io/proxyImage` .Values.global.proxy.image) }}
image: "{{ annotation .ObjectMeta `sidecar.istio.io/proxyImage` .Values.global.proxy.image }}"
{{- else }}
image: "{{ .Values.global.hub }}/{{ .Values.global.proxy.image }}:{{ .Values.global.tag }}"
{{- end }}
ports:
- containerPort: 15090
protocol: TCP
name: http-envoy-prom
args:
- proxy
- sidecar
- --domain
- $(POD_NAMESPACE).svc.{{ .Values.global.proxy.clusterDomain }}
- --configPath
- "/etc/istio/proxy"
- --binaryPath
- "/usr/local/bin/envoy"
- --serviceCluster
{{ if ne "" (index .ObjectMeta.Labels "app") -}}
- "{{ index .ObjectMeta.Labels `app` }}.$(POD_NAMESPACE)"
{{ else -}}
- "{{ valueOrDefault .DeploymentMeta.Name `istio-proxy` }}.{{ valueOrDefault .DeploymentMeta.Namespace `default` }}"
{{ end -}}
- --drainDuration
- "{{ formatDuration .ProxyConfig.DrainDuration }}"
- --parentShutdownDuration
- "{{ formatDuration .ProxyConfig.ParentShutdownDuration }}"
- --discoveryAddress
- "{{ annotation .ObjectMeta `sidecar.istio.io/discoveryAddress` .ProxyConfig.DiscoveryAddress }}"
{{- if eq .Values.global.proxy.tracer "lightstep" }}
- --lightstepAddress
- "{{ .ProxyConfig.GetTracing.GetLightstep.GetAddress }}"
- --lightstepAccessToken
- "{{ .ProxyConfig.GetTracing.GetLightstep.GetAccessToken }}"
- --lightstepSecure={{ .ProxyConfig.GetTracing.GetLightstep.GetSecure }}
- --lightstepCacertPath
- "{{ .ProxyConfig.GetTracing.GetLightstep.GetCacertPath }}"
{{- else if eq .Values.global.proxy.tracer "zipkin" }}
- --zipkinAddress
- "{{ .ProxyConfig.GetTracing.GetZipkin.GetAddress }}"
{{- else if eq .Values.global.proxy.tracer "datadog" }}
- --datadogAgentAddress
- "{{ .ProxyConfig.GetTracing.GetDatadog.GetAddress }}"
{{- end }}
- --proxyLogLevel={{ annotation .ObjectMeta `sidecar.istio.io/logLevel` .Values.global.proxy.logLevel}}
- --proxyComponentLogLevel={{ annotation .ObjectMeta `sidecar.istio.io/componentLogLevel` .Values.global.proxy.componentLogLevel}}
- --connectTimeout
- "{{ formatDuration .ProxyConfig.ConnectTimeout }}"
{{- if .Values.global.proxy.envoyStatsd.enabled }}
- --statsdUdpAddress
- "{{ .ProxyConfig.StatsdUdpAddress }}"
{{- end }}
{{- if .Values.global.proxy.envoyMetricsService.enabled }}
- --envoyMetricsServiceAddress
- "{{ .ProxyConfig.GetEnvoyMetricsService.GetAddress }}"
{{- end }}
{{- if .Values.global.proxy.envoyAccessLogService.enabled }}
- --envoyAccessLogServiceAddress
- "{{ .ProxyConfig.GetEnvoyAccessLogService.GetAddress }}"
{{- end }}
- --proxyAdminPort
- "{{ .ProxyConfig.ProxyAdminPort }}"
{{ if gt .ProxyConfig.Concurrency 0 -}}
- --concurrency
- "{{ .ProxyConfig.Concurrency }}"
{{ end -}}
{{- if .Values.global.controlPlaneSecurityEnabled }}
- --controlPlaneAuthPolicy
- MUTUAL_TLS
{{- else }}
- --controlPlaneAuthPolicy
- NONE
{{- end }}
- --dnsRefreshRate
- {{ valueOrDefault .Values.global.proxy.dnsRefreshRate "300s" }}
{{- if (ne (annotation .ObjectMeta "status.sidecar.istio.io/port" .Values.global.proxy.statusPort) "0") }}
- --statusPort
- "{{ annotation .ObjectMeta `status.sidecar.istio.io/port` .Values.global.proxy.statusPort }}"
- --applicationPorts
- "{{ annotation .ObjectMeta `readiness.status.sidecar.istio.io/applicationPorts` (applicationPorts .Spec.Containers) }}"
{{- end }}
{{- if .Values.global.trustDomain }}
- --trust-domain={{ .Values.global.trustDomain }}
{{- end }}
{{- if .Values.global.logAsJson }}
- --log_as_json
{{- end }}
{{- if (isset .ObjectMeta.Annotations `sidecar.istio.io/bootstrapOverride`) }}
- --templateFile=/etc/istio/custom-bootstrap/envoy_bootstrap.json
{{- end }}
{{- if .Values.global.proxy.lifecycle }}
lifecycle:
{{ toYaml .Values.global.proxy.lifecycle | indent 4 }}
{{- end }}
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: INSTANCE_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: SERVICE_ACCOUNT
valueFrom:
fieldRef:
fieldPath: spec.serviceAccountName
- name: HOST_IP
valueFrom:
fieldRef:
fieldPath: status.hostIP
{{- if eq .Values.global.proxy.tracer "datadog" }}
{{- if isset .ObjectMeta.Annotations `apm.datadoghq.com/env` }}
{{- range $key, $value := fromJSON (index .ObjectMeta.Annotations `apm.datadoghq.com/env`) }}
- name: {{ $key }}
value: "{{ $value }}"
{{- end }}
{{- end }}
{{- end }}
- name: ISTIO_META_POD_PORTS
value: |-
[
{{- $first := true }}
{{- range $index1, $c := .Spec.Containers }}
{{- range $index2, $p := $c.Ports }}
{{- if (structToJSON $p) }}
{{if not $first}},{{end}}{{ structToJSON $p }}
{{- $first = false }}
{{- end }}
{{- end}}
{{- end}}
]
- name: ISTIO_META_CLUSTER_ID
value: "{{ valueOrDefault .Values.global.multiCluster.clusterName `Kubernetes` }}"
- name: ISTIO_META_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: ISTIO_META_CONFIG_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: SDS_ENABLED
value: "{{ .Values.global.sds.enabled }}"
- name: ISTIO_META_INTERCEPTION_MODE
value: "{{ or (index .ObjectMeta.Annotations `sidecar.istio.io/interceptionMode`) .ProxyConfig.InterceptionMode.String }}"
- name: ISTIO_META_INCLUDE_INBOUND_PORTS
value: "{{ annotation .ObjectMeta `traffic.sidecar.istio.io/includeInboundPorts` (applicationPorts .Spec.Containers) }}"
{{- if .Values.global.network }}
- name: ISTIO_META_NETWORK
value: "{{ .Values.global.network }}"
{{- end }}
{{ if .ObjectMeta.Annotations }}
- name: ISTIO_METAJSON_ANNOTATIONS
value: |
{{ toJSON .ObjectMeta.Annotations }}
{{ end }}
{{ if .ObjectMeta.Labels }}
- name: ISTIO_METAJSON_LABELS
value: |
{{ toJSON .ObjectMeta.Labels }}
{{ end }}
{{- if .DeploymentMeta.Name }}
- name: ISTIO_META_WORKLOAD_NAME
value: {{ .DeploymentMeta.Name }}
{{ end }}
{{- if and .TypeMeta.APIVersion .DeploymentMeta.Name }}
- name: ISTIO_META_OWNER
value: kubernetes://apis/{{ .TypeMeta.APIVersion }}/namespaces/{{ valueOrDefault .DeploymentMeta.Namespace `default` }}/{{ toLower .TypeMeta.Kind}}s/{{ .DeploymentMeta.Name }}
{{- end}}
{{- if (isset .ObjectMeta.Annotations `sidecar.istio.io/bootstrapOverride`) }}
- name: ISTIO_BOOTSTRAP_OVERRIDE
value: "/etc/istio/custom-bootstrap/custom_bootstrap.json"
{{- end }}
{{- if .Values.global.sds.customTokenDirectory }}
- name: ISTIO_META_SDS_TOKEN_PATH
value: "{{ .Values.global.sds.customTokenDirectory -}}/sdstoken"
{{- end }}
{{- if .Values.global.meshID }}
- name: ISTIO_META_MESH_ID
value: "{{ .Values.global.meshID }}"
{{- else if .Values.global.trustDomain }}
- name: ISTIO_META_MESH_ID
value: "{{ .Values.global.trustDomain }}"
{{- end }}
{{- if and (eq .Values.global.proxy.tracer "datadog") (isset .ObjectMeta.Annotations `apm.datadoghq.com/env`) }}
{{- range $key, $value := fromJSON (index .ObjectMeta.Annotations `apm.datadoghq.com/env`) }}
- name: {{ $key }}
value: "{{ $value }}"
{{- end }}
{{- end }}
imagePullPolicy: "{{ valueOrDefault .Values.global.imagePullPolicy `Always` }}"
{{ if ne (annotation .ObjectMeta `status.sidecar.istio.io/port` .Values.global.proxy.statusPort) `0` }}
readinessProbe:
httpGet:
path: /healthz/ready
port: {{ annotation .ObjectMeta `status.sidecar.istio.io/port` .Values.global.proxy.statusPort }}
initialDelaySeconds: {{ annotation .ObjectMeta `readiness.status.sidecar.istio.io/initialDelaySeconds` .Values.global.proxy.readinessInitialDelaySeconds }}
periodSeconds: {{ annotation .ObjectMeta `readiness.status.sidecar.istio.io/periodSeconds` .Values.global.proxy.readinessPeriodSeconds }}
failureThreshold: {{ annotation .ObjectMeta `readiness.status.sidecar.istio.io/failureThreshold` .Values.global.proxy.readinessFailureThreshold }}
{{ end -}}
securityContext:
allowPrivilegeEscalation: {{ .Values.global.proxy.privileged }}
capabilities:
{{ if eq (annotation .ObjectMeta `sidecar.istio.io/interceptionMode` .ProxyConfig.InterceptionMode) `TPROXY` -}}
add:
- NET_ADMIN
{{- end }}
drop:
- ALL
privileged: {{ .Values.global.proxy.privileged }}
readOnlyRootFilesystem: {{ not .Values.global.proxy.enableCoreDump }}
runAsGroup: 1337
{{ if eq (annotation .ObjectMeta `sidecar.istio.io/interceptionMode` .ProxyConfig.InterceptionMode) `TPROXY` -}}
runAsNonRoot: false
runAsUser: 0
{{- else -}}
runAsNonRoot: true
runAsUser: 1337
{{- end }}
resources:
{{ if or (isset .ObjectMeta.Annotations `sidecar.istio.io/proxyCPU`) (isset .ObjectMeta.Annotations `sidecar.istio.io/proxyMemory`) -}}
requests:
{{ if (isset .ObjectMeta.Annotations `sidecar.istio.io/proxyCPU`) -}}
cpu: "{{ index .ObjectMeta.Annotations `sidecar.istio.io/proxyCPU` }}"
{{ end}}
{{ if (isset .ObjectMeta.Annotations `sidecar.istio.io/proxyMemory`) -}}
memory: "{{ index .ObjectMeta.Annotations `sidecar.istio.io/proxyMemory` }}"
{{ end }}
{{ else -}}
{{- if .Values.global.proxy.resources }}
{{ toYaml .Values.global.proxy.resources | indent 4 }}
{{- end }}
{{ end -}}
volumeMounts:
{{ if (isset .ObjectMeta.Annotations `sidecar.istio.io/bootstrapOverride`) }}
- mountPath: /etc/istio/custom-bootstrap
name: custom-bootstrap-volume
{{- end }}
- mountPath: /etc/istio/proxy
name: istio-envoy
{{- if .Values.global.sds.enabled }}
- mountPath: /var/run/sds
name: sds-uds-path
readOnly: true
- mountPath: /var/run/secrets/tokens
name: istio-token
{{- if .Values.global.sds.customTokenDirectory }}
- mountPath: "{{ .Values.global.sds.customTokenDirectory -}}"
name: custom-sds-token
readOnly: true
{{- end }}
{{- else }}
- mountPath: /etc/certs/
name: istio-certs
readOnly: true
{{- end }}
{{- if and (eq .Values.global.proxy.tracer "lightstep") .Values.global.tracer.lightstep.cacertPath }}
- mountPath: {{ directory .ProxyConfig.GetTracing.GetLightstep.GetCacertPath }}
name: lightstep-certs
readOnly: true
{{- end }}
{{- if isset .ObjectMeta.Annotations `sidecar.istio.io/userVolumeMount` }}
{{ range $index, $value := fromJSON (index .ObjectMeta.Annotations `sidecar.istio.io/userVolumeMount`) }}
- name: "{{ $index }}"
{{ toYaml $value | indent 4 }}
{{ end }}
{{- end }}
volumes:
{{- if (isset .ObjectMeta.Annotations `sidecar.istio.io/bootstrapOverride`) }}
- name: custom-bootstrap-volume
configMap:
name: {{ annotation .ObjectMeta `sidecar.istio.io/bootstrapOverride` "" }}
{{- end }}
- emptyDir:
medium: Memory
name: istio-envoy
{{- if .Values.global.sds.enabled }}
- name: sds-uds-path
hostPath:
path: /var/run/sds
- name: istio-token
projected:
sources:
- serviceAccountToken:
path: istio-token
expirationSeconds: 43200
audience: {{ .Values.global.sds.token.aud }}
{{- if .Values.global.sds.customTokenDirectory }}
- name: custom-sds-token
secret:
secretName: sdstokensecret
{{- end }}
{{- else }}
- name: istio-certs
secret:
optional: true
{{ if eq .Spec.ServiceAccountName "" }}
secretName: istio.default
{{ else -}}
secretName: {{ printf "istio.%s" .Spec.ServiceAccountName }}
{{ end -}}
{{- if isset .ObjectMeta.Annotations `sidecar.istio.io/userVolume` }}
{{range $index, $value := fromJSON (index .ObjectMeta.Annotations `sidecar.istio.io/userVolume`) }}
- name: "{{ $index }}"
{{ toYaml $value | indent 2 }}
{{ end }}
{{ end }}
{{- end }}
{{- if and (eq .Values.global.proxy.tracer "lightstep") .Values.global.tracer.lightstep.cacertPath }}
- name: lightstep-certs
secret:
optional: true
secretName: lightstep.cacert
{{- end }}
{{- if .Values.global.podDNSSearchNamespaces }}
dnsConfig:
searches:
{{- range .Values.global.podDNSSearchNamespaces }}
- {{ render . }}
{{- end }}
{{- end }}
injectedAnnotations:
values: '{"certmanager":{"enabled":false,"hub":"quay.io/jetstack","image":"cert-manager-controller","namespace":"istio-system","tag":"v0.6.2"},"clusterResources":true,"cni":{"namespace":"istio-system"},"galley":{"enableAnalysis":false,"enabled":false,"image":"galley","namespace":"istio-system"},"gateways":{"istio-egressgateway":{"autoscaleEnabled":true,"enabled":false,"env":{"ISTIO_META_ROUTER_MODE":"sni-dnat"},"namespace":"istio-system","ports":[{"name":"http2","port":80},{"name":"https","port":443},{"name":"tls","port":15443,"targetPort":15443}],"secretVolumes":[{"mountPath":"/etc/istio/egressgateway-certs","name":"egressgateway-certs","secretName":"istio-egressgateway-certs"},{"mountPath":"/etc/istio/egressgateway-ca-certs","name":"egressgateway-ca-certs","secretName":"istio-egressgateway-ca-certs"}],"type":"ClusterIP","zvpn":{"enabled":true,"suffix":"global"}},"istio-ingressgateway":{"applicationPorts":"","autoscaleEnabled":true,"debug":"info","domain":"","enabled":false,"env":{"ISTIO_META_ROUTER_MODE":"sni-dnat"},"meshExpansionPorts":[{"name":"tcp-pilot-grpc-tls","port":15011,"targetPort":15011},{"name":"tcp-citadel-grpc-tls","port":8060,"targetPort":8060},{"name":"tcp-dns-tls","port":853,"targetPort":853}],"namespace":"istio-system","ports":[{"name":"status-port","port":15020,"targetPort":15020},{"name":"http2","port":80,"targetPort":80},{"name":"https","port":443},{"name":"kiali","port":15029,"targetPort":15029},{"name":"prometheus","port":15030,"targetPort":15030},{"name":"grafana","port":15031,"targetPort":15031},{"name":"tracing","port":15032,"targetPort":15032},{"name":"tls","port":15443,"targetPort":15443}],"sds":{"enabled":false,"image":"node-agent-k8s","resources":{"limits":{"cpu":"2000m","memory":"1024Mi"},"requests":{"cpu":"100m","memory":"128Mi"}}},"secretVolumes":[{"mountPath":"/etc/istio/ingressgateway-certs","name":"ingressgateway-certs","secretName":"istio-ingressgateway-certs"},{"mountPath":"/etc/istio/ingressgateway-ca-certs","name":"ingressgateway-ca-certs","secretName":"istio-ingressgateway-ca-certs"}],"type":"LoadBalancer","zvpn":{"enabled":true,"suffix":"global"}}},"global":{"arch":{"amd64":2,"ppc64le":2,"s390x":2},"certificates":[],"configNamespace":"istio-system","configValidation":true,"controlPlaneSecurityEnabled":true,"defaultNodeSelector":{},"defaultPodDisruptionBudget":{"enabled":true},"defaultResources":{"requests":{"cpu":"10m"}},"disablePolicyChecks":true,"enableHelmTest":false,"enableTracing":false,"enabled":true,"hub":"docker.io/istio","imagePullPolicy":"IfNotPresent","imagePullSecrets":[],"istioNamespace":"istio-system","k8sIngress":{"enableHttps":false,"enabled":false,"gatewayName":"ingressgateway"},"localityLbSetting":{"enabled":true},"logAsJson":true,"logging":{"level":"default:warn"},"meshExpansion":{"enabled":false,"useILB":false},"meshNetworks":{},"mtls":{"auto":false,"enabled":false},"multiCluster":{"clusterName":"","enabled":false},"namespace":"istio-system","network":"","omitSidecarInjectorConfigMap":false,"oneNamespace":false,"operatorManageWebhooks":false,"outboundTrafficPolicy":{"mode":"ALLOW_ANY"},"policyCheckFailOpen":false,"policyNamespace":"istio-system","priorityClassName":"","prometheusNamespace":"istio-system","proxy":{"accessLogEncoding":"JSON","accessLogFile":"","accessLogFormat":"","autoInject":"disabled","clusterDomain":"cluster.local","componentLogLevel":"misc:error","concurrency":2,"dnsRefreshRate":"300s","enableCoreDump":false,"envoyAccessLogService":{"enabled":false},"envoyMetricsService":{"enabled":false,"tcpKeepalive":{"interval":"10s","probes":3,"time":"10s"},"tlsSettings":{"mode":"DISABLE","subjectAltNames":[]}},"envoyStatsd":{"enabled":false},"excludeIPRanges":"","excludeInboundPorts":"","excludeOutboundPorts":"","image":"proxyv2","includeIPRanges":"10.33.0.0/16,10.32.128.0/20","includeInboundPorts":"*","kubevirtInterfaces":"","logLevel":"warning","privileged":false,"protocolDetectionTimeout":"100ms","readinessFailureThreshold":30,"readinessInitialDelaySeconds":1,"readinessPeriodSeconds":2,"resources":{"limits":{"cpu":"500m","memory":"512Mi"},"requests":{"cpu":"100m","memory":"128Mi"}},"statusPort":15020,"tracer":"zipkin"},"proxy_init":{"image":"proxyv2","resources":{"limits":{"cpu":"100m","memory":"50Mi"},"requests":{"cpu":"10m","memory":"10Mi"}}},"sds":{"enabled":false,"token":{"aud":"istio-ca"},"udsPath":""},"securityNamespace":"istio-system","tag":"1.4.6","telemetryNamespace":"istio-system","tracer":{"datadog":{"address":"$(HOST_IP):8126"},"lightstep":{"accessToken":"","address":"","cacertPath":"","secure":true},"zipkin":{"address":""}},"trustDomain":"cluster.local","useMCP":false},"grafana":{"accessMode":"ReadWriteMany","contextPath":"/grafana","dashboardProviders":{"dashboardproviders.yaml":{"apiVersion":1,"providers":[{"disableDeletion":false,"folder":"istio","name":"istio","options":{"path":"/var/lib/grafana/dashboards/istio"},"orgId":1,"type":"file"}]}},"datasources":{"datasources.yaml":{"apiVersion":1}},"enabled":false,"env":{},"envSecrets":{},"image":{"repository":"grafana/grafana","tag":"6.4.3"},"ingress":{"enabled":false,"hosts":["grafana.local"]},"namespace":"istio-system","nodeSelector":{},"persist":false,"podAntiAffinityLabelSelector":[],"podAntiAffinityTermLabelSelector":[],"replicaCount":1,"security":{"enabled":false,"passphraseKey":"passphrase","secretName":"grafana","usernameKey":"username"},"service":{"annotations":{},"externalPort":3000,"name":"http","type":"ClusterIP"},"storageClassName":"","tolerations":[]},"istio_cni":{"enabled":false,"repair":{"enabled":true}},"istiocoredns":{"coreDNSImage":"coredns/coredns","coreDNSPluginImage":"istio/coredns-plugin:0.2-istio-1.1","coreDNSTag":"1.6.2","enabled":false,"namespace":"istio-system"},"kiali":{"contextPath":"/kiali","createDemoSecret":false,"dashboard":{"passphraseKey":"passphrase","secretName":"kiali","usernameKey":"username","viewOnlyMode":false},"enabled":false,"hub":"quay.io/kiali","ingress":{"enabled":false,"hosts":["kiali.local"]},"namespace":"istio-system","nodeSelector":{},"podAntiAffinityLabelSelector":[],"podAntiAffinityTermLabelSelector":[],"replicaCount":1,"security":{"cert_file":"/kiali-cert/cert-chain.pem","enabled":false,"private_key_file":"/kiali-cert/key.pem"},"tag":"v1.9"},"mixer":{"adapters":{"kubernetesenv":{"enabled":true},"prometheus":{"enabled":true,"metricsExpiryDuration":"10m"},"stackdriver":{"auth":{"apiKey":"","appCredentials":false,"serviceAccountPath":""},"enabled":false,"tracer":{"enabled":false,"sampleProbability":1}},"stdio":{"enabled":false,"outputAsJson":false},"useAdapterCRDs":false},"policy":{"adapters":{"kubernetesenv":{"enabled":true},"useAdapterCRDs":false},"autoscaleEnabled":true,"enabled":false,"image":"mixer","namespace":"istio-system","sessionAffinityEnabled":false},"telemetry":{"autoscaleEnabled":true,"enabled":false,"env":{"GOMAXPROCS":"6"},"image":"mixer","loadshedding":{"latencyThreshold":"100ms","mode":"enforce"},"namespace":"istio-system","nodeSelector":{},"podAntiAffinityLabelSelector":[],"podAntiAffinityTermLabelSelector":[],"replicaCount":1,"reportBatchMaxEntries":100,"reportBatchMaxTime":"1s","sessionAffinityEnabled":false,"tolerations":[],"useMCP":true}},"nodeagent":{"enabled":false,"image":"node-agent-k8s","namespace":"istio-system"},"pilot":{"appNamespaces":[],"autoscaleEnabled":true,"autoscaleMax":5,"autoscaleMin":1,"configMap":true,"configNamespace":"istio-config","cpu":{"targetAverageUtilization":80},"enableProtocolSniffingForInbound":false,"enableProtocolSniffingForOutbound":true,"enabled":true,"env":{},"image":"pilot","ingress":{"ingressClass":"istio","ingressControllerMode":"OFF","ingressService":"istio-ingressgateway"},"keepaliveMaxServerConnectionAge":"30m","meshNetworks":{"networks":{}},"namespace":"istio-system","nodeSelector":{},"podAntiAffinityLabelSelector":[],"podAntiAffinityTermLabelSelector":[],"policy":{"enabled":false},"replicaCount":1,"tolerations":[],"traceSampling":1,"useMCP":false},"prometheus":{"contextPath":"/prometheus","enabled":false,"hub":"docker.io/prom","ingress":{"enabled":false,"hosts":["prometheus.local"]},"namespace":"istio-system","nodeSelector":{},"podAntiAffinityLabelSelector":[],"podAntiAffinityTermLabelSelector":[],"replicaCount":1,"retention":"6h","scrapeInterval":"15s","security":{"enabled":true},"tag":"v2.12.0","tolerations":[]},"security":{"dnsCerts":{"istio-pilot-service-account.istio-control":"istio-pilot.istio-control"},"enableNamespacesByDefault":true,"enabled":true,"image":"citadel","namespace":"istio-system","selfSigned":true,"trustDomain":"cluster.local"},"sidecarInjectorWebhook":{"alwaysInjectSelector":[],"enableNamespacesByDefault":false,"enabled":true,"image":"sidecar_injector","injectLabel":"istio-injection","injectedAnnotations":{},"lifecycle":{},"namespace":"istio-system","neverInjectSelector":[],"nodeSelector":{},"objectSelector":{"autoInject":true,"enabled":false},"podAnnotations":{},"podAntiAffinityLabelSelector":[],"podAntiAffinityTermLabelSelector":[],"replicaCount":1,"resources":{},"rewriteAppHTTPProbe":false,"rollingMaxSurge":"100%","rollingMaxUnavailable":"25%","selfSigned":false,"tolerations":[]},"telemetry":{"enabled":true,"v1":{"enabled":true},"v2":{"enabled":false,"prometheus":{"enabled":true},"stackdriver":{"configOverride":{},"enabled":false,"logging":false,"monitoring":false,"topology":false}}},"tracing":{"enabled":false,"ingress":{"enabled":false},"jaeger":{"accessMode":"ReadWriteMany","enabled":false,"hub":"docker.io/jaegertracing","memory":{"max_traces":50000},"namespace":"istio-system","persist":false,"spanStorageType":"badger","storageClassName":"","tag":"1.14"},"nodeSelector":{},"opencensus":{"exporters":{"stackdriver":{"enable_tracing":true}},"hub":"docker.io/omnition","resources":{"limits":{"cpu":"1","memory":"2Gi"},"requests":{"cpu":"200m","memory":"400Mi"}},"tag":"0.1.9"},"podAntiAffinityLabelSelector":[],"podAntiAffinityTermLabelSelector":[],"provider":"jaeger","service":{"annotations":{},"externalPort":9411,"name":"http-query","type":"ClusterIP"},"zipkin":{"hub":"docker.io/openzipkin","javaOptsHeap":700,"maxSpans":500000,"node":{"cpus":2},"probeStartupDelay":200,"queryPort":9411,"resources":{"limits":{"cpu":"300m","memory":"900Mi"},"requests":{"cpu":"150m","memory":"900Mi"}},"tag":"2.14.2"}},"version":""}'
kind: ConfigMap
metadata:
annotations:
labels:
app: sidecar-injector
istio: sidecar-injector
operator.istio.io/component: Injector
operator.istio.io/managed: Reconcile
operator.istio.io/version: 1.4.6
release: istio
name: cm-test-toshi
```
2. Apply patch
```
$ kubectl patch configmap/cm-test-toshi --type merge -p '{
"data":{
"config":{
"template":{
"containers":[{
"name":"istio-proxy",
"lifecycle":{
"preStop":{
"exec":{
"command":["/bin/sh", "-c", "while [ $(netstat -plunt | grep tcp | grep -v envoy | wc -l | xargs) -ne 0]; do sleep 1; done"]
}
}
}
}]
}
}
}
}'
```
Anything else we need to know?:
===============================
Environment:
============
* Kubernetes version (use kubectl version): v1.14.10-dispatcher
* Cloud provider or hardware configuration: v1.14.10-gke.17 | 2020/04/09 | [
"https://Stackoverflow.com/questions/61116946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4156975/"
] | According to [kubernetes](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#alternate-forms-of-the-kubectl-patch-command) documentation:
>
> Alternate forms of the kubectl patch command
> --------------------------------------------
>
>
> The `kubectl patch` command takes YAML or JSON. It can take the patch as a file or directly on the command line.
>
>
> Create a file named `patch-file.json` that has this content:
>
>
>
> ```
> {
> "spec": {
> "template": {
> "spec": {
> "containers": [
> {
> "name": "patch-demo-ctr-2",
> "image": "redis"
> }
> ]
> }
> }
> }
> }
>
> ```
>
> The following commands are equivalent:
>
>
>
> ```sh
> kubectl patch deployment patch-demo --patch "$(cat patch-file.yaml)"
> kubectl patch deployment patch-demo --patch 'spec:\n template:\n spec:\n containers:\n - name: patch-demo-ctr-2\n image: redis'
>
> kubectl patch deployment patch-demo --patch "$(cat patch-file.json)"
> kubectl patch deployment patch-demo --patch '{"spec": {"template": {"spec": {"containers": [{"name": "patch-demo-ctr-2","image": "redis"}]}}}}'
>
> ```
>
>
The method You are trying to use is not supported.
So You can use `gsed` to stream the data as You mentioned. Or convert to a template like suggested from documentation. Or put the data into a file and `cat` it like in example above.
Hope it helps. |
31,439,780 | I have an `OnClickListener` in a fragment activity as shown here:
```
public class Menu1_Fragment extends Fragment {
Button CreateGroupButton;
View rootview;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
CreateGroupButton = (Button) rootview.findViewById(R.id.create_study_group);
CreateGroupButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Toast.makeText(getActivity().getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Menu1_Fragment.this.getActivity(), CreateGroup.class);
startActivity(intent);
}
});
return rootview;
}
}
```
Here is my `menu1_layout.xml` code:
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button
android:id="@+id/create_study_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/CreateGroupBtn"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is the page where you can create and view existing groups"
android:id="@+id/textView"
android:layout_below="@+id/create_study_group"/>
</RelativeLayout>
```
When the `Button` is clicked, the "Test" message is displayed but the app closes right after.
Here is the `CreateGroup` java class:
```
public class CreateGroup extends Fragment{
View rootview;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.create_group, container, false);
return rootview;
}
}
```
and the `create_group.xml` file:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is the page where the form is displayed"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
```
NavigationActivity:
```
public class NavigationActivity extends FragmentActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
FragmentManager fragmentManager = getSupportFragmentManager();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager =getSupportFragmentManager();
Fragment fragment= new Fragment();
switch (position){
case 0:
mTitle = getString(R.string.title_section1);
fragment = new Menu1_Fragment();
break;
case 1:
mTitle = getString(R.string.title_section2);
fragment = new Menu2_Fragment();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.navigation, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//if the log out button is selected, log out of Parse and go back to log in page
if (id == R.id.action_logout) {
ParseUser.logOut();
Intent intent = new Intent(NavigationActivity.this,LoginSignupActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Successfully Logged out", Toast.LENGTH_LONG).show();
finish();
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((NavigationActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
```
I'm having trouble figuring out why the `CreateGroup` class/layout file aren't being displayed as a new page. | 2015/07/15 | [
"https://Stackoverflow.com/questions/31439780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4695308/"
] | The CreateGroup class is a fragment , the intent should be using an activity if startActivity is being used |
195,944 | Alright, so while coming up with a way for adventurers in my world to obtain dragons, I decided that the drop mechanic system (please see [Preventing Dead Monsters From Spawning Undead](https://worldbuilding.stackexchange.com/questions/195344/preventing-dead-monsters-from-spawning-undead) for more on how that system works) would turn rocks or gems (which I count as rocks) in a dragon's body into dragon eggs upon death.
However, that poses a bit of a problem: sooner than later, the dragons will realize that if one of their own is killed with rocks inside them that their slayers will be able to collect some dragon eggs in result. Now it seems rather obvious that this is UNACCEPTABLE, since the people who normally kill dragons are either dragonslayers (duh) or adventurers, and they can't be trusted with dragon eggs.
Dragonslayers are likely to either destroy the eggs or use them in making food (omelets, cakes, and so forth) while adventurers are generally slightly crazy and like money, so they'll either sell the eggs to make some quick cash, hatch the eggs and raise the dragonlings as "companions", or train/breed/sell the hatchlings much like humans (likely) did anciently to domesticate wolves.
Never mind all that, and one still has a problem; the dragon's new children are left worse than defenseless, at the mercy of whoever killed the dragon or perhaps whoever outruns the slayer to collect the eggs. That being said, my question is simple: **Why Would A Dragon Leave Eggs For Their Slayers?**
**Specifically,** why would a dragon swallow rocks or gems knowing they would become dragon eggs if they were killed by someone, or just died in their sleep? They don't have gizzards, and they can reproduce normally, so that's right out....is there even a plausible reason for dragons to do this?
As always, I appreciate your input and feedback, thanks in advance. If you choose to VTC or close-vote, please give me an explanation so I can improve the question. | 2021/02/12 | [
"https://worldbuilding.stackexchange.com/questions/195944",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/80953/"
] | Biology is Cruel and the Logic is Ruthless:
-------------------------------------------
As a biologist, I have to say that nature is ruthless, cruel, and indiscriminate. Survival isn't of the fittest, but of the survivors. So there is a grim logic to leaving offspring in the hands of those who kill you. Even abandoning them is better than them never existing.
If you leave NO offspring, you don't survive. Period. Gone. No more dragons. So if adventurers are strong enough to kill a dragon, then they are strong enough to protect and raise a dragon. Yes, some will die. Biology is ruled by ruthless numbers. A hundred eggs destroyed that would have been destroyed or not existed anyway means no loss. So if one in a hundred survives as a pet, or domesticated dragon, or a good friend to a dragon slayer, then the dragon has passed on it's genes. **The dragon who DOESN'T pass on their genes this way is at a disadvantage.** If all the wild dragons were wiped out, only those in captivity would exist, and dragons would live on.
IF, however, these domesticated dragons threaten their own species survival (like dragons being used to track and kill other dragons) then the survival of these individuals DOES damage the species as a whole. But these captive dragons may become a useful sub-species and no longer consider themselves the same as wild dragons. You may have laws against keeping sentients as slaves, and if so then the only way to have a dragon is to raise it like a child and let it be free.
So swallow those stones, dragon brethren. Let mother nature take her shot and see what will be. The alternative is to risk extinction. |
22,440,809 | My console is giving the following error when trying to run an Android Project in Eclipse.
>
> WARNING: Application does not specify an API level requirement! Device
> API version is 15 (Android 4.0.4) Installation error: Unknown failure
> Please check logcat output for more details. Launch canceled!
>
>
>
I checked the logcat as suggested and there doesn't really seem to be that information in there. All it says is:
>
> D/AndroidRuntime( 5039): >>>>>> AndroidRuntime START
> com.android.internal.os.RuntimeInit <<<<<< D/AndroidRuntime( 5039):
> CheckJNI is OFF I/ethernet( 5039): Loading ethernet jni class
> D/AndroidRuntime( 5039): Calling main entry com.android.commands.pm.Pm
> D/AndroidRuntime( 5039): Shutting down VM D/dalvikvm( 5039):
> GC\_CONCURRENT freed 97K, 83% free 444K/2560K, paused 0ms+0ms
> D/dalvikvm( 5039): Debugger has detached; object registry had 1
> entries I/AndroidRuntime( 5039): NOTE: attach of thread 'Binder Thread
> #1' failed
>
>
>
Would you guys have any suggestions on what I could do to get this sorted out? I'm really new to Java/Android development but trying to learn. | 2014/03/16 | [
"https://Stackoverflow.com/questions/22440809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3276588/"
] | That pointcut will match public methods in Spring AOP. So getters and setters, but not constructors.
The Spring reference for this is [here](http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/aop.html). Section 8.2.3, look for "even constructors".
A clean way to only reference a group of methods is to apply the pointcut to an interface implemented by your service, instead of the service itself. This assumes your interface only contains business methods you want to advise. |
355,695 | Let $\mathcal V$ be a good enriching category. Recall that an enriched limit weight $\phi: D \to \mathcal V$ is called [absolute](https://ncatlab.org/nlab/show/absolute+colimit) if $\phi$-weighted limits are preserved by any $\mathcal V$-enriched functor whatsoever. If this is a familiar concept, please jump to my question at the end. But otherwise, I will provide some context. For instance,
* Idempotent splitting is absolute for $Set$-enrichment and (hence) for any enriching category;
* Finite products are absolute for enrichment in abelian groups, commutative monoids, etc;
* Limits of Cauchy sequences are absolute for enrichment in $([0,\infty],\geq,+)$;
* $\infty$-categorically, finite limits are absolute for enrichment in spectra;
* Eilenberg-Moore objects for idempotent monads are absolute for enrichment in $Cat$.
There are a number of general things to say here:
* ([Street](https://eudml.org/doc/91335)) A $\mathcal V$-weight $\phi: D \to \mathcal V$ is absolute if and only if $\phi$ has a left adjoint $\bar \phi: D^{op} \to \mathcal V$ in the bicategory of $\mathcal V$-categories and $\mathcal V$-profunctors.
* Following Lawvere and the third example above, a $\mathcal V$-category with all absolute $\mathcal V$-limits is called [Cauchy complete](https://ncatlab.org/nlab/show/Cauchy+complete+category). The *Cauchy completion* of a $\mathcal V$-category $C$ is obtained by freely adjoining absolute $\mathcal V$-limits to $C$, and may be constructed as the $\mathcal V$-category of absolute weights on $C$. This construction exhibits the Cauchy complete $\mathcal V$-categories as a reflective subcategory of $\mathcal V\text{-}Cat$.
* Thus a $\mathcal V$-weight $\phi: D \to \mathcal V$ is absolute if and only if it lies in the Cauchy completion of $D$.
These general facts are useful in working out explicit characterizations of the absolute weights for particular $\mathcal V$:
* An ordinary ($Set$-enriched) category $C$ is Cauchy-complete iff $C$ has all split idempotents; a $Set$-enriched weight $\phi: D \to \mathcal V$ is absolute iff it is a retract of a representable (and in particular an ordinary conical limit is absolute iff the indexing diagram has a cofinal idempotent);
* An $Ab$-enriched category $C$ is Cauchy-complete iff $C$ has split idempotents and finite products;
* A generalized metric space is Cauchy-complete iff it is Cauchy-complete in the usual sense;
* A spectrally-enriched $\infty$-category is Cauchy-complete iff it is stable with split idempotents;
But I don't know an analogous statement for $Cat$-enrichment.
>
> **Question:** When does a 2-category $C$ have all absolute weighted 2-limits?
>
>
>
Clearly $C$ must have split idempotents and Eilenberg-Moore objects for idempotent monads -- do these suffice? Or are there more absolute 2-limit weights out there which can't be built from these? | 2020/03/25 | [
"https://mathoverflow.net/questions/355695",
"https://mathoverflow.net",
"https://mathoverflow.net/users/2362/"
] | In my paper [Condensations in higher categories](https://arxiv.org/abs/1905.09566) joint with Davide Gaiotto, we claim the following answer. It deserves someone to write a careful model-dependent paper confirming it. I believe Martin Szyld has been thinking about how to do this.
Define a *2-idempotent* to be an endomorphism $e : X \to X$ together with a retract $\mu: e^2 \Leftrightarrow e : \mu^\*$, by which I mean 2-morphisms $\mu$ and $\mu^\*$ such that $\mu \cdot \mu^\* = \mathrm{id}\_e$, which is associative, coassiciative, and Frobenius. [In spite of the name "$\mu^\*$", it is just another 2-morphism, and isn't required to be the adjoint or dual in any sense beyond the requirement $\mu \cdot \mu^\* = \mathrm{id}\_e$. In particular, $\mu$ constrains but does not determine $\mu^\*$.]
By *Frobenius* I mean that the three natural maps $e^2 \Rightarrow e^2$, namely $\mu^\* \cdot \mu$, $(\mu \circ \mathrm{id}\_e) \cdot \mathrm{assoc} \cdot (\mathrm{id}\_e \circ \mu^\*)$, and $(\mathrm{id}\_e \circ \mu) \cdot \mathrm{assoc}^{-1} \cdot (\mu^\* \circ \mathrm{id}\_e)$, are all equal. [Actually, the Frobenius axiom together with $\mu \cdot \mu^\* = \mathrm{id}\_e$ imply the associativity of $\mu$ and coassociativity of $\mu^\*$.] Here my notation is that $\circ$ is the composition in the 1-morphism direction, and $\cdot$ for 2-morphisms, and $\mathrm{assoc} : e \circ e^2 \cong e^2 \circ e$ is the associator.
This same notion goes by many names. For instance, it is a nonunital separated monad, or a nonunital special Frobenius monad. It is almost but not quite the same as "separable monad" used by Douglas and Reutter. In our paper, we give it yet another name — "condensation monad". But Reutter and I have started saying "2-idempotent" when we talk to each other, and perhaps it is the best name.
A 2-idempotent $(X,e,\dots)$ *splits* when there is an object $Y$, 1-morphisms $f : X \leftrightarrows Y: f^\*$ [again, in spite of the name, I don't require any duality/adjunction], and some 2-morphisms and equations which I will list. First, I require the data of a retract $\phi : f\circ f^\* \Leftrightarrow \mathrm{id}\_Y : \phi^\*$, i.e. 2-morphisms such that $\phi \cdot \phi^\* = \mathrm{id}\_{\mathrm{id}\_Y}$. Now, using the retract $(\phi,\phi^\*)$, I claim that you can give the composition $f^\*\circ f$ the data of a 2-idempotent. Specifically, you set $\mu : (f^\* \circ f) \circ (f^\* \circ f) \Rightarrow (f^\* \circ f) \circ (f^\* \circ f)$ to be what you get by using an assotiator $(f^\* \circ f) \circ (f^\* \circ f) \cong f^\* \circ (f \circ f^\*) \circ f$ and then applying $\mathrm{id}\_{f^\*} \circ \phi \circ \mathrm{id}\_f$ and then applying some unitors; and $\mu^\*$ is the reverse. The last datum needed to say that $(X,e,\dots)$ splits is an isomorphism $e \cong f^\* \circ f$ of 2-idempotents on $X$.
To connect with things you know: 2-idempotents are a version of monads, and splittings are a version of Eilenberg–Moore objects. The difference is that mine are not unital and are separable, in fact separated.
Then our claim is that a weak 2-category is Cauchy complete when (and only when) it is locally idempotent complete [i.e. all hom-categories are idempotent complete] and also every 2-idempotent splits. If your 2-category is locally idempotent, then a splitting of a 2-idempotent is unique up to unique isomorphism. I forget if this is true without local idempotent completion.
---
We also claim an explicit construction of the 2- (indeed, $n$-)categorical Karoubi completion. Given any 2-category, the first step is to locally Karoubi complete it. [Easy exercise: write down the 1-morphism composition in the local Karoubi-completion of a 2-category.] Now given a locally Karoubi complete 2-category $\mathcal{C}$, I build a new 2-category whose objects are the 2-idempotents in $\mathcal{C}$. A morphism $(X,e,\dots) \to (Y,f,\dots)$ is a morphism $m : X \to Y$ together with retracts $m\circ e \Leftrightarrow m$ and $f \circ m \Leftrightarrow m$ such that a bunch of equations hold making $m$ into a bimodule and bicomodule and cetera. A "bi-bimodule", perhaps? The 2-morphisms are natural: they are the homomorphisms of these bi-bimodules.
The interesting thing is the composition. Given $(m, \dots) : (X,e,\dots) \to (Y,f,\dots)$ and $(n, \dots) : (Y,f,\dots) \to (Z,g,\dots)$, I can look at $n \circ m : X \to Z$. Now I claim you can write down an idempotent $n \circ m \Rightarrow n\circ m$. The trick is to map $n \circ m \Rightarrow n \circ f \circ m \Rightarrow n \circ m$ where you use the $f$-coaction on $m$, and then the $f$-action on $n$. Well, you could have used the $f$-coaction on $n$ and then the $f$-action on $m$, but it turns out you will get the same thing. Since your 2-category is by assumption locally idempotent complete, you can split this idempotent. Actually, $n \circ m$ was already a bi-bimodule, and the idempotent you write down on it is a moprhism of bi-bimodules. So the splitting is a bi-bimodule. This is the composition in the 2-Karoubi completion.
You can see that to write this down as a bicategory, say, would require making some arbitrary choices: I just told you "split the thing", and not which splitting to take, so even if you started life as a strict 2-category, you won't end up strict, and you should not expect our construction to lead to any statement of the form "this is the Cauchy completion" in the world of strict 2-categories and their functors. |
33,847,436 | I have this XML:
```
<root>
<experiment accessCount="1" downloadCount="1">alfa</experiment>
<experiment accessCount="1" downloadCount="1">beta</experiment>
</root>
```
And I would like to detect if the node experiment with value alfa exists.
But this PHP code is returning to me all values.
```
$this->xml = simplexml_load_file("data/stats.xml") or die("Error: Cannot create object");
$node = $this->xml->xpath("/root[experiment='alfa']");
```
Where am I wrong? | 2015/11/21 | [
"https://Stackoverflow.com/questions/33847436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4047348/"
] | **Your XPath,**
```
/root[experiment='alfa']
```
**says:**
>
> *Select the `root` element that contains an `experiment` element with string value equal to `'alfa'`.*
>
>
>
There is one such `root` element in your example, and it contains ***both*** `experimental` elements.
---
**This XPath,**
```
/root/experiment[.='alfa']
```
**says:**
>
> *Select the `experiment` element with string value equal to `'alfa'`.*
>
>
>
And will select the one `experiment` element you seek. |
1,239,208 | I wrote this code:
```
public class FileViewer extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JFileChooser chooser;
FileNameExtensionFilter filter = null;
JEditorPane pane = null;
JTextField text = null;
JButton button;
JTextArea o = null;
URL url;
public FileViewer(JTextArea o) {
this.o = o;
setLayout(new FlowLayout(FlowLayout.RIGHT));
JTextField text = new JTextField("file...", 31);
text.setColumns(45);
text.revalidate();
text.setEditable(true);
button = new JButton("Browse");
add(text);
add(button);
filter = new FileNameExtensionFilter("html", "html");
chooser = new JFileChooser();
chooser.addChoosableFileFilter(filter);
button.addActionListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D graphic = (Graphics2D) g;
graphic.drawString("HTML File:", 10, 20);
}
public void actionPerformed(ActionEvent event) {
int returnVal = 0;
if (event.getSource() == button) {
returnVal = chooser.showOpenDialog(FileViewer.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
text.setToolTipText(chooser.getSelectedFile().getName());
} else
o.append("Open command cancled by user.");
}
}
}
```
But in the line: `text.setToolTipText(chooser.getSelectedFile().getName());` a NullPointerException is thrown!
**EDIT**
I have fixed the problem which I have mentioned above but it doesn't work correctly (it doesn't write the name of the file in the text!) :-( | 2009/08/06 | [
"https://Stackoverflow.com/questions/1239208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124339/"
] | You've declared `text` globally and assigned `NULL` to it. In your constructor for `FileViewer` you declare it again with `new`, but this declaration is local. The variable referenced in `actionPerformed()` is the global one, which is still `NULL`, so you get the exception. If you change
```
JTextField text = new JTextField("file...", 31);
```
to
```
text = new JTextField("file...", 31);
```
that should fix it. |
12,190,382 | I have the following in my `user/Preferences.sublime-settings`
```
{
"tab_size": 2,
}
```
And most of the time it works. But once in a while I open a ruby file, and it jumped back to 4 spaces. I'm wondering if there is some bug or slight difference in opening a file that could change this?
Having trouble tracking this down. Thanks for the help. | 2012/08/30 | [
"https://Stackoverflow.com/questions/12190382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76486/"
] | You'll want to add:
```
"detect_indentation": false
```
This is on by default and ST is trying to be smart detecting the indentation of your current file, overloading the user or syntax specific default. |
34,604 | Here is the sentence said by Kansai speaker who was capturing 2 boys who were chasing another guy.
**まちいな** あんさんたち。
I think the word would mean 待つ with particle な emphasizing the emotion but I would like to know what the exact Japanese standard dialect form of the word really is. | 2016/06/03 | [
"https://japanese.stackexchange.com/questions/34604",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/9559/"
] | In some dialects spoken in the western part of Japan, you can elongate the last vowel of the masu-stem to make an imperative form:
>
> * 歩きい。 (dialect) = 歩け。 Walk.
> * 見い。 (dialect) = 見ろ。 Watch.
> * **[待ちい]{LHL}。** (dialect) = [待て]{HL}。 Wait.
> * [食べえ]{LHL}。 (dialect) = [食べろ]{LHL}。 Eat.
>
>
>
(From my personal experience, I feel this is mainly used in Chugoku/Shikoku region, but I may be wrong. See [西日本方言#文法](https://ja.wikipedia.org/wiki/%E8%A5%BF%E6%97%A5%E6%9C%AC%E6%96%B9%E8%A8%80#.E6.96.87.E6.B3.95))
You can attach various sentence-end particles like な, や, or よ, as usual.
(Attaching な to this kind of imperative may be specific to Osaka dialect. I found this article: [「大阪方言の命令形」に後接する終助詞ヤ・ナ](http://ir.library.osaka-u.ac.jp/dspace/bitstream/11094/4642/1/21-05.pdf) (PDF))
>
> * すぐ来【き】いや。 (dialect) = すぐ来【こ】いよ。 Come at once.
> * はよう寝えよ。 (dialect) = はやく寝ろよ。 Go to bed now.
> * **[待ちいな]{LHLL}。** (dialect) = [待てよ]{HLL}。 Wait.
>
>
>
Note that you can use な to form *positive* imperative in *standard* Japanese, too. But the last vowel of the masu-form is not elongated in the standard Japanese. Also see the difference in accents.
[Using な in positive instead of negative imperative (e.g. 行きな)](https://japanese.stackexchange.com/questions/2707/)
>
> * [待ちな]{LHH}。 = [待て]{HL}。
> * [食べな]{LHH}。 = [食べろ]{LHL}。
>
>
> |
4,519,324 | I have a web form with usual elements (first name, last name, etc). The Postback URL is a different website altogether as the form is intented to post lead information to another website.
The site that accepts the lead is expecting First Name to come over as "FName", and Last Name to come over as "LName". Is there any way I can set the ID of a textbox to "txtFName", but submit it over the wire as "FName"? I tried changing the name attribute, but at runtime it sets the name = id. | 2010/12/23 | [
"https://Stackoverflow.com/questions/4519324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382214/"
] | You should use normal (non-`runat="server"`) `<input>` elements.
You will then have complete control over the name and id. |
348,739 | Anything involving tensors has 47 different names and notations, and I am having trouble getting any consistency out of it.
This document (<http://www.polymerprocessing.com/notes/root92a.pdf>) clearly ascribes to the colon symbol (as "double dot product"):
$\mathbf{T}:\mathbf{U}=T\_{ij} U\_{ji}$
while this document (<http://www.foamcfd.org/Nabla/guides/ProgrammersGuidese3.html>) clearly ascribes to the colon symbol (as "double inner product"):
$\mathbf{T}:\mathbf{U}=T\_{ij} U\_{ij}$
Same symbol, two different definitions. To make matters worse, my textbook has:
$\mathbf{\epsilon}:\mathbf{T}$
where $\epsilon$ is the Levi-Civita symbol $\epsilon\_{ijk}$ so who knows what that expression is supposed to represent.
Sorry for the rant/crankiness, but it's late, and I'm trying to study for a test which is apparently full of contradictions. Any help is greatly appreciated. | 2013/04/02 | [
"https://math.stackexchange.com/questions/348739",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/25733/"
] | Sorry for such a late reply. I hope you did well on your test. Hopefully this response will help others.
The "double inner product" and "double dot product" are referring to the same thing- a double contraction over the last two indices of the first tensor and the first two indices of the second tensor. A double dot product between two tensors of orders m and n will result in a tensor of order (m+n-4).
So, in the case of the so called permutation tensor (signified with epsilon) double-dotted with some 2nd order tensor T, the result is a vector (because 3+2-4=1).
You are correct in that there is no universally-accepted notation for tensor-based expressions, unfortunately, so some people define their own inner (i.e. "dot") and outer (i.e. "tensor") products. But, this definition for the double dot product that I have described is the most widely accepted definition of that operation.
Hope this helps. |
57,517,586 | I am working on a project that will take user input value from an HTML form and then convert such values from one base to the other. I have been trying for hours without success. I have created five Html input types. One for the number to be converted. Two for the base to be converted from. Three for the base to be converted to. Four, a text box for displaying the result and finally a button which the user will click to run the process. I will put the code below for warm assistance. Thanks all in advance.
I tried PHP isset method, !empty, settype, post but all did not work
```
<form method="POST" name="btnN" id="chr"class="myfm" action=" <?php htmlspecialchars($_SERVER['PHP_SELF']);?>">
<span style="color:white">From number:</span> <br><input type="text" name="screen1" ><br><br>
<span style="color:white">From base:</span> <br><input type="text" name="screen2"><br><br>
<span style="color:white">To base:</span> <br><input type="text" name="screen3"><br><br>
<span style="color:white">Result:</span> <br><input type="text" name="screen" ><br><br>
<input name="conver" type="button" value="Convert" onclick="btnN.screen.value='<?php echo $converted; ?>'" style="width:50%" >
</form>
<?php
$screen1=settype($_POST['screen1']);
$screen2= settype($_POST['screen2']);
$screen3=settype($_POST['screen3']);
do{
$screen1=settype($screen1,"integer");
$screen2=settype($screen2,"integer");
$screen3=settype($screen3,"integer");
$converted= base_convert($screen1,$screen2,$creen3);
}
while(isset($_POST['conver']));
?>
```
All that I want is, to have an HTML form with text boxes where the user can enter the number he or she wants to convert from a specified base to another specified base. example converting 12548 from base10 to base5. My main problem is with the PHP codes. Thanks for helping! | 2019/08/16 | [
"https://Stackoverflow.com/questions/57517586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11412956/"
] | What are you using in section:
```
String SMTP_USERNAME = "smtp_username";
String SMTP_PASSWORD = "smtp_password";
```
The Sending authorization policy looks correct and more ever it is not required if your ses-smtp-user and SES verified domain in the same account, you need to make sure that you're using the credentials you created from SES console --> SMTP settings --> Credentials.
Since you're using SMTP, SMTP credentials are required, it won't work if you're using normal IAM access key and secret key. The SMTP access and secret keys should be created from SES console. |
61,074 | In [this link](https://avherald.com/h?article=4c497c3c&opt=0) I read about the crashed aircraft:
>
> The airplane then pitched nose down over the next 18 seconds to about 49° in response to nose-down elevator deflection.
>
>
>
I feel that this is a common mechanism, unknown to non-expert, like me. What does it mean?
Interested in a rather intuitive, relaxed explanation, rather than an analytical one. | 2019/03/13 | [
"https://aviation.stackexchange.com/questions/61074",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/8887/"
] | There are a few words in that description which might seem a bit technical to a lay-person.
The word "pitch" refers to the angle of the aircraft, either up or down.
>
> pitch: (of a moving ship, aircraft, or vehicle) rock or oscillate around a lateral axis, so that the front moves up and down.
>
>
>
"49°" refers to the angle from the horizontal (0°). 49° is a *very* steep decent. Much more so than a normal descent profile.
The "elevator" is the control surface used on an aircraft to control the pitch, either up or down. So "nose-down elevator deflection" says that the elevator position were such that the aircraft is pointing down. The implication/possibility is that the controls in the cockpit were commanding that input, or that a mechanical fault caused the elevators to do so. |
362,173 | I understand that when I open a terminal emulator like `xterm`, and then list the processes using `ps`, I can see `xterm` running as a process.
But when I type Ctrl+Alt+F#, I get a "full screen terminal", is this "full screen terminal" also a process? or is it a UI provided by the kernel without being an actual process? | 2017/04/29 | [
"https://unix.stackexchange.com/questions/362173",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/229242/"
] | Unlike regular terminal emulators, this full screen terminal is not handled by a userland process but, as you guessed, provided by the kernel.
See [Virtual console](https://en.wikipedia.org/wiki/Virtual_console) |
9,495,432 | I've created UIImageView with tableView and put this view on another view. But my table isn't enabled. I can't press on the cell or scroll my table. | 2012/02/29 | [
"https://Stackoverflow.com/questions/9495432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/631792/"
] | You should add the
```
runat="server"
```
attribute to the text area.
Or, preferable you should use the [`TextBox` ASP.NET control](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx) and set the [`TextMode` property](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.textmode.aspx) to `TextBoxMode.MultiLine`. Example follows:
Code behind:
```
Output1.Text = Output.ToString();
```
ASP:
```
<div style ="width: 78%; float: right; height: 85px; display: block;"
class="message_text_box_left">
<asp:TextBox ID="Output1" Rows="3"
CssClass="message_text_box" ToolTip="Share your ideas here..."
TextMode="MultiLine" />
</div>
``` |
798 | The billing software I use to keep track of my hours/clients/invoices etc. is no longer supported by the manufacturer, and I have to find something else. Is it off-topic here to ask for a suggestion? While it's not strictly about writing, anyone who writes/edits for a living in any capacity does have to keep track of money. | 2014/02/20 | [
"https://writers.meta.stackexchange.com/questions/798",
"https://writers.meta.stackexchange.com",
"https://writers.meta.stackexchange.com/users/553/"
] | This sounds like a case of [boat programming](https://meta.stackexchange.com/a/14486/162102) -- in this case, you're asking what's the best way to manage your billing *as a writer*, but the "as a writer" part isn't actually important to the question. You could ask the same question "as a contract programmer", "as a plumber", "as a private flight instructor", or whatever and you'd get the same answers. So my instinct would be that it's off-topic, quite aside from whether it's a list question.
However, if there *are* aspects of the question that are specific to writers, a question that focuses on those particular issues could be on-topic. |
26,245 | I'm looking for a C# PDF generation library compatible with windows 8.1 apps. Is there any free for commercial use solution? | 2015/11/05 | [
"https://softwarerecs.stackexchange.com/questions/26245",
"https://softwarerecs.stackexchange.com",
"https://softwarerecs.stackexchange.com/users/19196/"
] | If you want to go with using a commercial product, you should check out the [LEADTOOLS PDF SDK](https://www.leadtools.com/sdk/pdf-pro). You can use the LEADTOOLS libraries to simply convert any previous documents that you have to a PDF format.
The easiest way of doing so would be to load your original document using our [RasterCodecs.Load()](https://www.leadtools.com/help/leadtools/v19/dh/co/leadtools.codecs~leadtools.codecs.rastercodecs~load.html) method then save using the [RasterCodecs.Save()](https://www.leadtools.com/help/leadtools/v19/dh/co/leadtools.codecs~leadtools.codecs.rastercodecs~save(rasterimage,string,rasterimageformat,int32).html) method and specifying the output as a PDF.
Just to show how simple this can be done here is a code snippet of the process:
```
RasterCodecs codecs = new RasterCodecs();
RasterImage image = codecs.Load(<PATH TO FILE LOCATION>);
codecs.Save(image, <DESTINATION PATH>, RasterImageFormat.RasPdf, 0);
```
Disclaimer: I am an employee of this product |
30,334,421 | I am interested in taking my C++ program and cross compiling it into something that can run on an ARM MCU. To do this, I am required to have `gcc-arm-none-eabi` installed. I'm currently on a Windows 7 machine, and so I have installed GCC/make/g++/etc. via MinGW.
From the research I've done, it seems that MinGW does not support this toolchain, which leads me to believe that Windows-based ARM development isn't possible. So I ask: how does one use MinGW to install the `gcc-arm-none-eabi` toolchain locally? | 2015/05/19 | [
"https://Stackoverflow.com/questions/30334421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4009451/"
] | You can use MinGW for this; you just need to swap out the C++ toolchain for your chosen one. You can still invoke it from the MSYS console, and all your other tools will still work. There's nothing inherent to MinGW or MSYS that makes this "not supported".
Personally I install [GCC 4.9 *gcc-arm-none-eabi* from launchpad.net](https://launchpad.net/gcc-arm-embedded/4.9/4.9-2014-q4-major/+download/gcc-arm-none-eabi-4_9-2014q4-20141203-win32.exe), mount the toolchain's directory in MSYS then export the paths I need:
```
mount 'C:\PROGRA~2\GNUTOO~1\4947E~1.920' /foo
mount 'C:\PROGRA~2\GNUTOO~1\4947E~1.920\ARM-NO~1' /foo_local
```
To discover the short name for the paths, write `dir /X` at the Windows command prompt. On my machine, the paths above are equivalent to the following, respectively:
* `C:\Program Files (x86)\GNU Tools ARM Embedded\4.9 2014q4`
* `C:\Program Files (x86)\GNU Tools ARM Embedded\4.9 2014q4\arm-none-eabi`
The mounting only needs to be done once; the `export` directives may be added to `/etc/profile`:
```
export CPPFLAGS="-I/foo_local/include"
export CFLAGS="-I/foo_local/include"
export CXXFLAGS="-I/foo_local/include"
export LDFLAGS="-L/foo_local/lib -mthreads"
export PATH=".:/foo_local/bin:/foo/bin:/bin:/opt/bin"
```
Then just run `g++`.
Or of course you can skip all the export business and just invoke your chosen GCC directly:
```
/foo/bin/g++
``` |
9,751,249 | the following code
```
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setFirstWeekday:2];
[cal setMinimumDaysInFirstWeek:4];
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setYear: 2012];
[comp setMonth:3];
[comp setDay: 12];
NSDate *date = [cal dateFromComponents:comp];
NSLog(@"date:%@",date);
```
logs:
```
date:2012-03-11 23:00:00 +0000
```
Any Idea, why this happen and how to avoid
Tnx | 2012/03/17 | [
"https://Stackoverflow.com/questions/9751249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1165251/"
] | If you adjust your rules for IE7 in stylesie.css, then it should be loaded *after* your original css file:
```
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="/css/stylesie.css" />
<![endif]-->
```
Rules for a selector with the same [specificity](http://www.w3.org/TR/selectors/#specificity) will overwrite old ones, so IE7 will parse stylesie.css first and overwrite those rules with the ones from styles.css.
[Basic example of this behavior:](http://jsfiddle.net/YYpUj/)
```
div, div.red{
color:red;
}
div{
color:blue;
}
```
This will result in a blue color in all `<div>`, except the one tagged with the class `red`. |
32,809,056 | This is my first question on StackOverflow and I hope someone can help me. :-)
I am planning to build a web-application (backend) with spring roo. For the backend I will use Spring and Hibernate/JPA. In the future I will implement a web client (JSF/Primefaces), a mobile client (Android) and a Windows App.
With spring roo it is easy to create a layered architecture with domain classes, repositories and services. This part is fun.
But now I am thinking about remoting and how to connect all the clients (web, mobile, windows) with my backend.
**1.) What do you prefer for the remoting between client and backend? SOAP-Web Services or a REST-API (e.g. with JSON).**
**2.) If REST-API: How should the API look like for authentication/login functionality? REST is resource-oriented but how do you implement authentication with REST API?**
At the moment I think a REST-API is a good idea. Because I am using spring it is easy to create a Spring MVC controller with REST support. But is this the correct way to implement a REST API for all the three devices? The web client e.g. should be implemented with JSF and Primefaces and I don´t use spring MVC for the web layer.
**3.)Can I nevertheless use Spring MVC controllers to build the REST API (together with JSF in the web layer)? Or is there a better way?** | 2015/09/27 | [
"https://Stackoverflow.com/questions/32809056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5381712/"
] | **1.) What do you prefer for the remoting between client and backend? SOAP-Web Services or a REST-API (e.g. with JSON).**
I don't have too much experience with SOAP-WS, but I have a ton of experience with REST-APIs using JSON. There are many implementations for mobile, web and server side clients that are fairly simple to implement.
**2.) If REST-API: How should the API look like for authentication/login functionality? REST is resource oriented but how to implement authentication with REST API?**
If you are already using spring, I recommend securing your API with Spring Security. You can use spring security even if you don't end up going with Spring MVC for your API implementation. There are many ways to secure a rest API with spring security, but I the simplest is to send the basic auth header with every request to a secure URI
**3.)Can I nevertheless use Spring MVC controllers to build the REST API (together with JSF in the web layer)? Or is there a better way?**
Spring MVC Controllers will work fine, but I would recommend going with RestEasy or Jersey. I find them to be more flexable. |
8,394,678 | I installed opencv from Macports and it is in
/opt/local/include
I tried to compile basic OPENCV code from Terminal by giving the following commands, but it doesn't getting compiled:
```
g++ example.cpp -o example -I /usr/local/include/opencv/ -L /usr/local/lib/ -lopencv_highgui -lopencv_calib3d -lopencv_legacy
g++ example.cpp -o example -I /opt/local/include/opencv/ -L /opt/local/lib/ -lopencv_highgui -lopencv_calib3d -lopencv_legacy
```
**Can anyone tell me the right Terminal command to compile given below opencv program for Mac OS X 10,7?**
I was trying to compile the simple example given on this link:
<http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/>
**Edit:**
Here is the code I am trying to compile:
```
////////////////////////////////////////////////////////////////////////
//
// hello-world.cpp
//
// This is a simple, introductory OpenCV program. The program reads an
// image from a file, inverts it, and displays the result.
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
int main(int argc, char *argv[])
{
IplImage* img = 0;
int height,width,step,channels;
uchar *data;
int i,j,k;
if(argc<2){
printf("Usage: main <image-file-name>\n\7");
exit(0);
}
// load an image
img=cvLoadImage(argv[1]);
if(!img){
printf("Could not load image file: %s\n",argv[1]);
exit(0);
}
// get the image data
height = img->height;
width = img->width;
step = img->widthStep;
channels = img->nChannels;
data = (uchar *)img->imageData;
printf("Processing a %dx%d image with %d channels\n",height,width,channels);
// create a window
cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);
cvMoveWindow("mainWin", 100, 100);
// invert the image
for(i=0;i<height;i++) for(j=0;j<width;j++) for(k=0;k<channels;k++)
data[i*step+j*channels+k]=255-data[i*step+j*channels+k];
// show the image
cvShowImage("mainWin", img );
// wait for a key
cvWaitKey(0);
// release the image
cvReleaseImage(&img );
return 0;
}
```
**And here is the output:**
```
singhg@~/Programming/opencvTest $ g++ example.c -o example 'pkg-config --cflags --libs opencv'
i686-apple-darwin11-llvm-g++-4.2: pkg-config --cflags --libs opencv: No such file or directory
example.c:14:16: error: cv.h: No such file or directory
example.c:15:21: error: highgui.h: No such file or directory
example.c: In function ‘int main(int, char**)’:
example.c:21: error: ‘IplImage’ was not declared in this scope
example.c:21: error: ‘img’ was not declared in this scope
example.c:23: error: ‘uchar’ was not declared in this scope
example.c:23: error: ‘data’ was not declared in this scope
example.c:32: error: ‘cvLoadImage’ was not declared in this scope
example.c:43: error: expected primary-expression before ‘)’ token
example.c:43: error: expected `;' before ‘img’
example.c:47: error: ‘CV_WINDOW_AUTOSIZE’ was not declared in this scope
example.c:47: error: ‘cvNamedWindow’ was not declared in this scope
example.c:48: error: ‘cvMoveWindow’ was not declared in this scope
example.c:55: error: ‘cvShowImage’ was not declared in this scope
example.c:58: error: ‘cvWaitKey’ was not declared in this scope
example.c:61: error: ‘cvReleaseImage’ was not declared in this scope
```
Edit[6Dec]:
```
singhg@~/Programming/opencvTest $ g++ example.cpp -o example `pkg-config --cflags --libs opencv`
Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing `opencv.pc'
to the PKG_CONFIG_PATH environment variable
No package 'opencv' found
i686-apple-darwin11-llvm-g++-4.2: example.cpp: No such file or directory
i686-apple-darwin11-llvm-g++-4.2: no input files
singhg@~/Programming/opencvTest $
```
---
in my `/opt/local/lib` I have:
```
singhg@/opt/local/lib $ ls *cv*
libopencv_calib3d.2.3.1.dylib libopencv_highgui.dylib
libopencv_calib3d.2.3.dylib libopencv_imgproc.2.3.1.dylib
libopencv_calib3d.dylib libopencv_imgproc.2.3.dylib
libopencv_contrib.2.3.1.dylib libopencv_imgproc.dylib
libopencv_contrib.2.3.dylib libopencv_legacy.2.3.1.dylib
libopencv_contrib.dylib libopencv_legacy.2.3.dylib
libopencv_core.2.3.1.dylib libopencv_legacy.dylib
libopencv_core.2.3.dylib libopencv_ml.2.3.1.dylib
libopencv_core.dylib libopencv_ml.2.3.dylib
libopencv_features2d.2.3.1.dylib libopencv_ml.dylib
libopencv_features2d.2.3.dylib libopencv_objdetect.2.3.1.dylib
libopencv_features2d.dylib libopencv_objdetect.2.3.dylib
libopencv_flann.2.3.1.dylib libopencv_objdetect.dylib
libopencv_flann.2.3.dylib libopencv_ts.2.3.1.dylib
libopencv_flann.dylib libopencv_ts.2.3.dylib
libopencv_gpu.2.3.1.dylib libopencv_ts.dylib
libopencv_gpu.2.3.dylib libopencv_video.2.3.1.dylib
libopencv_gpu.dylib libopencv_video.2.3.dylib
libopencv_highgui.2.3.1.dylib libopencv_video.dylib
libopencv_highgui.2.3.dylib
singhg@/opt/local/lib $
```
Now I used this command:
```
singhg@~/Programming/opencvTest $ g++ hello-world.cpp -o hello-world -I /opt/local/include/opencv/ -L /opt/local/lib -lopencv_highgui -lopencv_core
In file included from hello-world.cpp:12:
/opt/local/include/opencv/cv.h:63:33: error: opencv2/core/core_c.h: No such file or directory
/opt/local/include/opencv/cv.h:64:33: error: opencv2/core/core.hpp: No such file or directory
/opt/local/include/opencv/cv.h:65:39: error: opencv2/imgproc/imgproc_c.h: No such file or directory
/opt/local/include/opencv/cv.h:66:39: error: opencv2/imgproc/imgproc.hpp: No such file or directory
/opt/local/include/opencv/cv.h:67:38: error: opencv2/video/tracking.hpp: No such file or directory
/opt/local/include/opencv/cv.h:68:45: error: opencv2/features2d/features2d.hpp: No such file or directory
/opt/local/include/opencv/cv.h:69:35: error: opencv2/flann/flann.hpp: No such file or directory
/opt/local/include/opencv/cv.h:70:39: error: opencv2/calib3d/calib3d.hpp: No such file or directory
/opt/local/include/opencv/cv.h:71:43: error: opencv2/objdetect/objdetect.hpp: No such file or directory
/opt/local/include/opencv/cv.h:72:37: error: opencv2/legacy/compat.hpp: No such file or directory
/opt/local/include/opencv/cv.h:79:37: error: opencv2/core/internal.hpp: No such file or directory
In file included from hello-world.cpp:13:
/opt/local/include/opencv/highgui.h:47:39: error: opencv2/highgui/highgui_c.h: No such file or directory
/opt/local/include/opencv/highgui.h:48:39: error: opencv2/highgui/highgui.hpp: No such file or directory
hello-world.cpp: In function ‘int main(int, char**)’:
hello-world.cpp:18: error: ‘IplImage’ was not declared in this scope
hello-world.cpp:18: error: ‘img’ was not declared in this scope
hello-world.cpp:20: error: ‘uchar’ was not declared in this scope
hello-world.cpp:20: error: ‘data’ was not declared in this scope
hello-world.cpp:29: error: ‘cvLoadImage’ was not declared in this scope
hello-world.cpp:40: error: expected primary-expression before ‘)’ token
hello-world.cpp:40: error: expected `;' before ‘img’
hello-world.cpp:44: error: ‘CV_WINDOW_AUTOSIZE’ was not declared in this scope
hello-world.cpp:44: error: ‘cvNamedWindow’ was not declared in this scope
hello-world.cpp:45: error: ‘cvMoveWindow’ was not declared in this scope
hello-world.cpp:52: error: ‘cvShowImage’ was not declared in this scope
hello-world.cpp:55: error: ‘cvWaitKey’ was not declared in this scope
hello-world.cpp:58: error: ‘cvReleaseImage’ was not declared in this scope
singhg@~/Programming/opencvTest $
``` | 2011/12/06 | [
"https://Stackoverflow.com/questions/8394678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1082701/"
] | Or use **pkg-config** to assist you filling in the paths and libraries:
```
g++ example.cpp -o example `pkg-config --cflags --libs opencv`
``` |
29,734,154 | iPhone 6 simulator: ![image 1](https://i.stack.imgur.com/VQ1jd.png)
iPhone5 hardware: ![image2](https://i.stack.imgur.com/8c3kL.png)
Channel Header:
```
- (id)initWithFrame:(CGRect)frame title:(NSString *)title {
self = [super initWithFrame:frame];
UILabel *l = [[UILabel alloc] initWithFrame:frame];
l.textAlignment = NSTextAlignmentCenter;
l.backgroundColor = BGC;
l.text = title;
[self addSubview:l];
return self;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
ChannelHeader *h = [[ChannelHeader alloc] initWithFrame:CGRectMake(0, 0, self.tv.frame.size.width, 44) title:[self titles][section]];
return h;
}
```
Why is my tableview header's textfield showing up off center?
Tableview frame in iPhone6 sim:
```
<UITableView: 0x7fce2c821a00; frame = (0 0; 414 736)
```
EDIT:
so I changed my simulated nib size from "iPhone 6" to "inferred", and the view boundaries grew. I stretched my UITableView to fit the bounds and now the text is even *more* off-centered. So somehow it's getting the wrong values for its frame.. | 2015/04/19 | [
"https://Stackoverflow.com/questions/29734154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172232/"
] | Well, your frame for iPhone 6 is wrong.
**iPhone 6** screen size is **375 x 667** points.
**iPhone 6 plus** screen size is **414 x 736** points.
Therefore, if you are running the application on iPhone 6 simulator and tableView frame is giving you iPhone 6 plus boundaries, then that is the error. Your header and UILabel is being rendered correctly according to the given frames.
So if you run your application in iPhone 6 plus simulator, you will get correct results.
[More info on frames.](http://www.paintcodeapp.com/news/iphone-6-screens-demystified)
**Solution:**
If your setting your tableView through nib, and if you are using AutoLayout then you need to apply **constraints** accordingly.
If you have disabled AutoLayout then apply proper resizing masks to your tableView, i.e. **Flexible Height** & **Flexible Width**
---
Also, it would be a good practice, if you take values of the tableView frame provided by the delegate method instead of referring to the tableView property.
```
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
ChannelHeader *h = [[ChannelHeader alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), 44) title:[self titles][section]];
return h;
}
```
*Note*: This is just a piece of good practice and it doesn't effect the logic or the answer. |
145,328 | Could someone please show me how to get LaTeX to properly typeset the -=, += assignment operators. I have tried
```
$a -= 1$
$a\texttt{-=}1$
$a\verb!-=!1$
```
but they all look really ugly. I have been searching all over to find a solution for this, but apparently I am the only one with this problem. And I only have two such assignments in my whole document, so I am not interested in typesetting arbitrary blocks of C++ code, just those two assignments | 2013/11/16 | [
"https://tex.stackexchange.com/questions/145328",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/41127/"
] | these two-part operators have to be declared as operators to get the correct spacing
on either side. the following definitions will take care of that, while forcing each
individual part to be treated as an ordinary character.
```
\newcommand{\pluseq}{\mathrel{{+}{=}}}
\newcommand{\minuseq}{\mathrel{{-}{=}}}
```
the result may still not be to your liking, but if you find the two parts to be
farther apart than you think they should be, that can be adjusted by some negative
space between them.
![enter image description here](https://i.stack.imgur.com/LPKmp.png) |
50,512,804 | I have sub-classed Generic DetialView class in `views.py` and trying to figure out a way to return data in JSON format based on an argument received in the url. Here's what I have tried doing...
```
# views.py
from django.views.generic import DetailView
from django.http import JsonResponse
class ExtendedView(DetailView):
context_object_name = 'post'
model = StorageModel
template_name='posts.html'
def get_context_data(self, **kwargs):
data = super(HacksViewPost, self).get_context_data(**kwargs)
if bool(self.request.GET):
data__ = JsonForm(request.GET)
if data__.is_valid():
json = data__.cleaned_data['json']
if json == 'true':
return JsonResponse({'data': 'data'})
return data
```
But this gave me `TypeError` as it should be:
```
TypeError at /category/extended-slug/
context must be a dict rather than JsonResponse.
```
The url that activates the `ExtendedView` class is:
```
/category/extended-slug?json=true
```
So, the question is how could i send data in JSON Format from a Generic View Class and are there any better ways of acheiving this? | 2018/05/24 | [
"https://Stackoverflow.com/questions/50512804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8030629/"
] | I think you patch it at the wrong level. The `get_context_data` is used by the `get` function to render it. As a result, the `get_context_data` object has *no* control about what is done with the result, in order to construct a server response,
You can however patch the `get(..)` function like:
```
class ExtendedView(DetailView):
"""A base view for displaying a single object."""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
**data =** self.get_context_data(object=self.object)
if self.request.GET:
data__ = JsonForm(request.GET)
if data__.is_valid():
json = data__.cleaned_data['json']
if json == 'true':
**return JsonResponse({'data': data})**
**return self.render\_to\_response(data)**
```
The same holds for `post`, `put`, and other requests.
If we take a look at the [`DetailView` source code](https://github.com/django/django/blob/master/django/views/generic/detail.py#L103) we see:
>
>
> ```
> class BaseDetailView(SingleObjectMixin, View):
> """A base view for displaying a single object."""
> def get(self, request, *args, **kwargs):
> self.object = self.get_object()
> context = self.get_context_data(object=self.object)
> return self.render_to_response(context)
>
> ```
>
>
Hence the `get(..)` calls the `get_context_data(..)` function. But it does *not* immediately returns the result, it wraps it into a *rendered* response. |
16,539,061 | I have installed redis on an independent database server(ec2 instance). And it has been installed and configured properly.
Now all that I want to do is from my webserver, I connect to it, and make changes to its key value store.
I have a python/django application running on heroku, and I am using PostgreSQL for everything else, I am using redis just to store some temporary variable in the KV sets.
Now, I install <https://github.com/andymccurdy/redis-py> on my localserver, and webserver.
To test the connection and check if things are working well, I try the following in my environment :
```
>>> pool = redis.ConnectionPool(host='MY_DBSERVER_IP_ADDRESS', port=6379, db=0)
>>> r = redis.Redis(connection_pool=pool)
>>> r.set('foo', 'bar')
```
this gives me an error - `ConnectionError: Error 111 connecting 54.235.xxx.xxx:6379. Connection refused.`
How do I connect? What am I missing? | 2013/05/14 | [
"https://Stackoverflow.com/questions/16539061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1629366/"
] | By default the config is set to only bind to 127.0.0.1
You just need to find your config (/etc/redis/redis.conf on Ubuntu) and comment out the bind 127.0.0.1 line. |
65,938,547 | I am coming from Java background and learning Scala now. I have a `Seq` respectively for `Loc` and `LocSize` objects whereby these 2 objects share a common member field `code`. I have a `validateRoom` function that basically validates these two `Seq` by matching a `Loc` instance to a `LocSize` instance and make some basic validation operations. My objective is to make sure all Loc objects passes the validation, hence I am using `Seq.forall` at the last `println`.
I believe that there are better, shorter and prettier FP ways to achieve what I want. How can I do so?
```
case class Loc(id: String, code: String, isRoom: Boolean, measureUnit: String, allowedSize: Int)
case class LocSize(code: String, width: Int, length: Int, measureUnit: String)
val locs = Seq(
Loc("_1", "loc01", true, "M", 100),
Loc("_2", "loc02", false, "M", 100),
Loc("_3", "loc03", true, "M", 100)
)
val locSizes = Seq(
LocSize("loc01", 5, 10, "M"),
LocSize("loc02", 6, 11, "M"),
LocSize("loc03", 9, 14, "M"),
LocSize("loc04", 8, 13, "M"),
LocSize("loc05", 9, 14, "M"),
)
def validateRoom(locs: Seq[Loc], loSizes: Seq[LocSize]): Seq[Boolean] = {
for (loc <- locs) yield {
if (loc.isRoom) {
val locSize = loSizes.find(_.code == loc.code)
locSize match {
case Some(i) => {
if (i.measureUnit.contains(loc.measureUnit) &&
i.width*i.length < loc.allowedSize)
true
else
false
}
case None => false
}
}
else
true
}
}
// Return false as loc03 size 9*14 > 100
println(validateRoom(locs, locSizes).forall(b => b))
``` | 2021/01/28 | [
"https://Stackoverflow.com/questions/65938547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/723497/"
] | YMMV and there are probably other more elegant solutions, here is one example
```scala
def validateRooms(locs: Seq[Loc], loSizes: Seq[LocSize]): Boolean = {
locs.foldLeft(true){ (state, loc) =>
if (state) {
val locSize = loSizes.find(_.code == loc.code)
locSize.map( s =>
s.measureUnit.contains(loc.measureUnit) &&
s.width*s.length < loc.allowedSize).getOrElse(false)
} else {
state
}
}
}
```
In this case the function returns the result `true` if all are valid eliminating the `forall`. Uses `map` and `foldleft` to eliminate the for comprehension. |
51,888,897 | I am reading a code and found too many use of `hdfs dfs -test /dir_name`.
I am curious about how does it execute its operations. | 2018/08/17 | [
"https://Stackoverflow.com/questions/51888897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5394210/"
] | Neat problem. Here's the issue:
`re.sub` does not allow one character to lie in multiple matching groups; once a character belongs to a match, it is consumed, unless you specify that the match be nonconsuming. When matching using the asterisk, a key fact was that a word boundary lies between an asterisk and a word character. Here are the matching groups when using the asterisk (the `{0}`, `{1}`, and `{2}` in the `lambda`):
```
('', 'first', '*')
('', 'second', '*')
('', 'third', '*')
('', 'fourth', '*')
('', 'fifth', '')
```
When the regex matcher hits the end of the first match, its cursor is between the first asterisk and the word `second`, which is at a word boundary. Hence `second*` is also a match, and then `third*`, etc.
However, when you use an underscore, here are the corresponding matches:
```
('', 'first', '_')
('_', 'third', '_')
('_', 'fifth', '')
```
When the regex matcher hits the end of the first match, its cursor is between the first underscore and the word `second` , which is *not* a word boundary. Since it's already passed the first underscore and isn't at a word boundary, it can't match `(_|\b)second`. Hence there is no match until the next underscore after `second`, and you can see that that match includes both underscores adjacent to `third`.
In short, the first example was "lucky" in that after passing the separator character, you'd land in a word boundary, which was not the case for the second example.
To fix this, you can use a lookahead assertion, which will not consume the matched characters.
```
def replace_words(string, rep_dict, separator):
regex = r'({0}|\b)({1})((?={2}|\b).*?)'.format(
re.escape(separator), '|'.join(rep_dict.keys()), re.escape(separator)
)
return re.sub(
regex, lambda x: '{0}{1}{2}'.
format(x.group(1), rep_dict[x.group(2)], x.group(3)), string
)
```
The matches are now the following:
```
('', 'first', '')
('*', 'second', '')
('*', 'third', '')
('*', 'fourth', '')
('*', 'fifth', '')
```
Ignore the struck-through text below, which would have matched on word prefixes, e.g. `*firstperson*` would have become `*1stperson*`.
P.S. Splitting and rejoining is probably your best bet. This is most likely what re.sub is doing under the hood anyway, since strings are immutable.
~~To fix this, you can match only on the separator character preceding a keyword *or* the start of the string (alternatively, the separator character following a keyword *or* the end of the string).~~
```
def replace_words(string, rep_dict, separator):
regex = r'(^|{0})({1})'.format(
re.escape(separator), '|'.join(rep_dict.keys())
)
return re.sub(
regex, lambda x: print(x.groups()) or '{0}{1}'.
format(x.group(1), rep_dict[x.group(2)]), string
)
``` |
21,253,371 | Can You help me please. I need to change background color of my list view item which is selected manually by **setSelection(int pos)** function and I need to stay with new color until new setSelection call. I have read some topics of how to do this, but I still have no succes. Thanks! | 2014/01/21 | [
"https://Stackoverflow.com/questions/21253371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1885632/"
] | I've managed to accomplish that by making several selectors for the different states
first put this in your listview
```
android:listSelector="@drawable/list_selector"
```
Then create xml files in drawable to control the diferent states
**@drawable/list\_selector**
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>
</selector>
```
**@drawable/list\_item\_bg\_normal**
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="@color/list_background"
android:endColor="@color/list_background"
android:angle="90" />
</shape>
```
**@drawable/list\_item\_bg\_pressed**
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="@color/list_background_pressed"
android:endColor="@color/list_background_pressed"
android:angle="90" />
</shape>
```
In your ListView Selection
```
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
view.setSelected(true);
...
}
}
```
Don't forget to add **list\_background\_pressed** and **list\_background** to your values/color.xml or just set the color manually in each file.
And I Believe that when you use **setSelection(int pos)** that will automatically uset the layout you've set as selectected.
Hope it helps. |
15,211,689 | I'm trying to create an index containing 37 million records.
I'm using a script to export the data from MySQL, and output this as XML, which is then being imported with xmlpipe2.
The problem I have, is the XML file being generated is considerably large, and the server I'm developing on doesn't have the memory to store the XML.
If I limit the amount of rows being imported, e.g. LIMIT 0, 1000000, when I then do LIMIT 1000000, 1000000, the index doesn't 'merge' as such, but overwrites.
Can I somehow stagger this so I eventually end up with an index of all the data?
Thanks | 2013/03/04 | [
"https://Stackoverflow.com/questions/15211689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/553452/"
] | Cute one-liner:
```
u.unit_type = unit_hash[:name][/Division|Brigade/]
```
The bug in your code is that `scan` returns an empty array (`[]`) when it doesn't find anything, and an empty array is "truthy". The method you're looking for is `include?` My solution bypasses the conditional entirely by directly assigning the string search result (which can be `nil`) to the unit type. |
4,096,004 | I would appreciate suggestions to solve:
If x, y, w, z > 0 and $x^4$ + $y^4$ + $w^4$ + $z^4$ <=4 prove the following:
1/$x^4$ + 1/$y^4$ + 1/$w^4$ + 1/$z^4$ >= 4
From plugging in numbers into Excel, it looks like x, y, w, z must be numbers near 1.
I tried to do a simple case:
If a, b, k > 0 and a + b < k prove the following: 1/a + 1/b > k
a + b < k so 1/(a+b) > 1/k
But 1/a + 1/b > 1/(a+b) so 1/a + 1/b > 1/k which is not what I want to prove.
It seems that I would have to impose a condition for the possible values of k. | 2021/04/09 | [
"https://math.stackexchange.com/questions/4096004",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/801952/"
] | Thank you very much for the hints. Here is the solution from the hint of achille hui:
We are told that $x^4$ + $y^4$ + $w^4$ + $z^4$ <=4 so ($x^4$+$y^4$ + $w^4$ + $z^4$)/4 <= 1
But AM >= HM (or HM <= AM) so:
4/(1/$x^4$ + 1/$y^4$ + 1/$w^4$ + 1/$z^4$) <= ($x^4$+$y^4$ + $w^4$ + $z^4$)/4 <= 1
Which means:
4/(1/$x^4$ + 1/$y^4$ + 1/$w^4$ + 1/$z^4$) <= 1
Re-arranging:
4 <= 1/$x^4$ + 1/$y^4$ + 1/$w^4$ + 1/$z^4$
In other words:
1/$x^4$ + 1/$y^4$ + 1/$w^4$ + 1/$z^4$ >= 4 |
1,116,397 | I am trying to write a bash script that checks all ports if they are closed or open and if the current ssh version is good or needs an update.
below is the code i got figured out but i think it could be improved-
`$ ssh -p115 -vv [email protected] && /usr/lib/ubuntu-release-upgrader/check-new-release`
i already know that all the servers i am working with are reachable by port 115.
i am not sure if its even possible to get the current version without logging on to the server. | 2019/02/07 | [
"https://askubuntu.com/questions/1116397",
"https://askubuntu.com",
"https://askubuntu.com/users/922300/"
] | Use `nmap` (you may have to `sudo apt install nmap` first. Read `man nmap`. Reread `man nmap`, and do something like (MY system runs `sshd` on port 22):
```
sudo nmap -sV -p22 --version-all localhost
Starting Nmap 7.01 ( https://nmap.org ) at 2019-02-07 09:22 EST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00010s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.6 (Ubuntu Linux; protocol 2.0)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 1.54 seconds
``` |
71,084 | I work in a legal/corp environment with cubicle desks. My coworker to the left of me is an older woman (early 50s) and can be a bit of a tattle tale/goody two shoes type of person. She's nice on the surface but can be a bit nit picky on things and always likes to brag how she's been in the field for so many years and knows more than the attorneys we work for.
I'm fairly new to the company (about 7 months) and she is the one that sort of trained me with the office systems, so we established a sort of friendship and get along well which is why it surprised me how she reacted to this situation.
Before I came along, there was this other coworker who would always spray Lysol and people started complaining especially my coworker. The office manager sent out an email that we were not to spray things to avoid peoples sensitivities.
I never use any such things even before said policy went into effect but this time right as we were getting ready to leave for the day (about 15 min before) I used a hand sanitizer/spritz that I had received and didn't realize it would have a strong scent. She asked me if I'd sprayed something and I said "Yes. Did it smell bad!?" She then went on to lecture me how we cannot spray anything not even deodorant etc. I apologized and told her that it was an honest mistake and I just didn't think it'd have a strong scent but that I was sorry and would not even bring it back. In a very snotty voice she told me that she would have to let the office manager know of this.
This was my one and only time doing this. I apologized and didn't in any way do it to be defiant. I kind of just by inertia used it. Absentmindedly and I told her I was sorry.
I am a bit hurt by her nasty reaction and even proclaiming to go to the office manager. I mean I accepted my error and she wouldn't let it go.
I am not sure if she actually will talk to her but should I wait until the office manager asks me what happened?
Is this coworker blowing things out of proportion? | 2016/07/09 | [
"https://workplace.stackexchange.com/questions/71084",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/53690/"
] | In the UK, there are two types of notice period; contractual, and statutory.
Contractual notice is that set in any contract. You've checked your contract, and there's nothing in there, so it won't apply. I assume you've checked your employment handbook also?
Statutory notice, if *you* decide to leave after you've worked at a company for more than a month, is one week. It doesn't change/get any longer based on how long you've worked there. If the company decides to make you redundant, they have to give notice of (or pay) one week for each year of service.
If you have any holiday this year accrued, take it off your notice period. |
59,238,677 | I have username and password to the metabase our company use heavily. Everyday I have to download CSVs frequently and then export them to google sheets to make report or analysis. Is there any way to connect Metabase to Google Sheet so that the sheets pull CSVs automatically from Metabase url? | 2019/12/08 | [
"https://Stackoverflow.com/questions/59238677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12501302/"
] | I've implemented a [Google Sheets add-on as a solution for this and open-sourced it](https://github.com/bplmp/metabase-google-sheets-add-on).
I've used this code as a Google Sheets add-on at a large organization and it has worked well so far, with hundreds of users a week, running tens of thousands of queries.
This is what it looks like in action:
[![gif of add-on in action](https://i.stack.imgur.com/Dxxuv.gif)](https://i.stack.imgur.com/Dxxuv.gif)
If you don't want the hassle of setting it up as a Google Sheets add-on, you can take the script and adapt it as a simple Apps Script. |
1,145,347 | >
> **Possible Duplicates:**
>
> [What is the correct way to create a single instance application?](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application)
>
> [Prevent multiple instances of a given app in .NET?](https://stackoverflow.com/questions/93989/prevent-multiple-instances-of-a-given-app-in-net)
>
>
>
Do I check whether another process with the same name exists? (What if the user doesn't have permission to do that?)
Write a file to disk and delete it before exiting? (what about abnormal termination?)
What would be a best practice to do this? | 2009/07/17 | [
"https://Stackoverflow.com/questions/1145347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | You can use a Mutex.
```
bool firstInstance = true;
using (Mutex mutex = new Mutex(true, "MyApplicationName", out firstInstance))
{
if (firstInstance)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
// Another instance loaded
}
}
``` |
14,330 | What will be the wavelength of an X-ray, if we apply a potential difference of, say $\pu{20 kV}$ across the ends of the X-ray tube?
Alright, I started with the modified de-Broglie equation-
$$\Lambda=\frac{h}{\sqrt{meV}}$$
I pinned the values of Planck constant, electronic charge and potential difference but can't guess what would be the mass $m$ here.
The answer comes $\pu{0.62\*10^-10m}$ if solved perfectly. Can anybody confirm? | 2014/07/14 | [
"https://chemistry.stackexchange.com/questions/14330",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/-1/"
] | $$\lambda=\frac h{\sqrt{meV}}$$
$$E=mc^2$$
Also $$E=\frac{hc}\lambda$$
Therefore,
$$mc^2=\frac{hc}\lambda$$
$$mc=\frac h\lambda$$
Hence $$m=\frac h{\lambda c}$$
Plugging the value of $m$ from here we get an equation with all known constants. Solving for $\lambda$, we can get the result as $0.62\times10^{-10}\ \mathrm m$. |
52,074,904 | I am trying to create a search functionality with AJAX so it will load posts. It currently does not show the results.
I took this code from another post and played around with it as the completed code was sent privately.
Any help would be greatly appreciated.
functions.php file code
```
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}}
```
Script (in functions.php)
```
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
```
html
```
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Search results will appear here</div>
``` | 2018/08/29 | [
"https://Stackoverflow.com/questions/52074904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9989181/"
] | Declare a parameter of type `TestInfo` in your test method and [JUnit will automatically supply an instance](https://junit.org/junit5/docs/current/user-guide/#writing-tests-dependency-injection) of that for the method:
```java
@Test
void getTestInfo(TestInfo testInfo) { // Automatically injected
System.out.println(testInfo.getDisplayName());
System.out.println(testInfo.getTestMethod());
System.out.println(testInfo.getTestClass());
System.out.println(testInfo.getTags());
}
```
You can get test method name (and more) from the `TestInfo` instance as shown above. |
8,901,895 | I've a Windows Services written in c#.net. If I need to change the app.config file, do I need to restart the Windows Service application so that it picks up the new changes?
Also, if I change the web.config connection string does app pool gets started automatically?
Thanks. | 2012/01/17 | [
"https://Stackoverflow.com/questions/8901895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/656348/"
] | The answer to the first question is yes. Unless you implement some kind of automatic file watcher plus domain restart scheme, yes, app.config files for services or other types of apps need to be re-read in order for changes in them to be applied.
As for the second, yes, ASP.NET will detect changes to web.config files and reload the app domain automatically. |
52,074,768 | So I have been utterly frustrated these past few days because I have not been able to find a single resource online which properly documents how to find emojis when writing a discord bot in javascript. I have been referring to this guide whose documentation about emojis seems to be either wrong, or outdated:
<https://anidiots.guide/coding-guides/using-emojis>
What I need is simple; to just be able to reference an emoji using the `.find()` function and store it in a variable. Here is my current code:
```js
const Discord = require("discord.js");
const config = require("./config.json");
const fs = require("fs");
const client = new Discord.Client();
const guild = new Discord.Guild();
const bean = client.emojis.find("name", "bean");
client.on("message", (message) => {
if (bean) {
if (!message.content.startsWith("@")){
if (message.channel.name == "bean" || message.channel.id == "478206289961418756") {
if (message.content.startsWith("<:bean:" + bean.id + ">")) {
message.react(bean.id);
}
}
}
}
else {
console.error("Error: Unable to find bean emoji");
}
});
```
*p.s. the whole bean thing is just a test*
But every time I run this code it just returns this error and dies:
**`(node:3084) DeprecationWarning: Collection#find: pass a function instead`**
Is there anything I missed? I am so stumped... | 2018/08/29 | [
"https://Stackoverflow.com/questions/52074768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7386888/"
] | I never used `discord.js` so I may be completely wrong
from the warning I'd say you need to do something like
```
client.emojis.find(emoji => emoji.name === "bean")
```
Plus after looking at the [`Discord.js Doc`](https://discord.js.org/#/docs/main/stable/class/Collection?scrollTo=find) it seems to be the way to go. BUT the docs never say anything about `client.emojis.find("name", "bean")` being wrong |
33,623,734 | My form consists of one splitContainer with two horitzontal panels, several buttons on the top panel and charts on the bottom panel.
When the form loads, the top panel is cut and some of the elements are hidden/cut. Moreover if I resize the form, none of the elements or splitContainer resize.
How can properly do it?
I tried with the autoresize property in `Form_Load()`
```
//this.AutoSize = true;
//this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
```
These are the splitContainer properties
```
//
// splitContainer1
//
this.splitContainer1.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.btnPlay);
this.splitContainer1.Panel1.Controls.Add(this.grpOptions);
this.splitContainer1.Panel1.Controls.Add(this.grpDisplay);
this.splitContainer1.Panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.splitContainer1_Panel1_Paint);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.splitContainer1.Size = new System.Drawing.Size(784, 561);
this.splitContainer1.SplitterDistance = 69;
this.splitContainer1.TabIndex = 0;
```
This is the screenshot:
[![enter image description here](https://i.stack.imgur.com/OrSXB.png)](https://i.stack.imgur.com/OrSXB.png) | 2015/11/10 | [
"https://Stackoverflow.com/questions/33623734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335493/"
] | I suggest you anchor the controls on the splitcontainer |
47,211,545 | I am installing the package mysql-server on debian (actually Raspbian, the Debian version for raspberry pi). I'm installing it with the following command
```
sudo apt-get install mysql-server
```
During the installation **I'm not asked to enter a root password**. And if I try to connect to mysql with the following command :
```
mysql -u root
```
or
```
mysql -u root -p
```
and using the system root password, I got the following error :
```
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
```
I am quite confused since apparently **I should be asked to provide a root password during the installation**.
What should I do ?
Regards. | 2017/11/09 | [
"https://Stackoverflow.com/questions/47211545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5485049/"
] | Try this:
After installation, run MySql Secure Installation:
```
pi@raspberrypi:~ $ sudo mysql_secure_installation
```
You'll be asked a series of security related configuration questions, including setting the root password.
Once the root password is set, you'll need to be logged in as root (or use `sudo`) to login. This is a consequence of how MySql uses credentials based on [process uid](https://stackoverflow.com/questions/28068155/access-denied-for-user-rootlocalhost-using-password-yes-after-new-instal) |
16,209,690 | I have custom tasks in my SBT (0.12.2) project. Let's call them `a`, `b` and `c`. So when I'm in the interactive mode of SBT I can just type `a` and the task associated with `a` is executed. I also can type `;a;b;c` and the three tasks are executed in sequence; the same way something like `;clean;compile` would do. What I also can do from the interactive shell is create an alias to run them all: `alias all=;a;b;c`. Now when I type `all` the tasks are executed in an obvious manner. What I'm trying to achieve is creating this alias inside of the SBT configuration for my project.
[This section](http://www.scala-sbt.org/0.12.2/docs/Detailed-Topics/TaskInputs) of SBT documentation deals with tasks, but all I could achieve was something like this:
```
lazy val a = TaskKey[Unit]("a", "does a")
lazy val b = TaskKey[Unit]("b", "does b")
lazy val c = TaskKey[Unit]("c", "does c")
lazy val all = TaskKey[Unit]("all", ";a;b;c")
lazy val taskSettings = Seq(
all <<= Seq(a,b,c).dependOn
)
```
The problem I have with this approach is that the tasks are **combined** and thus their execution happens in parallel in contrast to sequential, which is what I'm trying to achieve. So how can I create an alias like `alias all=;a;b;c` inside of the SBT configuration file? | 2013/04/25 | [
"https://Stackoverflow.com/questions/16209690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797926/"
] | I've been looking for the same thing and found [this request](https://github.com/sbt/sbt/issues/388) for an easy way of aliasing and [the commit](https://github.com/sbt/sbt/commit/6746557d05b2b1c207aa5d1a03e5426694c5bf2b) that provides one: `addCommandAlias`.
In my `build.sbt` I now have:
```
addCommandAlias("go", ";container:start;~copy-resources")
```
As you might guess, writing `go` in the console will now run the longer command sequence for me. |
31,901,428 | **Please look at my code**
Html :
```
`<div id="animated-example" class="animated swing"><div class="navbar"></div></div>`
```
Css :
```
.animated {
color: #9f9f9f;
min-height: 300px;
width: 100%;
padding-bottom: 24px;
background: #000000 url(../images/icons.svg) repeat center;
-webkit-animation-timing-function: linear;
-moz-animation-timing-function: linear;
-o-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
-moz-animation-iteration-count: infinite;
-o-animation-iteration-count: infinite;
animation-iteration-count: infinite;
-webkit-animation-duration:15s;
-moz-animation-duration:15s;
-o-animation-duration:15s;
animation-duration:15s;}
.navbar {
position: absolute;
min-height: 300px;
width: 100%;
padding-top: 24px;
background-image: -o-linear-gradient(-89deg, #000000 0%, rgba(0,0,0,0.00) 100%);
background-image: -moz-linear-gradient(-89deg, #000000 0%, rgba(0,0,0,0.00) 100%);
background-image: -ms-linear-gradient(-89deg, #000000 0%, rgba(0,0,0,0.00) 100%);
background-image: linear-gradient(-179deg, #000000 0%, rgba(0,0,0,0.00) 100%);
}
@-webkit-keyframes swing {
0% {
background-position-y:511px
}
100% {
background-position-y:0
}
}
@-moz-keyframes swing {
0% {
background-position-y:511px
}
100% {
background-position-y:0
}
}
@-o-keyframes swing {
0% {
background-position-y:511px
}
100% {
background-position-y:0
}
}
@keyframes swing {
0% {
background-position-y:511px
}
100% {
background-position-y:0
}
}
.swing {
-webkit-transform-origin: center;
transform-origin: center;
-webkit-animation-name: swing;
animation-name: swing;
}
```
**The problem is that the animation does not work in Firefox, but Chrome and other browsers work**
**Please see the video below, it speaks**
**<http://sendvid.com/b1r3hofg>** | 2015/08/09 | [
"https://Stackoverflow.com/questions/31901428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5207542/"
] | I'm not sure what you don't find clear in the [**Nexus Book**](http://books.sonatype.com/nexus-book/reference/confignx-sect-manage-repo.html). The short version is, a proxy repository is one that you are *mirroring*, and a hosted repository is one that you *host on your server through the Nexus software*. Hosted includes third party libraries that aren't public for some reason, see below.
>
> 6.2.1. Proxy Repository
> -----------------------
>
>
> A *Proxy Repository* is a proxy of a remote repository. By default, Nexus ships with the following configured proxy repositories:
>
>
> ### Apache Snapshots
>
>
> This repository contains snapshot releases from the Apache Software Foundation.
>
>
> ### Codehaus Snapshots
>
>
> This repository contains snapshot releases from Codehaus.
>
>
> ### Central
>
>
> This is the Central Repository containing release components. Formerly known as Maven Central, it is the default built-in repository for Apache Maven and directly supported in other build tools like Gradle, SBT or Ant/Ivy. Nexus connects to the Central Repository via HTTPS using the URL <https://repo1.maven.org/maven2/>.
>
>
> 6.2.2. Hosted Repository
> ------------------------
>
>
> A *Hosted Repository* is a repository that is hosted by Nexus. Nexus ships with the following configured hosted repositories:
>
>
> ### 3rd Party
>
>
> This hosted repository should be used for third-party dependencies not available in the public Maven repositories. Examples of these dependencies could be commercial, proprietary libraries such as an Oracle JDBC driver that may be referenced by your organization.
>
>
> ### Releases
>
>
> This hosted repository is where your organization will publish internal releases.
>
>
> ### Snapshots
>
>
> This hosted repository is where your organization will publish internal snapshots.
>
>
> |
27,104,226 | After having searched the official help files and even the Wiki for Notepad++, I am sort of disappointed there is no explanation (or at least I could not find anything) for that enclosed FF symbol which is all over my text for some reason.
I would like to remove that entirely from my file but it appears there are no resources how to handle this symbol with the find&replace procedure:
![enter image description here](https://i.stack.imgur.com/jk1F1.png)
Support is much appreciated.
Oh, by the way: How can I use Notepad++ to add a linebreak before a certain string? So, after removing that FF symbol, add a linebreak right in front of "ENGLISH"? (Without doing that manually for each one, of course). | 2014/11/24 | [
"https://Stackoverflow.com/questions/27104226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4287314/"
] | `FF` is a form feed character, to replace it with newline do following :
* Select the `FF`, press `Ctrl`+`H`
* Choose Extended Mode
* Replace with `\n`
* Click `Replace All`
![enter image description here](https://i.stack.imgur.com/bAYD9.jpg) |
44,242,844 | So, I'm honestly not even sure how to ask this question, since I lack experience in this topic. If there is information missing, just let me know and I'll add all I have.
I'm basically trying to add an Exception handling system in my web application by using a filter.
So below you can see the filter I created. In here I'm trying to reach my unitofwork, but I keep getting an exception on the `container.Resolve<IUnitOfWork>();` line.
```
public class LogExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var dependencyResolver = GlobalConfiguration.Configuration.DependencyResolver
as AutofacWebApiDependencyResolver;
var container = dependencyResolver.Container;
var uow = container.Resolve<IUnitOfWork>();
}
}
```
The exception I'm getting:
>
> **DependencyResolutionException was unhandled by user code**
>
> An exception of type 'Autofac.Core.DependencyResolutionException'
> occurred in Autofac.dll but was not handled in user code
>
>
> Additional information: No scope with a Tag matching
> 'AutofacWebRequest' is visible from the scope in which the instance
> was requested. This generally indicates that a component registered as
> per-HTTP request is being requested by a SingleInstance() component
> (or a similar scenario.) Under the web integration always request
> dependencies from the DependencyResolver.Current or
> ILifetimeScopeProvider.RequestLifetime, never from the container
> itself.
>
>
>
Here is the IUnitOfWork interface:
```
public interface IUnitOfWork : IDisposable
{
IBoothRepository BoothRepository { get; }
IEventRepository EventRepository { get; }
ILocationRepository LocationRepository { get; }
IPersonRepository PersonRepository { get; }
IProfessionalRepository ProfessionalRepository { get; }
IRegistrationRepository RegistrationRepository { get; }
IStakeholderRepository StakeholderRepository { get; }
IStudentRepository StudentRepository { get; }
IVisitRepository VisitRepository { get; }
void SaveChanges();
DbContextTransaction BeginTransaction();
}
``` | 2017/05/29 | [
"https://Stackoverflow.com/questions/44242844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664414/"
] | The *additional information* is your friend here:
>
> No scope [...] is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.)
>
>
>
An ExceptionFilter is a SingleInstance component, since it's generic (Single Instance) to all requests within the application instead of it having a specific instance be bound to a specific request.
They actually have a pretty decent [HowTo](http://docs.autofac.org/en/latest/integration/webapi.html#provide-filters-via-dependency-injection) for Web API on the Autofac website which comes down to implementing the IAutofacExceptionFilter and using Property Injection to get the stuff resolved in your FilterAttribute.
There's also an [MVC HowTo](http://docs.autofac.org/en/latest/integration/mvc.html#enable-property-injection-for-action-filters), which comes down to calling RegisterFilterProvider to enable Property Injection for filters. |
10,756,385 | I have a collection of strings in C# MAINWINDOW.xaml.cs like this
```
public class NameList : ObservableCollection<Shortcuts>
{
public NameList() : base()
{
Add(new Shortcuts("ctrl", "b","s"));
Add(new Shortcuts("ctrl", "b","m"));
Add(new Shortcuts("ctrl", "b","p"));
Add(new Shortcuts("ctrl", "b","1"));
}
}
public class Shortcuts
{
private string firstkey;
private string secondkey;
private string lastkey;
public Shortcuts(string first, string second, string last)
{
this.firstkey = first;
this.secondkey = second;
this.lastkey= last;
}
public string Firstkey
{
get { return firstkey; }
set { firstkey = value; }
}
public string Secondkey
{
get { return secondkey; }
set { secondkey = value; }
}
public string Lastkey
{
get { return lastkey; }
set { lastkey = value; }
}
}
}
```
Then in the MainWindow.xaml itself I have a combobox and I would like to bind these items to the combobox so this is what I did
```
<Window x:Class="Testing_learning.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:Testing_learning"
Title="Outlook Context Settings" Height="350" Width="525">
<Window.Resources>
<c:ListName Key ="NameListData"/>
</Window.Resources>
```
oh BTW the project name is ***Testing\_learning*** that is why there is this
```
xmlns:c="clr-namespace:Testing_learning"
```
BUT the problem is that when i add this line of code
```
<Window.Resources>
<c:ListName Key ="NameListData"/>
</Window.Resources>
```
I get an error at c:ListName the type ListName was not found why is this?
Any thoughts?
Screenshot 1
![enter image description here](https://i.stack.imgur.com/uC5Bb.png)
Screenshot 2
![enter image description here](https://i.stack.imgur.com/9Y1Vm.png) | 2012/05/25 | [
"https://Stackoverflow.com/questions/10756385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/935913/"
] | It appears to be a typo? Your C# has NameList, but your XAML has ListName. |
33,316,794 | I am working with radio buttons and a submit button to send the inputs of the radio buttons to a javascript file called script.js. Whenever i click the submit button without selecting data from the radio buttons, the alert message "Please fill out all fields" does not show.
my code of index.php
```
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="script.js"></script>
<script>
$(document).ready(function() {
setInterval(function(){
_path = $('img').attr('src');
_img_id = _path.replace('img/img', '');
_img_id = _img_id.replace('.jpg', '');
_img_id++;
$('img').attr('src', 'img/img' + _img_id + '.jpg');
}, 15000);
});
</script>
</head>
<body id="page-top">
<header>
<h1><img src="img/img1.jpg" alt="image" style="width:738px;height:444px;"></h1>
<hr>
<label>Alignment: </label>
<input type="radio" name="group1" value="5"> 5
<input type="radio" name="group1" value="4"> 4
<input type="radio" name="group1" value="3"> 3
<input type="radio" name="group1" value="2"> 2
<input type="radio" name="group1" value="1"> 1
<hr>
<label>Blend: </label>
<input type="radio" name="group2" value="5"> 5
<input type="radio" name="group2" value="4"> 4
<input type="radio" name="group2" value="3"> 3
<input type="radio" name="group2" value="2"> 2
<input type="radio" name="group2" value="1"> 1
<hr>
<label>Warp: </label>
<input type="radio" name="group3" value="5"> 5
<input type="radio" name="group3" value="4"> 4
<input type="radio" name="group3" value="3"> 3
<input type="radio" name="group3" value="2"> 2
<input type="radio" name="group3" value="1"> 1
<hr>
<label>Overall: </label>
<input type="radio" name="group4" value="5"> 5
<input type="radio" name="group4" value="4"> 4
<input type="radio" name="group4" value="3"> 3
<input type="radio" name="group4" value="2"> 2
<input type="radio" name="group4" value="1"> 1
<hr>
<input type="submit" id="submit" name="submit" value="Submit">
</header>
</body>
</html>
```
my code of script.js
```
$(document).ready(function () {
$("#submit").click(function () {
var radio1 = $("input[name=group1]:checked").val();
var radio2 = $("input[name=group2]:checked").val();
var radio3 = $("input[name=group3]:checked").val();
var radio4 = $("input[name=group4]:checked").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = '&submit1=' + radio1 + '&submit2=' + radio2 + '&submit3=' + radio3 + '&submit4=' + radio4;
if (radio1 == '' || radio2 == '' || radio3 == '' || radio4 == '') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function (result) {
alert(result);
}
});
}
return false;
});
});
``` | 2015/10/24 | [
"https://Stackoverflow.com/questions/33316794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893845/"
] | It is because arrow functions are not generator functions. For example,
```
function temp() {
yield 1;
}
```
Can we expect this to work? No. Because `temp` is not a generator function. The same is applicable to arrow functions as well.
---
FWIW, the usage of `yield` in an Arrow function is an early error as per the ECMAScript 2015 specification, as per [this section](http://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions-static-semantics-early-errors),
>
> *ArrowFunction : ArrowParameters => ConciseBody*
>
>
> * It is a Syntax Error if *ArrowParameters* Contains *YieldExpression* is ***true***.
> * It is a Syntax Error if *ConciseBody* Contains *YieldExpression* is ***true***.
>
>
> |
56,858,011 | When I push new changes to my work branch, two executions are created for that push.
I've tried to reproduce this on other branches, but only happens on some branches of my repository. And I looked for this issue, but this seems to happens to no one.
[![Duplicated executions](https://i.stack.imgur.com/o69nq.png)](https://i.stack.imgur.com/o69nq.png)
[![Pipeline steps 1 and 2](https://i.stack.imgur.com/HvQWs.png)](https://i.stack.imgur.com/HvQWs.png)
[![Pipeline step 3](https://i.stack.imgur.com/DhBJd.png)](https://i.stack.imgur.com/DhBJd.png) | 2019/07/02 | [
"https://Stackoverflow.com/questions/56858011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11730646/"
] | I've found that my pipeline has 2 webhooks associated. I'm generating the pipeline and the Github webhook through AWS CLI, did this happen to someone? Is it possible that when I create the pipeline the creation is automatically generating the webhook and the association? |
6,622,672 | OK, I have set-up my breadcrumbs trial using IF segment and IF category\_id statements. The reason being is because I have different products linking into 2-3 categories etc...
I have completed the whole trial and all works fine (alot of coding though!)
However, ONE category i'm having a big issue with, i've tried for hours to rectify it but can't, basically this category is in 2 parents and 2 children categories, under the one category group... All of the others have only one parent and one child so my code works fine.
I've tried everything, but it is bringing up
>
>
> >
> > Toys >> Ben 10 >> Children >> Ben 10
> >
> >
> >
>
>
>
It's repeating both categories and parents because the entry is in both of these in the one group... So I tried creating two seperate if statements away from my main if statement, like this:
My code is:
```
{if segment_2 == "view"}
{exp:channel:entries channel="toys"}
{categories}
{if parent_id == "25"}
{if category_id == "31"}
<li>
<a href="(URL TO CATEGORY)">Toys</a>
</li>
<li>
<a href="{path='toys/list'}">{category_name}</a>
</li>
{/if}
{/if}
{/categories}
{/exp:channel:entries}
{/if}
{if segment_2 == "view"}
{exp:channel:entries channel="toys"}
{categories}
{if parent_id == "26"}
{if category_id == "40"}
<li>
<a href="(URL TO CATEGORY)">Children</a>
</li>
<li>
<a href="{path='toys/list'}">{category_name}</a>
</li>
{/if}
{/if}
{/categories}
{/exp:channel:entries}
{/if}
```
I would have assummed that defining the specific parent and cat id that this would display only one...
Any solutions? | 2011/07/08 | [
"https://Stackoverflow.com/questions/6622672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/808907/"
] | For debugging purposes, it's often helpful to understand and "visualize" what the structure of the data you're dealing with is.
To get a sense of the [categories](http://expressionengine.com/user_guide/modules/channel/categories.html) you're trying to wrangle for your breadcrumbs trail, use the following code to output each categories' `parent_id` and `category_id`:
```
{exp:channel:entries channel="toys"}
{categories}
<strong>{category_name}</strong> [{parent_id}, {category_id}]<br />
{/categories}
{/exp:channel:entries}
```
This will give you an output like:
```
Toys [0, 1] // Parent Category
Children [1, 2] // Child Category
```
Armed with this information, you can rework your conditional breadcrumbs to *deal with products classified in two or more categories*:
```
{exp:channel:entries channel="toys"}
{categories limit="2"}
{if parent_id == "0"}
<!-- Show the Parent Category -->
<li><a href="{path=toys/list}">{category_name}</a></li>
{/if}
{if parent_id != "0"}
<!-- Show the Child Category -->
<li><a href="{path=toys/list}">{category_name}</a></li>
{/if}
{/categories}
{/exp:channel:entries}
``` |
12,557 | Inspired by the answers to [this question](https://latin.stackexchange.com/questions/12543/formation-of-words-like-essive-or-adessive), I want to ask about the different present participles of *esse* over time and their fate. I am aware that *esse* is a defective verb that classically does not have a present participle. But there are frozen forms like *absens* suggesting an old form *\*sens* for a present participle, and there is *ens* calqued from Greek. The word *essentia* "essence", another calque from Greek, also suggests a form like *\*essens*. | 2019/09/26 | [
"https://latin.stackexchange.com/questions/12557",
"https://latin.stackexchange.com",
"https://latin.stackexchange.com/users/183/"
] | Good question!
In the beginning, way back in the far-flung times of Proto-Indo-European, the word for "it is" was something like \**h₁ésti*, and it had a fairly regular present participle, \**h₁sónts*. In Latin, these forms evolved into *est* and *sōns*, respectively (vowels get lengthened before *-ns*). The latter is where we get forms like *absēns* > "absent" and *praesēns* > "present", with vowel reduction in non-initial syllables. (This reduction evidently happened before the lengthening.)
But over time, the meaning of this word started to drift. In legal language, "the one who is" started to mean "the real one", then "the actual perpetrator", then "the guilty one", and eventually *sōns* became synonymous with *reus*. So it didn't really work as a participle any more.
People then made do without a present participle for quite a while, until they had to translate philosophical texts from Greek. The philosophical term *οὐσία* "essence" was formed from the Greek present participle plus the noun-forming *-ία*. And while the latter had a nice equivalent in Latin (*-ia*), the former didn't. So some translators took the infinitive *esse*, built a fake participle off that (\**essens*), and attached *-ia* onto the end of that, giving *essentia*. *Essentia* caught on (hence English "essence" and all its cognates), but \**essens* didn't.
Eventually, in Mediaeval Latin, people started to question the lack of a present participle (since Greek and Romance had one). The Ancient Greek one in particular was *ὤν* (also from \**h₁sónts*; initial `/s/` tended to vanish in Greek), which coincidentally looked just like the standard participle *ending* (as in *λύ-ων* "releasing"). So by analogy, they took the ending off the Latin present participle, and started using it as a word of its own: *curr-ēns, curr-entis* > *ēns, entis*. While it's not Classical, this is probably the most popular participle you'll find, and will be the most easily understood nowadays. |
56,019,046 | I am using mapply to find the sum of a range of indices for all cases:
```
score = mapply(function(x, y, z) sum(df[x, y:z]), seq_len(nrow(df)), df$index, df$index+10)
```
How can I add a ifelse statement to mapply so that it only applies the function if df$index >5, else the sum is 0? | 2019/05/07 | [
"https://Stackoverflow.com/questions/56019046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433663/"
] | This should probably work
```
mapply(function(x, y, z) if (y > 5) sum(df[x, y:z]) else 0,
seq_len(nrow(df)), df$index, df$index+10)
```
Or you could avoid `if`/`else` by multiplying by `(y > 5)` so `index > 5` would be multiplied by 1 (`TRUE`) giving `sum(df[x, y:z])` and `index <= 5` would be multiplied by 0 (`FALSE`) giving 0.
```
mapply(function(x, y, z) sum(df[x, y:z]) * (y > 5),
seq_len(nrow(df)), df$index, df$index+10)
``` |
10,451,767 | I'm using JDOM with my Android project, and every time I get a certain set of characters in my server response, I end up with these error messages:
05-04 10:08:46.277: E/PARSE: org.jdom.input.JDOMParseException: Error on line 95 of document UTF-8: At line 95, column 5263: unclosed token
05-04 10:08:46.277: E/Error Handler: Handler failed: org.jdom.input.JDOMParseException: Error on line 1: At line 1, column 0: syntax error
When I make the same query through google chrome, I can see that all of the XML came through fine, and that there are in fact no areas where a token is not closed. I have run into this problem several times throughout the development of the application, and the solution has always been to remove odd ascii characters (copyright logos, or trademark characters, etc. that got copied/pasted into those data fields). How can I get it to either a remove those characters, or b strip them and continue the function. Here's an example of one of my parse functions.
```
public static boolean parseUserData(BufferedReader br) {
SAXBuilder builder = new SAXBuilder();
Document document = null;
try {
document = builder.build(br);
/* XML Output to Logcat */
if (document != null) {
XMLOutputter outputter = new XMLOutputter(
Format.getPrettyFormat());
String xmlString = outputter.outputString(document);
Log.e("XML", xmlString);
}
Element rootNode = document.getRootElement();
if (!rootNode.getChildren().isEmpty()) {
// Do stuff
return true;
}
} catch (Exception e) {
GlobalsUtil.errorUtil
.setErrorMessage("Error Parsing XML: User Data");
Log.e(DEBUG_TAG, e.toString());
return false;
}
}
``` | 2012/05/04 | [
"https://Stackoverflow.com/questions/10451767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/879082/"
] | You could add this at the beginning of your function:
```
If Dir(FileName) = "" Then 'File does not exist
IsFileReadOnlyOpen = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
```
I agree with the comment that you should use enum to make it easier to understand.
PS: As commented by [Martin Milan](https://stackoverflow.com/questions/10451758/convert-function-so-as-to-give-3rd-state/10451898#comment13495405_10451898) this might cause issues. Alternatively, you can use this:
```
With New FileSystemObject
If .FileExists(FileName) Then
IsFileReadOnlyOpen = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
End With
``` |
38,895,396 | How can I achieve this effect?
The gray image is a background and the blue box is a img.
I am using Bootstrap.
In a large screen looks like this. There are two divs, each spanning 6 columns (out of 12).
[![Normal size](https://i.stack.imgur.com/07Hmj.png)](https://i.stack.imgur.com/07Hmj.png)
When resizing, for example in a mobile device, the text goes below the image.
[![Resized](https://i.stack.imgur.com/muD2n.png)](https://i.stack.imgur.com/muD2n.png) | 2016/08/11 | [
"https://Stackoverflow.com/questions/38895396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182172/"
] | You can resolve this using CSS multiple backgrounds.
Please see this example based on the example found on [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds) documentation:
```
<div class="multi_bg_example"></div>
.multi_bg_example {
width: 100%;
height: 400px;
background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png), url(https://mdn.mozillademos.org/files/11307/bubbles.png), linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
background-repeat: no-repeat, no-repeat, no-repeat;
background-position: 100px 100px, left, right;
background: -moz-linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), -webkit-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), -ms-linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
}
```
<https://jsfiddle.net/MadalinaTn/e79gb1w5/1/> |
95,535 | Is there an alternative to *.htaccess*, in case the webhoster disabled the use of *.htaccess* files?
I can set some PHP variables and headers inside the PHP files but how can I perform actions like `mod_rewrite` rules and default 404 pages? | 2016/06/22 | [
"https://webmasters.stackexchange.com/questions/95535",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/51752/"
] | >
> ...in case the webhoster disabled the use of .htaccess files?
>
>
>
If the webhost has *disabled* the use of `.htaccess` files then there is no direct alternative. (`.htaccess` = per-directory Apache config file)
`.htaccess` files are not necessary if you have access to the Apache server config. In fact, it is preferable to use the server config instead of `.htaccess` anyway, but by the sounds of it, you do not have that luxury.
>
> I can set some PHP variables and headers inside the PHP files
>
>
>
With PHP 5.3+ under CGI/FastCGI then you can use `.user.ini` files for per-directory PHP config settings. But that's just for PHP config settings, eg. `error_reporting`, `include_path`, etc. (Mind you, under CGI/FastCGI you *need* to use `.user.ini`, since you'll get a 500 internal server error if you try to use `php_flag` and `php_value` directives in .htaccess - these are for when PHP is installed as an Apache module.)
If your (shared) host has disabled `.htaccess` and you are wanting to do more that serve simple files then... find a new host.
Just to add, it's possible for the webhost to change the name used for per-directory Apache config files (ie. "`.htaccess` files") using the `AccessFileName` directive in the server config. However, I have never encountered a host that has done this and it might possibly break other software if it is changed. It is universally expected that the Apache per-directory config file is called "`.htaccess`". |
52,289,328 | I'm at the moment developing an app for tablets and the app isn't supposed to be available for phones.
When I edit an XML in Android Studio, there's the design preview that shows roughly how the XML will be rendered on the device. By default it's set to show it in a phone device. How do I set this to be a tablet view? | 2018/09/12 | [
"https://Stackoverflow.com/questions/52289328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25282/"
] | What happens here is that the script is interrupted by `SIGHUP` signal when your session is closed. To overcome this problem, there is a tool called `nohup` which doesn't pass the `SIGHUP` down to the program/script it executes. Use it as follows:
```
nohup python manage.py runserver &
```
(note the `&` in the end, it is needed so that `manage.py` runs in background rather than in foreground).
By default `nohup` redirects the output in the file `nohup.out`, so you can use `tail -f nohup.out` to watch the output/logs of your Django app.
Note, however, that `manage.py runserver` is **not supposed to be used in production**. For production you really should use a proper WSGI server, such as uWSGI or Gunicorn. |
247,536 | I'm redirecting tcpdump output from machine A to machine B.
A and B must use a "secure" connection, using VPN or ssh tunnel. I only care about authentication, however: I don't need to protect from sniffing data.
How much overhead should I expect using VPN/ssh compared to a "plain" connection? Bandwidth is a non issue for me, but CPU overhead is.
(If you are wondering the "redirection" happens starting tcpdump with telnet on vpn or ssh on a plain connection) | 2011/03/15 | [
"https://serverfault.com/questions/247536",
"https://serverfault.com",
"https://serverfault.com/users/13192/"
] | It shouldn't be an issue at all, you should be able to do this both through SSH or OpenVPN with minor overhead, but you need to filter out from tcpdump the traffic that you're sending to your host B to avoid consuming your bandwidth on dump traces about that traffic.
`tcpdump [options here] src host not B or dst host not B` should do the trick for you |
38,643,837 | I just created a fresh laravel project and I'm using a Homestead vagrant box by running
>
> vagrant init laravel/homestead
>
>
>
and after
>
> Vagrant Up
>
>
>
When I use `vagrant ssh` it gives me no problem and I can acces the vagrant box, however when I want to connect to the DB with Heidisql I get a connection error:
>
> can't connect to mysql server on 'localhost' (10061)
>
>
>
Here's my setup
[![enter image description here](https://i.stack.imgur.com/vMO1x.png)](https://i.stack.imgur.com/vMO1x.png)
[![enter image description here](https://i.stack.imgur.com/tohxr.png)](https://i.stack.imgur.com/tohxr.png)
the password I'm using = "secret" | 2016/07/28 | [
"https://Stackoverflow.com/questions/38643837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5490695/"
] | The usual credentials/info you need:
* IP address 192.168.10.10 (Check your Homestead Folder>Homestead.yaml)
* Port: 3306
* User: homestead (all lowercase)
* Pw: secret |
67,583,219 | I have the following code to download media from chat:
```
getmessage = client.get_messages(dialog, limit=1000)
for message in getmessage:
try:
if message.media == None:
print("message")
continue
else:
print("Media**********")
client.download_media(message)
```
I want to limit the download media size to X MB,
How can I get the media size in bytes before I download it? | 2021/05/18 | [
"https://Stackoverflow.com/questions/67583219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15935819/"
] | You can refer to the [Objects Reference for `Message`](https://docs.telethon.dev/en/latest/quick-references/objects-reference.html#message) to find out the [`message.file`](https://docs.telethon.dev/en/latest/modules/custom.html#telethon.tl.custom.message.Message.file) property. It will be a [`File`](https://docs.telethon.dev/en/latest/modules/custom.html#telethon.tl.custom.file.File) object with a [`size` property](https://docs.telethon.dev/en/latest/modules/custom.html#telethon.tl.custom.file.File.size). Thus:
```py
if message.media:
print(message.file.size, 'in bytes')
```
Note that `file` will be `None` for media like polls. |
202,160 | Let's say I have this pattern and a large array:
```
String [] pattern = new String[]{"i","am","a", "pattern"};
String [] large_array = new String[]{"not","i","am","a", "pattern","pattern","i","am","a", "pattern", "whatever", "x", "y", i","am","a", "pattern",................, i","am","a", "pattern" ....};
```
As you can see the pattern appears multiple times in the array. The first time at index 1, the second time at index 6, etc... I want to find out at which positions the pattern begins and return it in a collection (eg list).
In this case the position array is
1,6,13, etc...
Here is my current method:
```
private ArrayList<Integer> getStartPositionOfPattern(String[] headerArray, String[] pattern) {
ArrayList<Integer> allPositions = new ArrayList<>();
int idxP = 0, idxH = 0;
int startPos = 0;
while (idxH < headerArray.length) {
if (pattern.length == 1) {
if (pattern[0].equals(headerArray[idxH])) {
allPositions.add(idxH);
}
} else {
if (headerArray[idxH].equals(pattern[idxP])) {
idxP++;
if (idxP == pattern.length) { //you reached end of pattern
idxP = 0; //start Pattern from begining
allPositions.add(startPos); //you can save startPosition because pattern is finished
}
} else {
idxP = 0;
startPos = idxH + 1;
if (pattern[idxP].equals(headerArray[idxH])) { //if current arrray.idxH is not pattern.idxP but array.idxH is begining of pattern
startPos = idxH;
idxP++;
}
}
}
idxH++;
}
return allPositions;
}
```
Is there a way to make my function more readable and faster? I believe it works correctly, but because the function is complex, I worry I might have an undetected bug.
NOTE: `headerArray` is the large array. | 2018/08/21 | [
"https://codereview.stackexchange.com/questions/202160",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/175306/"
] | The easiest way is to use the `numpy` interface for this, since it allows you to do operations on the whole image:
```
from PIL import Image
import numpy as np
def _colour_mask(img, colour):
"""Finds all indices of a single colour in a PIL.Image"""
if len(img.shape) == 3:
return (img == colour).all(axis=2).nonzero()
elif len(image.shape) == 2:
return (img == colour).nonzero()
else:
raise ValueError("Invalid image shape {}".format(img.shape))
def _convert_colour(img, incolour, outcolour):
"""Replaces incolour with outcolour in a PIL.Image.
Returns a new PIL.Image.
Assumes that img has as many channels as len(incolour) and len(outcolour).
"""
img = np.array(img)
img[_colour_mask(img, incolour)] = outcolour
return Image.fromarray(img)
def convert_colour(region_number, incolour, outcolour):
file_name = region_list.regions_d[region_number][0]
img = Image.open(file_name)
new_img = _convert_colour(img, incolour, outcolour)
new_img.save(file_name, "PNG")
colour_change_single(region_number, outcolour)
``` |
26,502,788 | i have a Listview that i use like a gridview. inside the itemtemplate i have only a 'modifyble' field, a dropdownlist.
I would like to fire a 'Save' event when user change the dropdownlist. I know i have to set up the autopostback = true of the dropdownlist but i don't know how to fire the event because visual studio don't allow me to create the 'on change event' of the dropdownlist when it is inside a listview.
This is my code example
```
<asp:ListView ID="lvDmr" runat="server" DataSourceID="dsDmr" DataKeyNames="id">
<ItemTemplate>
<table style="width: 100%;" cellspacing="0" cellpadding="8">
<tr style="width: 100%;">
<td class="colonna-griglia" style="width: 5%;">
<%# Convert.ToDateTime(Eval("data_rilevazione")).ToString("d") %>
</td>
<td class="colonna-griglia">
<%# Eval("rivista")%>
</td>
<td class="colonna-griglia">
<asp:DropDownList runat="server" ID="myComboBox" DataSourceID="dsAgenti" DataTextField="customer"
DataValueField="customer" Width="150px" AutoPostBack="true">
</asp:DropDownList>
</td>
...
....
</asp:listview>
``` | 2014/10/22 | [
"https://Stackoverflow.com/questions/26502788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/141579/"
] | You may not get this in `designer` view, but if you directly add `event` handler it will definitely work. Following are code snippet for this.
1. Add `OnSelectedIndexChanged="myComboBox_SelectedIndexChanged"` to `myComboBox`.
>
>
> ```
> <asp:DropDownList runat="server" ID="myComboBox" DataSourceID="dsAgenti" DataTextField="customer"
> DataValueField="customer" Width="150px" AutoPostBack="true" OnSelectedIndexChanged="myComboBox_SelectedIndexChanged">
> </asp:DropDownList>
>
> ```
>
>
2. Next in serverside , use following for `event` handler.
>
>
> ```
> protected void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
> {
> DropDownList ddlListFind = (DropDownList)sender;
> ListViewItem item1 = (ListViewItem)ddlListFind.NamingContainer; // item1, is current row of Listview, which hold the dropdownlist that caused postback.
> }
>
> ```
>
>
More help - <http://forums.asp.net/t/1357900.aspx?SelectedIndexChanged+of+a+DropDownList+which+is+inside+a+ListView> |
16,974,639 | I need to create an application that will run on a server and be able to be configured to run commands at certain times. For instance, there will be a web interface allowing a user to set an engage time and a disengage time. Once those values have been saved by the user I need for the server to be able to fire off those commands precisely at the time specified each day.
I would also need to be able to set single use non recurring events that would occur... maybe 10 minutes from the time an event was triggered and have a command fired off when that 10 minute timer goes off.
I've already got a class library written that has the engage and disengage commands exposed. I would hope to be able to integrate this into whatever solution I end up with and simply be able to make calls directly to the class. Alternatively I could also compile the class library into an executable and have commands issued to it via command line. I'm hoping to not have to do the latter.
I've never written anything like this before. I've peeked a bit at Windows Services, but there is a lot of chatter out there saying that it isn't necessarily the best option. Can someone please guide me in the right direction please? | 2013/06/07 | [
"https://Stackoverflow.com/questions/16974639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/410167/"
] | A windows service is not a bad idea, its perfect for this kind of application. Unless you end up using standard windows scheduled tasks as the trigger for your command, you need some sort of process that is always running to contain your scheduler. A windows service is an excellent candidate for this.
Using a windows service in conjunction with Quartz.NET and some sort of persistence layer so you can store your schedules (in case you need to restart the service or it crashes etc) would be a good way to go.
Alternatively, you could write an application that just adds and removes windows scheduled tasks, but considering you have existing class libraries, using Quartz.NET will fit in well with your existing libraries. |
23,624,650 | I've looked through the API documentation on Instagram and researched the web, but I haven't been able to find a consistent answer to whether it's possible to download your own Instagram photos via a web app.
For example, I'm trying to write a web app which allows users to authenticate into their Instagram account, and then download all their Instagram photos into the web app and display it.
The closest thing I've seen on Instagram is the following url: <http://instagram.com/developer/endpoints/media/#get_media>
But can someone confirm if this is the correct endpoint? Also, if this is the correct endpoint, assuming that I uploaded a high-resolution photo, would that photo be available for me to download in high resolution via the API? | 2014/05/13 | [
"https://Stackoverflow.com/questions/23624650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849876/"
] | You can do it easy with Google Chrome and you don't need the API:
I wrote a small ES6 script that does just this ( let's you view and save instagram images and videos on right click )
Here's the code:
```
document.addEventListener('contextmenu', (event) => {
const elements = document.elementsFromPoint(event.clientX, event.clientY);
const mediaSource = elements.find(element => /img|video/gi.test(element.tagName)).getAttribute('src');
mediaSource && window.open(mediaSource, '_blank');
});
```
What it does is when you click on image or video, it get's all elements under the mouse, finds the image/video and opens it in new tab. Then you save it.
Also, it's available as a [Chrome Extension](https://instasee.me) |
52,522,236 | I'm transforming the data in a table, and then inserting that transform into a new table. I don't want the new table to contain certain values from the transform, so is there a proper way to do the following?
```
INSERT INTO #transformed (NewValue)
SELECT func_doTransformation(ot.OldValue)
FROM OriginalTable ot
WHERE func_doTransformation(ot.OldValue) <> 'bad data'
```
I've considered doing an `INSERT ...` followed by a `DELETE ... WHERE`, but that seems only slightly less inefficient than calling `func_doTransformation` twice. | 2018/09/26 | [
"https://Stackoverflow.com/questions/52522236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368/"
] | I would use a CTE in this scenario.
```
; WITH cte AS (SELECT Val = func_doTransformation(ot.OldValue) FROM OriginalTable ot)
INSERT INTO #transformed (NewValue)
SELECT Val FROM cte WHERE Val <> 'Bad Data';
``` |
51,720,145 | I have a `boost::fusion::map` like this:
```
struct bar {};
struct baz {};
template<typename... Args>
struct foo
{
foo(bar &, baz &) {}
};
template<typename... T>
using MapEntry = boost::fusion::pair<boost::mpl::set<T...>, foo<T...>>;
using Map = boost::fusion::map<
MapEntry<int, bool, double>,
MapEntry<std::string>,
MapEntry<int64_t, uint32_t>,
MapEntry<char, uint64_t>
// ...
>;
```
then need to initialize instanse of `Map`, passing `bar_` and `baz_` into all `foo` constructors.
At the moment, I have :
```
int main()
{
bar bar_;
baz baz_;
Map map_(
boost::fusion::make_pair<boost::mpl::set<int, bool, double>>(foo<int, bool, double>(bar_, baz_)),
boost::fusion::make_pair<boost::mpl::set<std::string>>(foo<std::string>(bar_, baz_)),
boost::fusion::make_pair<boost::mpl::set<int64_t, uint32_t>>(foo<int64_t, uint32_t>(bar_, baz_)),
boost::fusion::make_pair<boost::mpl::set<char, uint64_t>>(foo<char, uint64_t>(bar_, baz_))
// ...
);
return 0;
}
```
But this is very redundant. Is it possible to make this code cleaner ? | 2018/08/07 | [
"https://Stackoverflow.com/questions/51720145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226448/"
] | At first create a function to create `MapEntry`
```
template<typename E, typename... Args>
E make_map_entry(Args &&...args)
{
return boost::fusion::make_pair<E::first_type>(E::second_type(std::forward<Args>(args)...));
}
```
At second create a function to create `Map`, it uses helper function that unroll `make_map_entry` for each entry
```
template<typename M, std::size_t ...I, typename... Args>
M make_map_impl(std::index_sequence<I...>, Args &&...args)
{
return M(make_map_entry<boost::fusion::result_of::value_at_c<M, I>::type>(std::forward<Args>(args)...)...);
}
template<typename M, typename... Args>
M make_map(Args &&...args)
{
return make_map_impl<M>(std::make_index_sequence<boost::fusion::result_of::size<M>::value> {}, args...);
}
```
then we can write
```
int main()
{
bar bar_;
baz baz_;
Map map(make_map<Map>(bar_, baz_));
return 0;
}
``` |
30,610 | As some background I've been building Electrophysiological models of neurons, and in the process stumbled upon a model, that in all respects is biologically plausible, but has a bizarre property I didn't think happened in nature. It spikes in response to hyper polarized currents.
My particular model has only one ion channel which is has similar properties to Hodgkin-Huxley's transient sodium channel. It has one activation gate and one inactivation gate. The reason I only use a single Ion Channel was I was exploring If I could create a minimal spiking neuron with just a single channel. The answer is yes, but has different properties then I expected.
Basically when I inject a hyper-polarizing current it spikes and depolarizing current causes it to stop spiking.
I know that Depolarization block can occur, my current isn't that High, in fact its no current produces no spikes. It has a normal rest potential around -55 mV and Fires upward to about +40 mV.
Also note that If I change the parameters around I get a more normal neuron that spikes in response to depolarizing currents. So the property must be somehow related to the ion channel kinetics.
The question is: Are there biological neurons that spike when hyper-polarizing currents are injected? | 2015/03/20 | [
"https://biology.stackexchange.com/questions/30610",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/13388/"
] | **Short answer**
Action potentials are always generated after a depolarization step.
**Background**
Action potentials are generated by prior depolarization of a neuron, typically by the action of an excitatory neurotransmitter. An action potential is per definition a sharp depolarization, followed by a somewhat slower re-polarization step. The most important step in an action potential is the activation of voltage-gated sodium channels (VGSCs). VGSCs open when the membrane potential exceeds a certain voltage upon depolarization ([Liu et al. 2012](http://www.ncbi.nlm.nih.gov/pubmed/23095258)), in turn initiating the depolarization step of the action potential. Hence, action potentials are always generated through depolarization.
The only ion channel I am aware of that may mediate a hyperpolarization-induced cation influx resembling that seen in VOSCs is the hyperpolarization-activated cyclic nucleotide-gated (HCN) class of channels. The associated current (Ih) is a non-specific cation flux (Na+, Ca2+). The HCN channel opens when the membrane potential hyperpolarizes. Thereby it generates a relatively small positive, depolarizing influx current. it is mainly involved in setting the frequency of pacemaker activity in, e.g., thalamic relay neurons that are involved in the oscillatory cortical activity characteristic of slow-wave sleep. However, Ih itself does not elicit spikes, it generates excitatory postsynaptic currents (EPSCs) associated with excitatory postsynaptic potentials (EPSPs), but not full blown spikes [(McCormick & Pape, 1990)](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1181775/).
**Model evaluation and recommendations**
1. Perhaps you identified EPSPs as action potentials? They are not.
2. Your resting membrane potential is very high (depolarized) - a more typical value is [**-70 mV**](http://www.columbia.edu/cu/psychology/courses/1010/mangels/neuro/neurosignaling/neurosignaling.html).
3. VOSCs are opened at around [**-50 mV**](http://www.columbia.edu/cu/psychology/courses/1010/mangels/neuro/neurosignaling/neurosignaling.html), hence your resting membrane potential is awfully close to action potential threshold. Any small perturbation leading to a bit cation influx will trigger action potentials. With a bit of stochastic leak currents included, a spontaneous spiking neuron is what you get. Ih (-like) activity may also set the stage for your out-of-the-ordinary observation.
4. Suggestion - lower your resting membrane potential to a more conservative value (-70 mV) and check the difference between EPSPs and action potentials. If you look at the following figure you can see that at your chosen resting membrane potential you are hovering between EPSP / actin potential threshold. A bi-stable situation results.
![AP vs EPSP](https://i.stack.imgur.com/SyXci.jpg)
Action potential versus EPSP. [Source: What when and how](http://what-when-how.com/neuroscience/synaptic-transmission-the-neuron-part-1/)
**References**
[Liu et al. *BMC Neurosci* 2012;**25**:2-9](http://www.ncbi.nlm.nih.gov/pubmed/23095258)
[McCormick & Pape. *J Physiol* 1990;**431**:291-318](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1181775/) |
365,986 | I am trying to redirect non-existing woocommerce product's url's to worpdress page.
Example:
<https://testname.com/product/abc> to <https://testname.com/sample-page>
here there is no product published as abc.
also i have few working products at <https://testname.com/product/def>.
i tried with .htaccess but looks like it's not possible to use .htaccess in this case.
Thanks in advance. | 2020/05/06 | [
"https://wordpress.stackexchange.com/questions/365986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5669/"
] | If you prefer more control in coding, you may use
* [request hook](https://developer.wordpress.org/reference/hooks/request/) - test the WordPress query after it is being setup
* [preg\_match()](https://www.php.net/manual/en/function.preg-match.php) - match `/product/` keyword
* [url\_to\_postid()](https://developer.wordpress.org/reference/functions/url_to_postid/) - test if product url exists
to build a checking when `WordPress query is being setup`. The advantage of code against .htaccess is that it is relatively server independent such as server migration, site migration and so on.
The following code is placed in theme functions.php and proved to work in a testing site.
```
add_filter( 'request', 'ws365986_check_request' );
function ws365986_check_request( $query ) {
// var_dump($_SERVER['REQUEST_URI']); // for debug
// only check for product url if /product/ is found in URL
if( isset( $_SERVER['REQUEST_URI'] ) && preg_match( '/\/product\//', $_SERVER['REQUEST_URI'], $matches ) ) {
// check if url product exist
if( empty( url_to_postid( $_SERVER['REQUEST_URI'] ) ) ) {
// redirect if return is 0 (empty)
$url = home_url( '/sample-page' );
// wp_redirect( $url ); // because $url is prepared by internally, wp_redirect should be enough
wp_safe_redirect( $url );
exit(); // exit script after redirect
}
}
// default
return $query;
}
``` |
74,360,790 | I have without success tried to figure out how to most efficiently fetch data with powershell from the below JSON that is returned to me by a REST API:
```
{
"$schema": "api:standardResponse",
"links": [
{
"rel": "canonical",
"href": "http://localhost:8501/services/v2/replicats",
"mediaType": "application/json"
},
{
"rel": "self",
"href": "http://localhost:8501/services/v2/replicats",
"mediaType": "application/json"
},
{
"rel": "describedby",
"href": "http://localhost:8501/services/v2/metadata-catalog/replicats",
"mediaType": "application/schema+json"
}
],
"messages": [],
"response": {
"$schema": "ogg:collection",
"items": [
{
"links": [
{
"rel": "parent",
"href": "http://localhost:8501/services/v2/replicats",
"mediaType": "application/json"
},
{
"rel": "canonical",
"href": "http://localhost:8501/services/v2/replicats/RNIMDA00",
"mediaType": "application/json"
}
],
"$schema": "ogg:collectionItem",
"name": "RNIMDA00"
},
{
"links": [
{
"rel": "parent",
"href": "http://localhost:8501/services/v2/replicats",
"mediaType": "application/json"
},
{
"rel": "canonical",
"href": "http://localhost:8501/services/v2/replicats/RNIMDA01",
"mediaType": "application/json"
}
],
"$schema": "ogg:collectionItem",
"name": "RNIMDA01"
},
{
"links": [
{
"rel": "parent",
"href": "http://localhost:8501/services/v2/replicats",
"mediaType": "application/json"
},
{
"rel": "canonical",
"href": "http://localhost:8501/services/v2/replicats/RNIMDA02",
"mediaType": "application/json"
}
],
"$schema": "ogg:collectionItem",
"name": "RNIMDA02"
}
]
}
}
```
I only need the data from the "name": node, and the data from the "href": node.
I have done some searching and found som examples where the JSON is converted with **ConvertFrom-Json** and then iterated with a foreach like the pseudo code below:
```
$users = $response | ConvertFrom-Json
foreach ($user in $users)
{
write-host "$($user.name) has the email: $($user.email)"
}
```
But I wonder if there is a better way of fetching data with powershell from a object that contains JSON.
Thanks :) | 2022/11/08 | [
"https://Stackoverflow.com/questions/74360790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10046570/"
] | It is not really clear what your desired output should be.
Let's assume you have the JSON data converted in a variable $json using `$json = $response | ConvertFrom-Json`
Then if you do:
```
$json.response.items | Select-Object name, @{Name = 'href'; Expression = {$_.links.href}}
```
You will get objects with a `name` and a `href` property, where the `href` will be an array.
PowerShell would output this on screen as
```
name href
---- ----
RNIMDA00 {http://localhost:8501/services/v2/replicats, http://localhost:8501/services/v2/replicats/RNIMDA00}
RNIMDA01 {http://localhost:8501/services/v2/replicats, http://localhost:8501/services/v2/replicats/RNIMDA01}
RNIMDA02 {http://localhost:8501/services/v2/replicats, http://localhost:8501/services/v2/replicats/RNIMDA02}
```
If however you would like to return an object for each of the href values inside the links nodes you can do:
```
$json.response.items | ForEach-Object {
$name = $_.name
foreach ($link in $_.links) {
[PsCustomObject]@{
name = $name
href = $link.href
}
}
}
```
which will output
```
name href
---- ----
RNIMDA00 http://localhost:8501/services/v2/replicats
RNIMDA00 http://localhost:8501/services/v2/replicats/RNIMDA00
RNIMDA01 http://localhost:8501/services/v2/replicats
RNIMDA01 http://localhost:8501/services/v2/replicats/RNIMDA01
RNIMDA02 http://localhost:8501/services/v2/replicats
RNIMDA02 http://localhost:8501/services/v2/replicats/RNIMDA02
``` |
41,535,673 | ```
if (int.Parse(q.textBoxNumberOfEmployees.Text) < 15)
{
Rect1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
}
```
scenario: main window and a child window, mainWindowButton opens the child window and the user enters information, when the user enters information the child window closes and in the main window a rectangle shows filled accordingly. Everything works!
But when i click on the child window's "x" to close the window manually it shows me this error, only then! I looked for an answer in previous questions similar to mine, but none have the exact problem.
All the code is in the MainWindowButton\_ClickEvent | 2017/01/08 | [
"https://Stackoverflow.com/questions/41535673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6655445/"
] | It is possible the user does not enter an integer into `q.textBoxNumberOfEmployees` so you need to handle that.
**Approach 1**
```
var numOfEmployees;
if (!int.TryParse(q.textBoxNumberOfEmployees.Text, out numOfEmployees))
{
// What do you want to do? The user did not enter an integer.
}
// Proceed normally because user entered integer and it is stored in numOfEmployees
```
**Approach 2**
Only allow the user to enter numbers into the textbox as shown in [this](https://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) answer. Since you have that check in multiple places, I would create a user control for this so it allows only numbers. Then use that user control every where it is needed. It is up to you which approach you want to go with. |
86,040 | I need a thermally AND electrically conductive heat sink compound for attaching power transistors to an aluminium heat sink. I've given Coollaboratory's LiquidPro a try and that oxidized the aluminium. Artic Silver 5 was completely the wrong solution, not conductive at all (I had some exploding FETs on my hands).
Any suggestions? | 2013/10/21 | [
"https://electronics.stackexchange.com/questions/86040",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/23014/"
] | I hardly can see why you need a conductive paste? The aluminum is covered with thin insulation layer of Al-oxide and will break the electrical contact anyway with the time, regardless of the paste properties.
1. If you need the heat sink to be electrically connected to the element - use a wire instead and screw it on the heat sink.
2. Use copper heat sink and solder the element on it - this way you will get the best electrical and thermal contact possible and very effective heat sink at the same time. (Use very thin solder layer). |
19,302,063 | I'm have a really weird bug, heres the setup:
I have a web app running in openshift, all is good and runs great in Chrome, Firefox, Internet Explorer, Safari and Android WebView.
But because I need some hardware level access for a few functions, I created a JavaFX application running a WebView with a JavaScript interface for the hardware functions.
Everything works and runs (although with low FPS) except for the Bootstrap 3 Glyphicons.
**Here is a screenshot from Chrome:**
![Here is a screenshot from Chrome](https://i.stack.imgur.com/Fcruv.png)
**Here is a screenshot from JavaFX WebView**
![Here is a screenshot from JavaFX WebView](https://i.stack.imgur.com/Y0gY7.png)
**The RIA, client side is running:**
-Bootstrap 3 and Glyphicons (from the CDN)
-Bootstrap Modal (from the server)
-JQuery 2.0.3 (from CDN)
-AngularJS (from CDN)
**UPDATE:**
After some testing, it appears that Glyphicons from Bootstrap 2.3.2 do work as expected inside JavaFX. But I'm not willing to go back to BS 2.3.2 | 2013/10/10 | [
"https://Stackoverflow.com/questions/19302063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599609/"
] | Bootstrap glyph icons show in [Java 8](https://jdk8.java.net/download.html).
This is (likely) because JavaFX in [Java 8 adds @font-face support](http://fxexperience.com/2012/12/use-webgoogle-fonts-in-javafx/) which was not present in Java 7 (JavaFX 2.2).
Related JavaFX issue tracker issues which added support in Java 8:
* [RT-10343 CSS add support for CSS3 @font-face](https://javafx-jira.kenai.com/browse/RT-10343) (uses JavaFX css styles).
* [RT-17428 WebView-component to render CSS @font-face declarations](https://javafx-jira.kenai.com/browse/RT-17428) (uses HTML css styles). |
45,274,836 | I am running c# tests using ShouldBe and I have this code:
```
int x = 3;
int y = 3;
x.ShouldBeSameAs(y);
```
Problem is it throws exception:
>
> An exception of type 'Shouldly.ShouldAssertException' occurred in
> Shouldly.dll but was not handled in user code
>
>
>
Additional information: x
```
should be same as
```
3
```
but was
```
3
How can I test equality of to integers with ShouldBe? | 2017/07/24 | [
"https://Stackoverflow.com/questions/45274836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6001456/"
] | According to the documentation `ShouldBeSameAs` uses reference equality.
Use `ShouldBe`.
See documentation [here](https://github.com/shouldly/shouldly). |
38,317,547 | I'm trying to make a script to autoinstall packages on Windows, and I keep getting
>
> =y was unexpected at this time
>
>
>
What's wrong with it?
```
@echo off
echo Checking Internet...
Ping www.google.com -n 1 -w 1000
cls
if errorlevel 1 (set internet=n) else (set internet=y)
if %internet%=y goto start
if %internet%=n goto warn
:warn
echo Warning! You are not connected to the Internet.
echo Chocolatey will not install until you connect and
echo run this batchfile again.
echo Press any key to continue anyways.
pause >nul
:start
echo Copying...
echo [sudo.exe]
mkdir C:\pkg
copy sudo.exe C:\pkg
sudo xcopy C:\pkg\sudo.exe C:\Windows
echo [chocolatey.bat]
copy chocolatey.bat C:\pkg
echo [package.bat]
copy package.bat C:\pkg
echo Installing Choco...
if %internet%=y sudo C:\pkg\chocolatey.bat
if %internet%=n echo Cancelled: No internet.
echo Press any key when complete.
pause >nul
echo Installing Packages...
if %internet%=y sudo C:\pkg\package.bat
if %internet%=n echo Cancelled: No internet.
echo Press any key when complete
```
Note: I use "sudo.exe" to elevate privileges. I'm not trying to use bash in windows. | 2016/07/11 | [
"https://Stackoverflow.com/questions/38317547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6576788/"
] | ### I keep getting "=y was unexpected at this time" What's wrong with it?
```
if %internet%=y goto start
```
`=` is not a valid comparison operator, you should be using `==`:
```
if %internet%==y goto start
```
That applies to all of your `if %internet%` commands.
---
### Syntax
```
F:\test>if /?
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
NOT Specifies that Windows should carry out
the command only if the condition is false.
ERRORLEVEL number Specifies a true condition if the last program run
returned an exit code equal to or greater than the number
specified.
string1==string2 Specifies a true condition if the specified text strings
match.
```
---
### Further Reading
* [An A-Z Index of the Windows CMD command line](http://ss64.com/nt/) - An excellent reference for all things Windows cmd line related.
* [if](http://ss64.com/nt/if.html) - Conditionally perform a command. |
62,718,824 | I want to have a viewController (graphsVC) on which there will be a data entry field and 6 to 10 buttons for the user to select a graph type.
I'd like to programmatically:
* create a UIView on this viewController in which the selected graph will be drawn depending on which button is pressed.
* assign the UIView a particular class based on a button the user selects (each class uses `draw` to create the selected graph).
* if the user then selects a different button, I want to remove that UIView and recreate it with a different class corresponding to that choice.
* if the user changes the data, I want the graph to update itself.
Basically this pseudo-code:
```
func createViewWithCustomClass(selectedGraph)
{
create new UIView on graphsVC with selectedGraph's class
set view parameters for selected graph
}
func buttonX (selectedGraph)
remove previous view
create new view with new class
}
```
So, I began with this :
```
func createGraphView(selectedGraph: Int) {
let graphView = UIView.init()
// set view's size, location, colors, etc. according to selectedGraph
switch selectedGraph {
case 0: // set custom parameters for graph 0
case 1: // set custom parameters for graph 1
// etc.
default: break
}
}
```
Each button has code similar to this:
```
@IBAction func buttonGraph0(_ sender: UIButton) {
graphView.removeFromSuperView() // remove existing view
createGraphView(selectedGraph: 0) // create new view (how to assign another class???)
}
```
But this button's function does not have access to the `graphView`. So I moved `let graphView = UIView.init()` outside the function but now don't know how to assign it a class. (Clearly I am floundering!)
```
var graphView = UIView.init()
func createGraphView(selectedGraph: Int) {
// set graph size, location, colors, etc.
}
``` | 2020/07/03 | [
"https://Stackoverflow.com/questions/62718824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8635708/"
] | You need to write a view controller for each graph type. Then in your createViewWithCustomClass, just assign the VC to use the UIView and let the new VC do the work. Here's an example;
```
var graphTypeVCNames = ["graph1VC", "graph2VC", "graph3VC"]
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: graphTypeVCNames[selectedGraph]) // as! CustomViewController
vc.view.frame = subView.bounds
self.addChild(vc)
self.subView.addSubview(vc.view)
vc.didMove(toParent: self)
```
Also, you should remove each one when you add a new one. |
3,651,308 | $$f(x)=\left\{\begin{matrix} \sin x, & x \in \Bbb Q\\
0, & x \in \Bbb R\backslash \Bbb Q\end{matrix}\right.$$
1. Prove that $f$ is differentiable at $x=0$
2. Find $f'(0)$
What I did was $f'(0)= \lim\_{x\to0} \dfrac{\sin x-\sin0}{x-0} = \lim\_{x\to0} \dfrac{\sin x}{x}$
And I don't know how to go from there, please help. | 2020/04/30 | [
"https://math.stackexchange.com/questions/3651308",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/753271/"
] | $f$ is not differentiable at $0$ !
First note that $f(0)= \sin 0=0,$ since $0$ is rational.
Now let $(r\_n)$ be a sequence in $ \mathbb Q \setminus \{0\}$ such that $r\_n \to 0.$ Then
$$ \frac{f(r\_n)-f(0)}{r\_n -0}= \frac{ \sin r\_n}{r\_n } \to 1,$$
as $n \to \infty.$
$If (s\_n)$ is a sequence in $ \mathbb Q^c$ such that $s\_n \to 0.$ Then
$$ \frac{f(s\_n)-f(0)}{s\_n -0}= 0 \to 0,$$
as $n \to \infty.$ |
13,045 | How to find the smallest difference between two numbers in a sorted list using divide-and-conquer approach? For example,
```
(smallest-dif '(5 500 510 670 750 10000)) => 10
``` | 2013/07/03 | [
"https://cs.stackexchange.com/questions/13045",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/8983/"
] | The smallest difference between two numbers in a sorted list is given by the difference between some consecutive numbers in the list. This can be found out in linear time without using a divide and conquer approach. Since you have a `O(n)` algorithm which is the least possible time required to solve this problem it is not advisable to use a divide and conquer approach. |
50,890,977 | While going through the slides of a lecture on memory management, I came across this:
>
> Relocation register value is static during program execution. Hence all of the OS must be present (it might be used). Otherwise, we have to relocate user code/data “on the fly”! In other words, we cannot have transient OS code
>
>
>
I couldn't understand what the above lines meant. I would appreciate if anyone could explain this. | 2018/06/16 | [
"https://Stackoverflow.com/questions/50890977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8992384/"
] | The relocation-register scheme provides an effective way to allow the
operating system’s size to change dynamically. This flexibility is desirable in
many situations. For example, the operating system contains code and buffer
space for device drivers.
If a device driver (or other operating-system service) is not commonly used, we do not want to keep the code and data inmemory, as
we might be able to use that space for other purposes. Such code is sometimes
called transient operating-system code; it comes and goes as needed. Thus,
using this code changes the size of the operating system during program
execution. |
29,450,910 | i have a draggable list, a sortable-droppable list and a couple of li's inside the first.
now i want to pull them over, in the stop-funtion i have a function that adds a class to the first child (it's a span representing the clip-number like
```
<li>
<span>1.</span>
<span>Title</span>
<span>1min23sec</span>
</li>
```
). the reason for this is, i want to represent the original clip number in the playlist(sortable).
but i get a console error saying
```
TypeError: ui.children is not a function
ui.children("li")[0].addClass(".slot_clip_info");
```
i am not 100% sure, but i think this exact code HAS already worked in the past time, i might have changed somthing without knowing, but i am not aware of that.
draggable:
```
$(function() {
$(".pl_clipEntry").draggable({
appendTo: "body",
revert: "invalid",
connectToSortable: "#tracks",
distance: 20,
helper: function(){
return $(this).clone().width($(this).width()); // hack for the drag-clone to keep the correct width
},
stop: function(ui) {
ui.children("li")[0].addClass(".slot_clip_info");
},
zIndex: 100
});
});
```
sortable:
```
$(function() {
var removeItem;
$("#tracks").sortable({
items: "li:not(.placeholder)",
connectWith: "li",
placeholder: "sort_placeholder",
helper: "clone",
distance: 20,
sort: function () {
$(this).removeClass("ui-state-default");
updatePlaylist();
},
over: function (event,ui) {
updatePlaylist();
removeItem = false;
console.log(event);
console.log(ui);
var originalClass = ui.helper.context.childNodes[0].className;
console.log(originalClass);
var small_clip = originalClass.match(/(\d+)/g)[1];
ui.item.context.children[0].innerHTML = small_clip;
ui.item.context.children[0].classList.add("slot_clip_info");
},
out: function () {
updatePlaylist();
removeItem = true;
},
beforeStop: function(event,ui) {
if (removeItem) {
ui.item.remove();
}
},
stop: function(event,ui) {
console.log("checking placeholder");
var list = $(this);
var count = list.children(':not(.placeholder)').length;
list.children('.placeholder').css("display", count > 0 ? "none" : "block");
savePlaylist();
}
});
```
as soon as i pull and element IN or reorder them, i get the said error.
also, on refresh, the list seems to multiply itself.. but i guess that's another issue...
[Full fiddle (pretty messy, functionality in top dropdown button "PL TOGGLE"](https://jsfiddle.net/PSone/7egjrrnn/)
UPDATE: another thing i noticed: the first drag works without problems, then shows the error on release, subsequent drags will (mostly.. sometimes they do...) not work | 2015/04/04 | [
"https://Stackoverflow.com/questions/29450910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4547337/"
] | you need to make ui a jquery object, and then wrap the first element in another jquery object to do what you want.
so change:
```
ui.children("li")[0].addClass(".slot_clip_info");
```
to
```
$($(ui).children("li")[0]).addClass(".slot_clip_info");
``` |
56,716,855 | I'm trying to convert an integer with value of `1-360` and save it as a char of value `001-360`. Examples `1 = 001`, `43 = 043`, `349 = 349`.
(If there's a better approach than char I'm all ears)
I've looked for different approaches weather using string or char[] but can't seem to get it right.
LOtrackAngle will be an int number 1-360
```
case 'q':
case 'Q':
{
char trackAngleCHR[4];
sprintf(trackAngleCHR, "%d", LOtrackAngle);
ss << " 16"
<< "1" << trackAngleCHR << ""
<< "1"
<< "9";
LOtrackAngle += 1;
if (LOtrackAngle > 360)
{
LOtrackAngle = LOtrackAngle - 360;
}
break;
}
```
Is:
```
LOtrackAngle=248, Output is 16124819.
LOtrackAngle=34, Output is 1613419.
LOtrackAngle=7, Output is 161719.
```
Should be:
```
LOtrackAngle=7, Output is 16100719.
```
I need these to always be 8 characters long. | 2019/06/22 | [
"https://Stackoverflow.com/questions/56716855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1464157/"
] | Since you already use streams, I recommend to use fully C++ solutions:
```
#include <iomanip> //for std::setw
case 'q':
case 'Q':
{
ss << " 16" << "1"
<< std::setw(3) << std::setfill('0') << LOtrackAngle
<< "1" << "9";
LOtrackAngle += 1;
if (LOtrackAngle > 360)
{
LOtrackAngle = LOtrackAngle - 360;
}
break;
}
```
It is not only more concise and easier to read, but also safe against buffer overflow (in case your number won't fit in buffer of length `4` for some reason, you won't get some strange UB) |
67,068,090 | I have a `mediaType` variable, when it change, `currentSelectedMedia` need to be filtered. In this scenario, I get `react-hooks/exhaustive-deps` warning.
```
/**
data example:
currentSelectedMedia = [
{ id: '1', mediaType: '1', name: 'facebook'},
{ id: '2', mediaType: '2', name: 'twitter'}
]
**/
useEffect(() => {
setCurrentSelectedMedia(currentSelectedMedia.filter(item => item.mediaType === mediaType))
}, [mediaType])
```
If I add `currentSelectedMedia` to the dependency array,infinite loop is caused.
the warning is right according to the rule, the reason of infinite loop is also obvious.
But how can I get escape? | 2021/04/13 | [
"https://Stackoverflow.com/questions/67068090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4225768/"
] | You are getting react-hooks/exhaustive-deps warning or infinite loop because your `useEffect` hook gets trigger every time there is a change in `mediaType` state;
And in your `useEffect` method you are setting the value of `mediaType` state;
To solve this problem either you can have two different state or just a normal function which sets the `mediaType` or just create a variable which filters the data when your state gets change.
That depends on how you are setting your mediaType state from other places.
```
const filteredData = currentSelectedMedia.filter(item => item.mediaType === mediaType);
```
Use filteredData to render the data. |
3,038 | Algorithms for edit distance give a measure of the distance between two strings.
Question: which of these measures would be most relevant to detect two different persons names which are actually the same? (different because of a mispelling). The trick is that it should minimize false positives. Example:
Obaama
Obama
=> should probably be merged
Obama
Ibama
=> should not be merged.
This is just an oversimple example. Are their computer scientists out there who worked out this issue in more detail? | 2012/08/12 | [
"https://scicomp.stackexchange.com/questions/3038",
"https://scicomp.stackexchange.com",
"https://scicomp.stackexchange.com/users/1894/"
] | I recommend looking into this,
<http://norvig.com/spell-correct.html>
With the correct training data, you can likely taylor the solution to just formal names. |
22,905,860 | I have a query that contains the `subquery`
```
select doc_id from request
where id in
(select r.root_id from request r, action a where a.request_id = r.id and a.ID
in (1253960076) );
```
I want to output the a.id in the main result set means I want doc\_id as well as a.id in the main result. I am trying to use alias but that is not working. Is there any way we can do this? | 2014/04/07 | [
"https://Stackoverflow.com/questions/22905860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015115/"
] | In your layout file instead of `MapFragment` you need to write `SupportMapFragment` as you have already accessed it using `SupportMapFragment` .So change it as below:
```
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="2dp" />
```
Also initialize your map as below:
```
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
``` |
105,458 | I have a Makehuman export in Blender (2.79) with skin mesh and cloth mesh bound to an armature. I edit the cloth mesh with Sculpt mode just fine. When I try to do the same for the skin, I enter the Sculpt mode successfully and pick tools to sculpt, but no changes are shown on the model and the model is not affected at all. However, when use ctrl + alt + z to see the history, I can see all the sculpting I've done. Why is that?
Update: when I move to Edit mode, I can see all the changes done; I can only see the changes I make in Sculpt mode, after going through edit mode. Otherwise, neither Sculpt mode or Edit mode updates the changes. | 2018/04/01 | [
"https://blender.stackexchange.com/questions/105458",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/54069/"
] | What?
=====
You seem to be editing a shape key (also known by some as a morph target) that has zero weight. You can find shape keys in Properties > Object Data > Shapekeys. A shape key - grossly simplifying - is a snapshot of the arrangement of vertices in a mesh. With shape keys it's possible to interpolate between different states of the mesh.
How to fix?
===========
The active shape key is the one that is being modified by the sculpting, but it may have weight zero and thus not be reflected onto the mesh. To pick which key is being edited, simply select it from the list. While sculpting you may wish to activate the pin icon: it will mute all but the active key. Just remember to deactivate it when you start rigging if you want to avoid surprises.
Why is this a thing?
====================
Deforming a character with bones alone often leads to unsightly wrinkles. To combat this, many character rigs (including those made by Makehuman) are designed with shape keys that make the folding of elbows and knees more natural and that are triggered automatically by bone motion. Another related use is driving creasing in clothing or bulging muscles. Shape keys (here the name morph target is somewhat more fitting) can also be used to drive radical but gradual transformations from one character to another. |
29,897,569 | Is there an equivalent of `update_columns` for `hstore` attributes in rails 4?
My model is:
```
class Image < ActiveRecord::Base
store_accessor :additions, :small, :medium, :big, :image_version
end
```
Assuming I want to update `small`.
I tried:
```
@image = Image.first
@image.update_columns(small: 'my_small_image')
```
But I receive, of course:
```
PG::UndefinedColumn: ERROR: column "small" of relation "contents" does not exist
LINE 1: UPDATE "images" SET "small" = 'my_small_image' WHERE "imag...
^
: UPDATE "images" SET "small" = 'my_small_image' WHERE "images"."id" = 1
```
Is there an easy way to do it?
EDIT: I can't use `update_attributes`, because I need to save **only** the passed arguments.
`update_attributes` calls `save`, and I don't want this, because it saves all other changed attributes, not only the one passed.
Example:
```
@image = Image.first
@image.big = 'fjdiosjfoa'
@image.update_attributes(small: 'my_small_image')
```
Both big and small are saved.
Instead, with `update_columns`, only small get saved. How to do it with an hstore? | 2015/04/27 | [
"https://Stackoverflow.com/questions/29897569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2837813/"
] | Use `update_attributes(small: 'my_small_image')` if you want to save.
Use `assign_attributes(small: 'my_small_image')` if you dont want to save. |
1,519 | Ich habe diesen Satz in einer Kurzgeschichte gelesen:
>
> Er ist todunglücklich!
>
>
>
Was bedeutet es genau?
* Ist er so unglücklich, dass er tot gewesen sollen?
* Ist er so unglücklich, dass es für ihn besser wäre, tot zu sein?
* Er ist unglücklich, da seine Tochter tot ist?
* Er ist traurig, dass seine Tochter tot ist?
* Er war unglücklich sein ganzes Leben lang?
usw. | 2011/06/21 | [
"https://german.stackexchange.com/questions/1519",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/109/"
] | Es ist nur eine Vermutung von mir, aber ich denke, dass *todunglücklich* als [Elativ](http://de.wikipedia.org/wiki/Elativ) zu verstehen ist. Es handelt sich also um eine extreme Steigerung zum normalen *unglücklich*. Als Bedeutung könnte *todunglücklich* folgendermaßen interpretiert werden:
>
> Er war so unglücklich, dass das Wort *unglücklich* nicht ausreichte, seinen Zustand zu beschreiben.
>
>
>
Vergleiche auch *reich* -> *steinreich* = extrem reich |
554,495 | Two baskets containing $n\_1$, respectively $n\_2$ balls, of which $k\_1 \lt n\_1$ , respectively $k\_2 \lt n\_2$ are white. From the first basket a ball is extracted and is put in the other basket, from which there are extracted three balls consecutively(returned). Calculate the probabilities of obtaining $k\in\{ 0,1,2,3,4\}$ white balls.
I can't get my head around this one. Thanks! | 2013/11/06 | [
"https://math.stackexchange.com/questions/554495",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/105621/"
] | This is an effort to get this question off from [the unanswered queue](http://meta.math.stackexchange.com/questions/4437/could-chatrooms-serve-as-noticeboards/9868#9868).
I would like to share my two cents: asking a seemingly homework-like question with the name of Professor Monk, the book written by whom I had learned a lot from, I would say this looks very inappropriate.
Anyway I just would like extend Felix Marin's incomplete answer to a full one. There is one most important feature of Euler-Lagrange equation he forgot to mention.
Another relevant question I remembered answering not very long time ago:
[Euler-Lagrange equations of the Lagrangian related to Maxwell's equations](https://math.stackexchange.com/questions/278356/euler-lagrange-equations-of-the-lagrangian-related-to-maxwells-equations/470771)
---
>
> Find the equation of motion of the charged particle from the Lagrangian.
>
>
>
The equation of motion obtained from the Lagrangian basically is the Euler-Lagrange equation:
$\newcommand{\b}{\mathbf}$
$$
\frac{\partial L}{\partial {\mathbf r}} - \frac{\mathrm d }{\mathrm dt}\left( \frac{\partial L}{\partial {\mathbf r'}}\right) =0, \tag{1}
$$
whereas the $\dfrac{\mathrm d }{\mathrm dt}$ represents taking the **total derivative** (time derivative, plus the convective derivative w.r.t. the spacial variable, or so to speak). Yet prime only stand for the time derivative usually.
Plugging $L$ into (1) we have: (the usual postulate is that $\mathbf v$ is not explicitly a function of $\mathbf r$)
$$
\frac{\partial L}{\partial {\mathbf r}} = \nabla \left( \frac{q}{c} \b{v}\cdot \b{A} - q\phi\right)
\\
= q\left(\frac{1}{c} \nabla(\b{v}\cdot \b{A}) - \nabla \phi \right)
\\
= q\left(\frac{1}{c} \b{v}\times( \nabla\times\b{A}) + \frac{1}{c} (\b{v}\cdot \nabla) \b{A} - \nabla \phi \right).
$$
And
$$
\frac{\partial L}{\partial {\mathbf r'}} = \frac{\partial L}{\partial {\mathbf v}}
= m\b{v} + \frac{q}{c}\b{A}.
$$
Now taking the total derivative:
$$
\frac{\mathrm d }{\mathrm dt}\left( \frac{\partial L}{\partial {\mathbf r'}}\right) =
\frac{\partial }{\partial t}\left( \frac{\partial L}{\partial {\mathbf r'}}\right)
+ \left(\frac{\mathrm d \b{r} }{\mathrm dt}\cdot\nabla\right)\left( \frac{\partial L}{\partial {\mathbf r'}}\right).
$$
Notice the total derivative of $\b{r} = (x(t),y(t),z(t))$ is $\b{r}'$, hence:
$$
\frac{\mathrm d }{\mathrm dt}\left( \frac{\partial L}{\partial {\mathbf r'}}\right) = \frac{\partial }{\partial t}\left(m\b{v} + \frac{q}{c}\b{A}\right)
+(\b{v}\cdot \nabla ) \left(m\b{v} + \frac{q}{c}\b{A}\right)
\\
= m\frac{\partial^2 \b{r}}{\partial t^2}
+ \frac{q}{c}\frac{\partial \b{A}}{\partial t}
+ \frac{q}{c}(\b{v}\cdot \nabla )\b{A},
$$
where we used that the convective derivative of $\b{v} = \b{v}(t)$ is zero.
Now put everything back to (1), we have:
$$
m\frac{\partial^2 \b{r}}{\partial t^2} =
- \frac{q}{c}\frac{\partial \b{A}}{\partial t}
+\frac{q}{c} \b{v}\times( \nabla\times\b{A} )- q\nabla \phi. \tag{2}
$$
Equation (2) is basically the motion equation of the Lagrangian.
---
>
> Express the force acting on the particle in terms of electric and magnetic fields only (i.e. the equation of motion should have the form of the Newton's second law and contain fields $\mathbf{E}$ and $\mathbf{B}$ but not the 'potentials' $\mathbf{A}$ and $\phi$).
>
>
>
If the potentials are replaced using the $\b{E}$ and $\b{B}$ respectively, (2) will become:
$$
m\frac{\partial^2 \b{r}}{\partial t^2} = q(\b{E} + \b{v}\times \b{B}). \tag{3}
$$
This is nothing but the famous [Lorentz force formula](http://en.wikipedia.org/wiki/Lorentz_force), a.k.a. the Newton Second Law for a particle moving through an electromagnetic field. |
267,263 | In my custom modules I am creating a custom content type. I also need to apply a twig template for this custom content type, but I can't seem to get it to actually apply.
in myModule.module file I have:
```
function myModule_theme($existing, $type, $theme, $path) {
return [
'faculty_bio_node' => [
'variables' => [],
]
];
}
```
and I have a custom twig template named : faculty\_bio-node.html.twig
The content types machine name is faculty\_bio | 2018/08/09 | [
"https://drupal.stackexchange.com/questions/267263",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/50167/"
] | If you want to load the template from the module folder you are in the right hook, but you need to use the correct base hook. This means you have to start the template name with the base hook and a double underscore `node__` and declare the base hook in theme\_hook(), see [Store template in module](https://drupal.stackexchange.com/questions/194498/store-template-in-module).
hook\_theme():
```
function myModule_theme($existing, $type, $theme, $path) {
return [
'node__faculty_bio' => [
'base hook' => 'node',
]
];
}
```
The Twig template path and name would then be `mymodule/templates/node--faculty-bio.html.twig`. |
330,496 | Consider a cylindrical mass in empty space oriented along the x1 direction. In general relativity, do the space-time dimensions (x1, x2, x3, x4) curve about the mass in a completely symmetrical manner? | 2017/05/02 | [
"https://physics.stackexchange.com/questions/330496",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/154517/"
] | [![enter image description here](https://i.stack.imgur.com/8p3eF.png)](https://i.stack.imgur.com/8p3eF.png)
M2, is the paper and M1 is the coin. We are exerting a rightward force $F$ on the paper. It's obvious that the paper moves because of the force we are exerting on it, and it's acceleration is decreased by the friction force between the coin and the paper.(The paper is going rightwards, but the coin is exerting a friction force to the paper, leftwards). Based on Newton's third, because the coin is exerting a force on the paper leftwards, the paper is exerting a rightward force on the coin too. That's the reason the coin will stick to the paper when you're pulling the paper slowly. But the question is what happens when we increase this force. Firstly, the static friction force can not exceed a certain value. Which means if $F$ gets too high, the friction force can not keep up with $F$ and at some point the acceleration of the paper becomes more than the coin. So the coin can not keep up with the paper. So after a while, the coin just slips and falls into the glass.
---
I want to calculate the minimum force $F$ so that it causes the coin to slip. Imagine the maximum static friction force between the paper and the coin is $f\_{k.max}$. So the maximum force that can be exerted on the coin is $f\_{k.max}$. Which means the maximum acceleration of the coin is:
$a = F/M1 = \dfrac{f\_{k.max}}{M1}$
So if you want to make the coin slip on the paper, you have to make the system move with an acceleration more that $a$. Which means:
$F > a \* (M1 + M2) => F > \dfrac{(M1 + M2)f\_{k.max}}{M1}$
If the force is below this value, then the coin doesn't slip, because the force exerted on it is not above $f\_{k.max}$ but if the force exceeds this value, then $M1$ can not keep up with M2.
Think of the coin and the paper, as a whole system, only when the acceleration exceeds some value, the system breaks.
---
Forces on the paper:
$\sum{F\_{paper}} = F - f\_{k} = M\_2 \* a$
Forces on the coin:
$\sum{F\_{coin}} = f\_{k} = M\_1 \* a$
And we know that:
$f\_k \leq f\_{k.max} => M\_1 \* a \leq f\_{k.max} => a \leq \dfrac{f\_{k.max}}{M\_1}$
$=> M\_2 \* a + f\_{k} = F, => F \leq M\_2 \* \dfrac{f\_{k.max}}{M\_1} + f\_{k.max} => F\leq \dfrac{(M\_1 + M\_2)f\_{k.max}}{M\_1} $ |
54,809,578 | I am currently trying to accept a `POST` request to a .NET Core Web API endpoint that accepts the following model:
```
public class OrderPost
{
[Required]
public string DeliveryStreet { get; set; }
public string DeliveryBuilding { get; set; }
[Required]
public string DeliveryCity { get; set; }
[Required]
public string DeliveryProvince { get; set; }
[Required]
public string DeliveryPostalCode { get; set; }
[Required]
public string CardName { get; set; }
[Required]
public string CardNumber { get; set; }
[Required]
public string CardExpiry { get; set; }
[Required]
public long CardCvv { get; set; }
[Required]
public List<OrderItem> OrderItems { get; set; }
}
public class OrderItem
{
public long Id { get; set; }
public string Category { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Uri ImageUrl { get; set; }
public long Price { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public long Quantity { get; set; }
}
```
When I remove the `List<OrderItem>` and post the data without the List the call works perfectly. As soon as I add the list back and try and `POST` the data I get a `400 Bad Request` error. I have a feeling I am just missing some attribute or something on the List. The JSON I am posting is valid, I double checked that. Any ideas of what could be causing this?
Here is the JSON I am POST'ing:
```
{
"deliveryStreet": "Test street",
"deliveryBuilding": "",
"deliveryCity": "TEst",
"deliveryProvince": "TEst",
"deliveryPostalCode": "0852",
"cardName": "Jane Jones",
"cardNumber": "4711 1000 0000 0000",
"cardExpiry": "05 / 20",
"cardCvv": "123",
"orderItems": [{
"id": 1,
"category": null,
"name": "Test",
"description": "Test test test",
"imageUrl": "http://google.com/",
"price": 625,
"createdAt": "2019-02-21T13:25:56.709192",
"updatedAt": "2019-02-21T13:25:56.709192",
"quantity": 5
}]
}
```
Here is the Endpoint that I am trying to `POST` to:
```
[HttpPost]
public IActionResult Post([FromBody]OrderPost data)
{
//Get the credit card type off of the number
var type = StringUtilities.GetCardTypeFromNumber(data.CardNumber);
//Check if valid type was found
if (type == "UNKNOWN")
return BadRequest("Unknown credit card type");
float total = 0;
.................
}
``` | 2019/02/21 | [
"https://Stackoverflow.com/questions/54809578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8125309/"
] | You could try the DISTINCT clause, so your query looks like this:
```
SELECT DISTINCT
rate,
status,
ride_id,
trip_number,
mta_id,
service_date,
service_start,
driver_id,
cab_number,
trip_total_amount
FROM cte0 c
WHERE NOT EXISTS (
SELECT 1 FROM cte0 ci
WHERE c.ride_id = ci.ride_id
AND status = 'Approved'
GROUP BY ride_id
HAVING SUM(trip_total_amount) = 0::money
);
``` |
362,013 | ```
$ ls
abcmkde
ghemkde
vdecdde
```
For example I only want to list out file name with only 4 and 5th character with only one iteration of single match (`mk` and `cd` in the example above).
There is a bunch of files with different names and different fourth and fifth character. | 2017/04/28 | [
"https://unix.stackexchange.com/questions/362013",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/229128/"
] | Since [you really don't want to parse `ls`](http://unix.stackexchange.com/questions/128985/why-not-parse-ls), this should do the trick:
```
find . -type f -maxdepth 1 -exec basename "{}" \; | cut -d'-' -f1 | sort -u
``` |
6,999,547 | I have a project using cucumber outside of rails. How can I load the gems with the versions specified in my gemfile? | 2011/08/09 | [
"https://Stackoverflow.com/questions/6999547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884507/"
] | Digging through [the Bundler website](http://bundler.io/):
1. Create `Gemfile` (run `bundle init` to create skeleton `Gemfile`)
2. `bundle install`
3. In your app:
```
# Only needed for ruby 1.8.x
require 'rubygems'
# The part that activates bundler in your app
require 'bundler/setup'
# require your gems as usual
require 'some_gem'
# ...or require all the gems in one statement
Bundler.require
```
### Could be worth checking out:
[Bundler.io - Using Bundler in Your Appplication](http://bundler.io/v1.12/guides/using_bundler_in_application.html)
[Bundler.io - Bundler.setup and Bundler.require](http://bundler.io/v1.12/bundler_setup.html)
[Are bundle exec and require 'bundler/setup' equivalent?](https://stackoverflow.com/questions/11117112/are-bundle-exec-and-require-bundler-setup-equivalent) |
57,198,191 | I have implemented a method `getUsers()`, which basically construct a `List<ShoppingCart>`, then create a `List<User>`:
```
public List<User> getUsers() {
// construct a liste of List<ShoppingCart>
....
// update
...
}
```
The construction of `List<ShoppingCart>` contains a lot of logic, so I decided to move those code out and create a private method:
```
public List<User> getUsers() {
// construct a liste of List<ShoppingCart>
List<ShoppingCart> shoppingList = getShoppingList();
// update
...
}
private List<ShoppingCart> getShoppingList() {
...
}
```
Now I need to unit test `getUsers()`. But I realized that I have difficulty to get the `List<ShoppingCart>` because it's a private method.
And I don't want to make `getShoppingList()` public because I don't need it anywhere else.
I think there is a design problem in my code, what is the best way to unit test these kinds of methods containing returned value of private methods ?
Thanks.
**UPDATE**
No it's not the same question as [Java test class with many private methods](https://stackoverflow.com/questions/27969920/java-test-class-with-many-private-methods), my question is not if it's necessary to test private method, but what should be a better design | 2019/07/25 | [
"https://Stackoverflow.com/questions/57198191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5035236/"
] | I think good option is separate logic for user and shopping cards. If You agree with me, You can move shopping cards logic to different class, and then You can mock this logic on Your test and then write test for `getUsers()` like this:
```
public class UserTest {
@Mock
private ShoppingCard shoppingCard;
private User sut = new User();
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldReturnUsersEmptyListWhenCardsEmpty(){
//given
when(shoppingCard.getShoppingCards()).thenReturn(Collections.emptyList());
//when
final List<User> result = sut.getUsers();
//then
assertEquals(0, result.size());
}
}
``` |
196,230 | Earth's density is about 5.51 g/cm^3 and it's the highest density in the Solar System of a terrestrial planet. I understand that planet density is partially determined by various factors, including its composition and gravity. I want to play with densities, like increasing a planet's density by as much as x2 Earth density and the like, but I am not sure if this is reasonable. I looked at some exoplanet information, but densities were not readily available. Is is somewhat normal for terrestrial, Earth-like planets to have densities 7-11 g/cm^3, or is that not very prevalent in the physics of the real world? | 2021/02/17 | [
"https://worldbuilding.stackexchange.com/questions/196230",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/82646/"
] | If you look at my answer to the question: *[Mars sized planet with 83% Earth gravity?](http://ttps://worldbuilding.stackexchange.com/questions/195880/mars-sized-planet-with-83-earth-gravity/195885#195885)* you will see I discuss this and the evolution of my thinking.
In our solar system Earth has the highest density of all the planets, at 5.514 t/m$^\sf3$, then Mercury (5.427 t/m$^\sf3$), followed by Venus (5.243 t/m$^\sf3$).
Earth and Venus are what I call conventional terrestrial planets: they formed from the accretion of solar disc dust. It is speculated that Earth collided with Theia which resulted in Earth what it is today and the Moon, but both Earth and Theia were both formed from solar disc dust and the Earth has differentiated geological structure: large core, thick mantel and a thin crust.
[Mercury](https://en.wikipedia.org/wiki/Mercury_(planet)) has a large density for such a small planet, which is very unusual.
>
> The most widely accepted theory is that Mercury originally had a metal–silicate ratio similar to common chondrite meteorites, thought to be typical of the Solar System's rocky matter, and a mass approximately 2.25 times its current mass. Early in the Solar System's history, Mercury may have been struck by a planetesimal of approximately 1/6 that mass and several thousand kilometers across. The impact would have stripped away much of the original crust and mantle, leaving the core behind as a relatively major component. A similar process, known as the giant impact hypothesis, has been proposed to explain the formation of the Moon.
>
>
>
So Mercury is the remnant core of what was once a larger planet.
In answering the question I provided a link to, I answered it over a number of days and I researched the exoplanet [K2-38b](https://en.wikipedia.org/wiki/K2-38b). It is 1.55 times the size of the Earth, but it's mass is 7.3 times that of Earth, resulting in an average density of 11.0 t/m$^\sf3$. This is is one of the highest densities for any planet yet discovered.
Like Mercury, it is speculated that K2-38b is the remnant compressed core of a large planet that was stripped of its outer layers by a collision or some form of celestial bombardment.
This leads to your question "what are reasonable density for terrestrial planets?"
If your are considering planets that have not been stripped of their outer layers then densities similar to Earth's, about 5.5 t/m$^\sf3$ are reasonable.
If your are considering planets that have been stripped of their outer layers then anything up to 20 t/m$^\sf3$, would appear reasonable, given that K2-38b was initially thought to have had a density of 17.5 t/m$^\sf3$.
If you are considering planets that would be habitable, that gets trickier. Life requires certain metals to exist, such as iron, copper and zinc. The planet must contain such metals in an easily obtainable form on the surface of the planet - they can't be locked away in the core or the mantel. Though heavily metals locked away in the core are required for gravity.
The mass of a planet will be determined by the amount of material it contains. Generally, the more it contains heavy metals the more mass it will have.
Average planet density, gravity and escape velocity are dictated by the mass of the planet and its radius. You can't just consider density, you have to consider it along with planet size, mass, gravity and escape velocity.
For a planet to be habitable, as with temperature, atmospheric composition and pressure, there will be a Goldilocks zone for gravity as well and this will be linked to planet density. |
28,461,340 | I'm currently building an AngularJS application with a PHP backend. The routing is done using Slim PHP and I've found an AngularJs module to do token-based authentication. In the module example for the backend they use Laravel and a client called GuzzleHttp\Client(). Now, I'm not sure what GuzzleHttp do that Slim PHP don't (if any) but I'm trying to follow along their example but I don't want to install 2 frameworks that could essentially do the same thing.
So I have my routing done so that when a request is made to the backend (auth/google) it'll do this:
```
public function google()
{
$app = \Slim\Slim::getInstance();
$request = $app->request()->getBody();
$body = json_decode($request);
$accessTokenUrl = 'https://accounts.google.com/o/oauth2/token';
$peopleApiUrl = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect';
$params = array(
'code' => $body->code,
'client_id' => $body->clientId,
'redirect_uri' => $body->redirectUri,
'grant_type' => 'authorization_code',
'client_secret' => GOOGLE_SECRET
);
$client = new GuzzleHttp\Client();
// Step 1. Exchange authorization code for access token.
$accessTokenResponse = $client->post($accessTokenUrl, ['body' => $params]);
$accessToken = $accessTokenResponse->json()['access_token'];
$headers = array('Authorization' => 'Bearer ' . $accessToken);
// Step 2. Retrieve profile information about the current user.
$profileResponse = $client->get($peopleApiUrl, ['headers' => $headers]);
$profile = $profileResponse->json();
// Step 3a. If user is already signed in then link accounts.
if (Request::header('Authorization'))
{
$user = User::where('google', '=', $profile['sub']);
if ($user->first())
{
return Response::json(array('message' => 'There is already a Google account that belongs to you'), 409);
}
$token = explode(' ', Request::header('Authorization'))[1];
$payloadObject = JWT::decode($token, Config::get('secrets.TOKEN_SECRET'));
$payload = json_decode(json_encode($payloadObject), true);
$user = User::find($payload['sub']);
$user->google = $profile['sub'];
$user->displayName = $user->displayName || $profile['name'];
$user->save();
return Response::json(array('token' => $this->createToken($user)));
}
// Step 3b. Create a new user account or return an existing one.
else
{
$user = User::where('google', '=', $profile['sub']);
if ($user->first())
{
return Response::json(array('token' => $this->createToken($user->first())));
}
$user = new User;
$user->google = $profile['sub'];
$user->displayName = $profile['name'];
$user->save();
return Response::json(array('token' => $this->createToken($user)));
}
}
```
Now this won't work because I don't have GuzzleHttp installed but my question is: **can I do this in Slim PHP or do I need GuzzleHttp to complement it?** | 2015/02/11 | [
"https://Stackoverflow.com/questions/28461340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Guzzle is a code based HTTP client package/framework which also contains DOM crawling functionality not a micro-framework, thus it is not analogous to Slim.
From their Readme:
>
> **Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.**
>
>
>
Slim does not provide this functionality directly because it doesnt fall under what Slim is meant to do which is transform HTTP requests into HTTP responses (and the core things that need to happen in between).
Since your example is in Guzzle and it implements what you are trying to do i would probably use Guzzle. However, you could do the same types of thing (ie. interact with an external web service) using `cURL`, `ext/http`, or another HTTP client package. There are several. |
2,222 | Will the Monero command line daemon/wallet programs still be available after the release of the official GUI?
Will Monerod will be blended in similarly to how bitcoin core node/wallet is? | 2016/10/12 | [
"https://monero.stackexchange.com/questions/2222",
"https://monero.stackexchange.com",
"https://monero.stackexchange.com/users/201/"
] | >
> Will command line still be available after the release of the official GUI?
>
>
>
Yes, it will. As far as I know, there will be support for both in the future. Thus, you will have `monero-wallet-cli`, which is the command line wallet, and `monero-wallet-gui`, which will be the GUI wallet.
>
> Will Monerod will be blended in similarly of what bitcoin core node/wallet is?
>
>
>
In the future, yes, see the feature request opened [here](https://github.com/monero-project/monero-core/issues/39). For now, however, `monero-wallet-gui` will be a separate binary that has to run alongside `monerod`. However, the GUI has a progress bar that shows the syncing status of `monerod`. Thus, new users would only have to open `monerod` and let it sync. They can monitor the progress in `monero-wallet-gui`.
Note that `monero-wallet-gui` might not be the official naming, but I used it in this answer for convenience. |
68,618,351 | My Database table is as shown below. I need to get latest mark of each student. Latest entry is the row with maximum `udate` and maximum `oder`. (The `oder` will be incremented by one on each entry with same date)
[![enter image description here](https://i.stack.imgur.com/VpqjH.png)](https://i.stack.imgur.com/VpqjH.png)
In my example, I have two students `Mujeeb, Zakariya` and two subjects `ENGLISH, MATHS`. I need to get latest mark of each student for each subject. My expectd result is as follows
[![enter image description here](https://i.stack.imgur.com/wXSDS.png)](https://i.stack.imgur.com/wXSDS.png)
My sample data is
```
DROP TABLE IF EXISTS `students`;
CREATE TABLE IF NOT EXISTS `students` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`udate` date NOT NULL,
`oder` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`Subject` varchar(20) NOT NULL,
`mark` int(11) NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
INSERT INTO `students` (`uid`, `udate`, `oder`, `name`, `Subject`, `mark`) VALUES
(1, '2021-08-01', 1, 'Mujeeb', 'ENGLISH', 10),
(2, '2021-08-01', 1, 'Zakariya', 'ENGLISH', 20),
(3, '2021-08-10', 2, 'Mujeeb', 'ENGLISH', 50),
(4, '2021-08-11', 2, 'Zakariya', 'ENGLISH', 60),
(5, '2021-08-02', 1, 'Mujeeb', 'ENGLISH', 100),
(6, '2021-08-03', 1, 'Zakariya', 'ENGLISH', 110),
(7, '2021-08-10', 1, 'Mujeeb', 'ENGLISH', 500),
(8, '2021-08-11', 1, 'Zakariya', 'ENGLISH', 600),
(9, '2021-08-01', 2, 'Mujeeb', 'MATHS', 100),
(10, '2021-08-01', 2, 'Zakariya', 'MATHS', 75),
(11, '2021-08-10', 3, 'Mujeeb', 'MATHS', 50),
(12, '2021-08-11', 3, 'Zakariya', 'MATHS', 60);
``` | 2021/08/02 | [
"https://Stackoverflow.com/questions/68618351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6491982/"
] | Depending on how exactly namespaces are organized in your XML code below may be simplified a bit, but it should work as is just as well:
```
<set-variable name="test" value="@(
context.Request.Body.As<XElement>()
.Descendants()
.FirstOrDefault(x => x.Name.LocalName == "B" && x.Attributes().FirstOrDefault(a => a.Name.LocalName == "n")?.Value == "3")?
.Attributes()
.FirstOrDefault(a => a.Name.LocalName == "v")?
.Value
)" />
``` |
118,877 | Essentially, I have a virus which temporarily turns people into psychopaths. This virus is being used by my antagonists to collapse a city.
I will be using a lysogenic virus which is triggered by some form of EM waves. It will limit the production of the hormone oxytocin, which is the main chemical regarding our morality ([link to research](https://spectrum.ieee.org/podcast/geek-life/profiles/can-one-chemical-be-the-basis-of-all-morality)).
**Transmission:**
The first infected person will be infected in a lab by a tiny dart (similar to a tranquiliser dart in terms of mechanics) which contains the virus. This person will then be released into the public. The virus can spread as per normal i.e. coughing, bloodstream, saliva etc. (not airborne but waterborne). However, once a certain radio wave is emitted from my antagonists' HQ, the darts will become 'live' and will emit the EM waves required to trigger the virus. Once this happens, the people with darts will turn into psychopaths, but so will any infected people around them (as long as they're within a short distance). Once these people have turned evil, they will be armed with darts (from the antagonists) and will attempt to infect any healthy people (as they're psychopaths so they'll want the city to collapse as well). However, once my antagonists' turn off their signal, the darts will stop emitting their waves and the infected will go back to normal (i.e. stop being psychopaths).
**Would this work?**
(If you need any clarifications, feel free to ask in the comments) | 2018/07/22 | [
"https://worldbuilding.stackexchange.com/questions/118877",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/46250/"
] | It sounds like you have a dangerously wrong idea of what psychopathy is...
A psychopath is not some crazy killing machine whose only goal is complete chaos. It's a person whose empathy and remorse is impaired in a way that makes them often egoistical, cold blooded and manipulative, but not destructive per se.
The [Wikipedia article](https://en.wikipedia.org/wiki/Psychopathy#Signs_and_symptoms) about psychopathy states in the section "Violence":
>
> Studies have suggested a strong correlation between psychopathy scores and violence, and the PCL-R emphasizes features that are somewhat predictive of violent behavior. Researchers, however, have noted that **psychopathy is dissociable from and not synonymous with violence.**
>
>
> It has been suggested that psychopathy is associated with "instrumental", also known as predatory, proactive, or "cold blooded" aggression, a form of aggression characterized by reduced emotion and **conducted with a goal differing from** but facilitated by **the commission of harm.**
>
>
>
Why would an egoist who manipulates people to get their way actively use dart guns to spread some diseas he doesn't know about?
If you want infected people to actively infect more people, you should find other means. The 2007 anime "Appleseed Ex Machina" had a similar plot, in which a company spread new mobile devices (that looked like bluetooth headsets and were worn in one ear) among people, then activated their trigger signal. The devices would somehow connect to the wearers nervous system and make them force anyone around them to also wear such a device.
There are also some examples of parasites influencing their hosts behavior. See [this video for examples](https://www.youtube.com/watch?v=bfKrF2J9fBU), but **be warned of gross content**!
The parasites seem to manipulate base instincts of their hosts, like snails seeking out sunlight or infected crickets diving right into water. Your virus could make humans more social, thus infecting their family and friends. |
3,769,990 | Enumeration interface has method hashMoreElements is used with refrence variable (Enumv), how can they be used
since they are not implemented ?
I meant it is an interface method so how can it be called - Enumv.hasMoreElements() it does not have a implementation .
```
Vector v = new Vector();
//v contains list of elements - Suppose
Enumeration Enumv = v.elements();
while(Enumv.hasMoreElements()) {
System.out.println(Enumv.nextElement());
}
```
How is this possible? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3769990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454853/"
] | For your code,
```
Enumeration Enumv = v.elements();
```
This is what `Vector` is returning to you.
```
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return (E)elementData[count++];
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
```
As you can see, Vector returns an implemented `Enumeration` class (which annonymous to the developer).
>
> **so how can it be called - Enumv.hasMoreElements() it does not
> have a implementation .**
>
>
>
It is implemented (as shown above). |
29,145,778 | How to search for version no python:
```
Build Host : iox-lux-013
Version : 3.2.8.08I sample
```
I tried:
```
import re
p=re.compile("Version.*: (.*?) ")
list=p.findall(s)
for i in list:
print i
```
works good
but not for:
```
Version : 3.2.8.08I
```
doesnt work :/ | 2015/03/19 | [
"https://Stackoverflow.com/questions/29145778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4689908/"
] | Use `\S+` to match one or more non-space characters.
```
p = re.compile(r"Version\s*:\s*(\d+(?:\.\d+)*[A-Z]\b)")
```
`\s*` matches zero or more spaces , so you don't need to use `.*` before `:`
**Example:**
```
>>> s = '''Build Host : iox-lux-013
Version : 3.2.8.08I sample
Version : 3.2.8.08I'''
re.findall(r"Version\s*:\s*(\d+(?:\.\d+)*[A-Z]\b)", s)
['3.2.8.08I', '3.2.8.08I']
``` |