问:
Implementation of a chat service using Restlet api
First off I'm not too familiar with restlets , just starting out. I wanted to implement a broadcast chatroom where a client sending a message would have the message broadcast to all other clients.  </p>

```<code>   My attempt was to use a resource on the server side where the client would send the message(as a String) using POST. The other clients would constantly have to poll this resource to receive the message. I know this method must be horribly ineffective.

   I was wondering if there was a better method where a change on the server side(in this case the sending of the string message) would result in the server alerting the clients of this update.
</code>```

答:
Some things will come in version 2.1 with the new nio connector. Within web page, you might consider using technologies like Comet or HTML5 web sockets.

See the specification page from the developer wiki of Restlet: http://wiki.restlet.org/developers/172-restlet/g3/354-restlet.html

Thierry

ContentLicense: CC BY-SA 2.5

Body:
First off I'm not too familiar with restlets , just starting out. I wanted to implement a broadcast chatroom where a client sending a message would have the message broadcast to all other clients.

   My attempt was to use a resource on the server side where the client would send the message(as a String) using POST. The other clients would constantly have to poll this resource to receive the message. I know this method must be horribly ineffective.

   I was wondering if there was a better method where a change on the server side(in this case the sending of the string message) would result in the server alerting the clients of this update.


来源: stackexchange

问:
Password field not taking keys using Selenium through Python
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

```<code><div>
    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    <a id="btnSmallForgotPassword" class="smallForgotPassword visible-sm-block" href="javascript:__doPostBack('btnSmallForgotPassword','')">forgot password</a>
</div>
</code>```

```<code>WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")
</code>```

I am getting no error message but it is not sending keys for password

答:
To send character sequence to the USER ID and PASSWORD field you need to to induce WebDriverWait for the element to be clickable and you can use the following Locator Strategy:

Code Block:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input#txtUser"))).send_keys("abhishek_gupta")
driver.find_element_by_css_selector("input#txtPassword").send_keys("abhishek_gupta")
</code>```

Browser Snapshot:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    forgot password

WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")

I am getting no error message but it is not sending keys for password

Body:
To send character sequence to the USER ID and PASSWORD field you need to to induce WebDriverWait for the element to be clickable and you can use the following Locator Strategy:

Code Block:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input#txtUser"))).send_keys("abhishek_gupta")
driver.find_element_by_css_selector("input#txtPassword").send_keys("abhishek_gupta")

Browser Snapshot:


问:
TYPO3: CKEditor removes some html tags (e.g. strong, h4)
When I add html content to CKEditor (source-code mode) and then save the html content, some tags are removed - for example  or
.

I am using the default YAML Konfiguration and add my own one:

```<code># EXT:my_ext/Configuration/RTE/Default.yaml
imports:
  # Import default RTE config (for example)
  - { resource: "EXT:rte_ckeditor/Configuration/RTE/Processing.yaml" }
  - { resource: "EXT:rte_ckeditor/Configuration/RTE/Editor/Base.yaml" }
  - { resource: "EXT:rte_ckeditor/Configuration/RTE/Full.yaml" }
  # Import the image plugin configuration
  - { resource: "EXT:rte_ckeditor_image/Configuration/RTE/Plugin.yaml" }

editor:
  config:
    # RTE default config removes image plugin - restore it:
    removePlugins: null
    removeButtons:
      - Anchor
    extraAllowedContent: 'a[onclick]'
    toolbarGroups:
      - { name: basicstyles, groups: [ basicstyles, align, cleanup ] }
      - { name: styles }
    stylesSet:
      - { name: "Rote Schrift", element: "span", attributes: { class: "highlighted red"} }
      - { name: "Button", element: "a", attributes: { class: "btn"} }
      - { name: "Checkliste", element: "ul", attributes: { class: "check-list"} }
    toolbarGroups:
      - { name: links, groups: ['MenuLink', 'Unlink', 'Anchor'] }
  externalPlugins:
      typo3image: { allowedExtensions: "jpg,jpeg,png,gif,svg" }
      typo3link: { resource: "EXT:rte_ckeditor/Resources/Public/JavaScript/Plugins/typo3link.js", route: "rteckeditor_wizard_browse_links" }

processing:
  HTMLparser_db:
    denyTags: null
</code>```

Furthermore I have the following TS page config (not sure if this is used by TYPO3 - it's a setup of the old RTE editor):

```<code>RTE.default.enableWordClean.HTMLparser {
    allowTags = a,b,blockquote,br,div,em,h2,h3,h4,h5,h6,hr,i,img,li,ol,p,span,strike,strong, ...
</code>```

答:
I finally found the solution, by comparing my Custom.yaml with typo3\sysext\rte_ckeditor\Configuration\RTE\Full.yaml

To allow more tags I had to add the new tags in the following sections of my Yaml file:

```<code>editor:
  config:
    allowTags:
      - link
      - strong
      - h4

processing:
  allowTags:
    - link
    - strong
    - h4
</code>```

Body:
When I add html content to CKEditor (source-code mode) and then save the html content, some tags are removed - for example  or
.

I am using the default YAML Konfiguration and add my own one:

# EXT:my_ext/Configuration/RTE/Default.yaml
imports:
  # Import default RTE config (for example)
  - { resource: "EXT:rte_ckeditor/Configuration/RTE/Processing.yaml" }
  - { resource: "EXT:rte_ckeditor/Configuration/RTE/Editor/Base.yaml" }
  - { resource: "EXT:rte_ckeditor/Configuration/RTE/Full.yaml" }
  # Import the image plugin configuration
  - { resource: "EXT:rte_ckeditor_image/Configuration/RTE/Plugin.yaml" }

editor:
  config:
    # RTE default config removes image plugin - restore it:
    removePlugins: null
    removeButtons:
      - Anchor
    extraAllowedContent: 'a[onclick]'
    toolbarGroups:
      - { name: basicstyles, groups: [ basicstyles, align, cleanup ] }
      - { name: styles }
    stylesSet:
      - { name: "Rote Schrift", element: "span", attributes: { class: "highlighted red"} }
      - { name: "Button", element: "a", attributes: { class: "btn"} }
      - { name: "Checkliste", element: "ul", attributes: { class: "check-list"} }
    toolbarGroups:
      - { name: links, groups: ['MenuLink', 'Unlink', 'Anchor'] }
  externalPlugins:
      typo3image: { allowedExtensions: "jpg,jpeg,png,gif,svg" }
      typo3link: { resource: "EXT:rte_ckeditor/Resources/Public/JavaScript/Plugins/typo3link.js", route: "rteckeditor_wizard_browse_links" }

processing:
  HTMLparser_db:
    denyTags: null

Furthermore I have the following TS page config (not sure if this is used by TYPO3 - it's a setup of the old RTE editor):

RTE.default.enableWordClean.HTMLparser {
    allowTags = a,b,blockquote,br,div,em,h2,h3,h4,h5,h6,hr,i,img,li,ol,p,span,strike,strong, ...

Body:
I finally found the solution, by comparing my Custom.yaml with typo3\sysext\rte_ckeditor\Configuration\RTE\Full.yaml

To allow more tags I had to add the new tags in the following sections of my Yaml file:

editor:
  config:
    allowTags:
      - link
      - strong
      - h4

processing:
  allowTags:
    - link
    - strong
    - h4


问:
How to iterate over a map to get all the values for 2 keys
I have read csv and stored the values in map (key-value format)
I need to fetch all values for 2 particular key into an array list to comapre it with database values columns

ArrayList ftlVal = new ArrayList<>();

```<code>                for (Map<String, String> map : finResult) {
                      Object[] key = {"Column2", "Column6"};
                      for (int i = 0; i < key.length; i++) {
                             do {
                                   //for (int j = 0; j <key.length; j++) {
                                          //while (map.get(key[j]) != null) {
                                                Object value = map.get(key[i]);
                                                // System.out.println(value);

                                                if (!ftlVal.contains(value)) {
                                                       ftlVal.add((String) value);
                                                       System.out.println(ftlVal);
                                                       i++;
                                                }
                                          }while (map.containsKey(key[i]));
                                   }
                             }
                             // System.out.println(finResult);
                      //}
                //}
</code>```

I need all the values for column2 and column6 in an arrylist and then to compare those columns with database column2 and column6

答:
Keeping aside how you compare the ArrayLists with the database columns, the following code will give you the two ArrayLists that you need.

```<code>ArrayList<String> column2List = new ArrayList<>();
ArrayList<String> column6List = new ArrayList<>();
for (Map<String, String> map : finResult) {
  String column2Value = map.get("Column2", null);
  String column6Value = map.get("Column6", null);
  column2List.add(column2Value);
  column6List.add(column6Value);
}
</code>```

The column2List and column6List are the two ArrayLists that you need.

Body:
I have read csv and stored the values in map (key-value format)
I need to fetch all values for 2 particular key into an array list to comapre it with database values columns

ArrayList ftlVal = new ArrayList<>();

                for (Map<String, String> map : finResult) {
                      Object[] key = {"Column2", "Column6"};
                      for (int i = 0; i < key.length; i++) {
                             do {
                                   //for (int j = 0; j <key.length; j++) {
                                          //while (map.get(key[j]) != null) {
                                                Object value = map.get(key[i]);
                                                // System.out.println(value);

                                                if (!ftlVal.contains(value)) {
                                                       ftlVal.add((String) value);
                                                       System.out.println(ftlVal);
                                                       i++;
                                                }
                                          }while (map.containsKey(key[i]));
                                   }
                             }
                             // System.out.println(finResult);
                      //}
                //}

I need all the values for column2 and column6 in an arrylist and then to compare those columns with database column2 and column6

Body:
Keeping aside how you compare the ArrayLists with the database columns, the following code will give you the two ArrayLists that you need.

ArrayList<String> column2List = new ArrayList<>();
ArrayList<String> column6List = new ArrayList<>();
for (Map<String, String> map : finResult) {
  String column2Value = map.get("Column2", null);
  String column6Value = map.get("Column6", null);
  column2List.add(column2Value);
  column6List.add(column6Value);
}

The column2List and column6List are the two ArrayLists that you need.


问:
How to reattach released PersistentVolume in Kubernetes
Here is my overall goal:

Have a MongoDB running

Persist the data through pod failures / updates etc

The approach I’ve taken:

K8S Provider: Digital Ocean

Nodes: 3

Create a PVC

Create a headless Service

Create a StatefulSet

Here’s a dumbed down version of the config:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: some-pvc
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
  storageClassName: do-block-storage
---
apiVersion: v1
kind: Service
metadata:
  name: some-headless-service
  labels:
    app: my-app
spec:
  ports:
  - port: 27017
    name: my-app-database
  clusterIP: None
  selector:
    app: my-app
    tier: database
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: my-app-database
  labels:
    app: my-app
    tier: database
spec:
  serviceName: some-headless-service
  replicas: 1
  selector:
    matchLabels:
      app: my-app
      tier: database
  template:
    metadata:
      labels:
        app: my-app
        tier: database
    spec:
      containers:
      - name: my-app-database
        image: mongo:latest
        volumeMounts:
        - name: some-volume
          mountPath: /data
        ports:
        - containerPort: 27017
          name: my-app-database
      volumes:
      - name: some-volume
        persistentVolumeClaim:
          claimName: some-pvc
</code>```

This is working as expected. I can spin down the replicas to 0:

kubectl scale —replicas=0 statefulset/my-app-database

Spin it back up:

kubectl scale —replicas=1 statefulset/my-app-database

And the data will persist..

But one time, as I was messing around by scaling the statefulset up and down, I was met with this error:

```<code>Volume is already exclusively attached to one node and can't be attached to another
</code>```

Being new to k8s, I deleted the PVC and “recreated” the same one:

```<code>kubectl delete pvc some-pvc
kubectl apply -f persistent-volume-claims/
</code>```

The statefulset spun back up with a new PV and the old PV was deleted as the persistentVolumeReclaimPolicy was set to Delete by default.

I set this new PV persistentVolumeReclaimPolicy to Retain to ensure that the data would not be automatically removed.. and I realized: I’m not sure how I’d reclaim that PV. Earlier to get through the “volume attachment” error, I deleted the PVC, which will just create another new PV with the setup I have, and now I’m left with my data in that Released PV.

My main questions are:

Does this overall sound like the right approach for my goal?

Should I look into adding a claimRef to the dynamically created PV and then recreating a new PVC with that claimRef, as mentioned here: Can a PVC be bound to a specific PV?

Should I be trying to get that fresh statefulset PVC to actually use that old PV?

Would it make sense to try to reattach the old PV to the correct node, and how would I do that?

答:
If your want to use StatefulSet with scalability, your storage should also support this, there are two way to handle this:

If do-block-storage storage class supprt ReadWriteMany, then put all pod's data in single volume.

Each pod use a different volume, add volumeClaimTemplate to your StatefulSet.spec,
then k8s will create PVC like some-pvc-{statefulset_name}-{idx} automatically:

```<code>spec:
  volumeClaimTemplates:
  - metadata:
      name: some-pvc
    spec:
      accessModes:
        - ReadWriteOnce
      resources:
        requests:
          storage: 5Gi
      storageClassName: do-block-storage
</code>```

Update:

StatefulSet replicas Must deploy with mongodb replication, then each pod in StatefulSet will has same data storage.

So when container run mongod command, you must add option --replSet={name}. when all pods up, execute command rs.initiate() to tell mongodb how to handle data replication. When you scale up or down StatefulSet, execute command rs.add() or rs.remove() to tell mongodb members has changed.

Body:
Here is my overall goal:

Have a MongoDB running

Persist the data through pod failures / updates etc

The approach I’ve taken:

K8S Provider: Digital Ocean

Nodes: 3

Create a PVC

Create a headless Service

Create a StatefulSet

Here’s a dumbed down version of the config:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: some-pvc
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
  storageClassName: do-block-storage
---
apiVersion: v1
kind: Service
metadata:
  name: some-headless-service
  labels:
    app: my-app
spec:
  ports:
  - port: 27017
    name: my-app-database
  clusterIP: None
  selector:
    app: my-app
    tier: database
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: my-app-database
  labels:
    app: my-app
    tier: database
spec:
  serviceName: some-headless-service
  replicas: 1
  selector:
    matchLabels:
      app: my-app
      tier: database
  template:
    metadata:
      labels:
        app: my-app
        tier: database
    spec:
      containers:
      - name: my-app-database
        image: mongo:latest
        volumeMounts:
        - name: some-volume
          mountPath: /data
        ports:
        - containerPort: 27017
          name: my-app-database
      volumes:
      - name: some-volume
        persistentVolumeClaim:
          claimName: some-pvc

This is working as expected. I can spin down the replicas to 0:

kubectl scale —replicas=0 statefulset/my-app-database

Spin it back up:

kubectl scale —replicas=1 statefulset/my-app-database

And the data will persist..

But one time, as I was messing around by scaling the statefulset up and down, I was met with this error:

Volume is already exclusively attached to one node and can't be attached to another

Being new to k8s, I deleted the PVC and “recreated” the same one:

kubectl delete pvc some-pvc
kubectl apply -f persistent-volume-claims/

The statefulset spun back up with a new PV and the old PV was deleted as the persistentVolumeReclaimPolicy was set to Delete by default.

I set this new PV persistentVolumeReclaimPolicy to Retain to ensure that the data would not be automatically removed.. and I realized: I’m not sure how I’d reclaim that PV. Earlier to get through the “volume attachment” error, I deleted the PVC, which will just create another new PV with the setup I have, and now I’m left with my data in that Released PV.

My main questions are:

Does this overall sound like the right approach for my goal?

Should I look into adding a claimRef to the dynamically created PV and then recreating a new PVC with that claimRef, as mentioned here: Can a PVC be bound to a specific PV?

Should I be trying to get that fresh statefulset PVC to actually use that old PV?

Would it make sense to try to reattach the old PV to the correct node, and how would I do that?

Body:
If your want to use StatefulSet with scalability, your storage should also support this, there are two way to handle this:

If do-block-storage storage class supprt ReadWriteMany, then put all pod's data in single volume.

Each pod use a different volume, add volumeClaimTemplate to your StatefulSet.spec,
then k8s will create PVC like some-pvc-{statefulset_name}-{idx} automatically:

spec:
  volumeClaimTemplates:
  - metadata:
      name: some-pvc
    spec:
      accessModes:
        - ReadWriteOnce
      resources:
        requests:
          storage: 5Gi
      storageClassName: do-block-storage

Update:

StatefulSet replicas Must deploy with mongodb replication, then each pod in StatefulSet will has same data storage.

So when container run mongod command, you must add option --replSet={name}. when all pods up, execute command rs.initiate() to tell mongodb how to handle data replication. When you scale up or down StatefulSet, execute command rs.add() or rs.remove() to tell mongodb members has changed.


问:
ACR to AKS deployment ERROR: The container operating system does not match the host operating system
I have deployed a windows container which runs successfully in my local system using docker. Moved the image to Azure container registry and deployed the image from ACR to AKS.

I have created a windows node using AKS windows preview

```<code>C:\Users\HTECH>kubectl get nodes -o wide
NAME                                STATUS   ROLES   AGE    VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                    KERNEL-VERSION      CONTAINER-RUNTIME
aks-nodepool1-36563144-vmss000000   Ready    agent   2d3h   v1.14.0   10.240.0.4    <none>        Ubuntu 16.04.6 LTS          4.15.0-1042-azure   docker://3.0.4
akssample000000                     Ready    agent   2d2h   v1.14.0   10.240.0.35   <none>        Windows Server Datacenter   10.0.17763.379      docker://18.9.2

</code>```

Docker File:

```<code>FROM microsoft/iis:latest
SHELL ["powershell"]

RUN Install-WindowsFeature NET-Framework-45-ASPNET ; \
    Install-WindowsFeature Web-Asp-Net45

COPY . ewims
RUN Remove-WebSite -Name 'Default Web Site'
RUN New-Website -Name 'sample' -Port 80 \
    -PhysicalPath 'c:\sample' -ApplicationPool '.NET v4.5'
EXPOSE 80
</code>```

Manifest YAML

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: samplecloudpoc-v1
spec:
  replicas: 1
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  minReadySeconds: 5
  selector:
    matchLabels:
      app: samplecloudpoc-v1
  template:
    metadata:
      labels:
        app: samplecloudpoc-v1
    spec:
      containers:
      - name: samplecloudpoc-v1
        image: samplecloud.azurecr.io/sample:v1
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 100m
          limits:
            cpu: 100m
        env:
        - name: dev
          value: "samplecloudpoc-v1"
      imagePullSecrets:
        - name: sampleauth
      nodeSelector:
        beta.kubernetes.io/os: windows
---
apiVersion: v1
kind: Service
metadata:
  name: samplecloudpoc-v1
spec:
  loadBalancerIP: 13.90.205.141
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: samplecloudpoc-v1

</code>```

While checking the deployement status using below command, I'm getting the following error.

```<code>D:\Cloud>kubectl describe po samplecloudpoc-v1-5d567d48d9-7gtx8
Name:               samplecloudpoc-v1-5d567d48d9-7gtx8
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               akssample000000/10.240.0.35
Start Time:         Thu, 30 May 2019 13:05:13 +0530
Labels:             app=samplecloudpoc-v1
                    pod-template-hash=5d567d48d9
Annotations:        <none>
Status:             Running
IP:                 10.240.0.44
Controlled By:      ReplicaSet/samplecloudpoc-v1-5d567d48d9
Containers:
  sample:
    Container ID:  docker://0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112
    Image:         samplecloud.azurecr.io/sample:v1
    Image ID:      docker-pullable://samplecloud.azurecr.io/sample@sha256:55ac14dc512abc0f8deebb8b87ee47d51fdfbfd997ce6cee0ab521bd69d42b08
    Port:          80/TCP
    Host Port:     0/TCP
    Args:
      -it
    State:       Waiting
      Reason:    CrashLoopBackOff
    Last State:  Terminated
      Reason:    ContainerCannotRun
      Message:   CreateComputeSystem 0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112: The container operating system does not match the host operating system.
(extra info: {"SystemType":"Container","Name":"0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112","Owner":"docker","VolumePath":"\\\\?\\Volume{f5ff1135-4e83-4baa-961d-f4533dcb6985}","IgnoreFlushesDuringBoot":true,"LayerFolderPath":"C:\\ProgramData\\docker\\windowsfilter\\0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112","Layers":[{"ID":"b3b88c23-310f-5e95-86bc-117e9f6a6184","Path":"C:\\ProgramData\\docker\\windowsfilter\\0cc15446c028e2fe68601b10a1921a809dedb2a981162c4ed90344d2fde58f0e"},{"ID":"fb1ae57e-89dc-502c-996b-75804b972adc","Path":"C:\\ProgramData\\docker\\windowsfilter\\7217ca2e8bbd2c431c9db44050946ec4f8040c42fdd79f7ceae321e48dc5ca0d"},{"ID":"bb5e3864-b1af-51c8-a8e4-63d88749f082","Path":"C:\\ProgramData\\docker\\windowsfilter\\16f07ffe70a600c95bea2e8297c04cbb6af877562c2cc2ac1693267b152d3793"},{"ID":"2fae8c16-582f-5ab1-acfe-0a88980adec3","Path":"C:\\ProgramData\\docker\\windowsfilter\\a325070d766dd4af490b433d75eac6e1d71297961d89011e5798949eae2e7e4a"},{"ID":"dffd6df2-a500-5985-9c9c-1bc03c9efce3","Path":"C:\\ProgramData\\docker\\windowsfilter\\1221f773d66647fd1dc7aad44693f28843c8385612edb520231c1cb754eb2f97"},{"ID":"7e349a26-81b9-554e-aa13-a6e4286de93e","Path":"C:\\ProgramData\\docker\\windowsfilter\\67d6d22eae7f829e590fde792c6b8129aff3d9f9242850fe72e8d167e284a6b7"},{"ID":"8730db1a-385d-5e9a-a4ec-c45525b5fcb3","Path":"C:\\ProgramData\\docker\\windowsfilter\\2a53ed97b10bd4f67e62e8511e8922496651f3d343dd1889425ba1bedca134fa"},{"ID":"d1e23520-6c0b-5909-8e52-bb6961f80876","Path":"C:\\ProgramData\\docker\\windowsfilter\\d3a27083556be1bb7e36997f0eee2b544f6a16eab94797715bc21db99bf42e88"},{"ID":"18d8ab30-09e9-54e3-a991-f48cca651c8d","Path":"C:\\ProgramData\\docker\\windowsfilter\\9b4143f537ff70f6b1e05b2a5e38e3b05dd2a4b2f624822e32bb2b7cd17b7cca"},{"ID":"2acb6fa3-f27c-50cf-9033-eedb06d5bf32","Path":"C:\\ProgramData\\docker\\windowsfilter\\f71b6708cc4045bf9633f971dd4d6eddb1c5ffeda52d38e648c740e0e277b2df"},{"ID":"0dc40cf1-482a-5fed-af35-c5d1902b95ae","Path":"C:\\ProgramData\\docker\\windowsfilter\\100f3380579a77f2fb2c0f997201e34a0dd2c42e4b0d9a39fb850706aa16e474"}],"ProcessorWeight":5000,"HostName":"samplecloudpoc-v1-5d567d48d9-7gtx8","MappedDirectories":[{"HostPath":"c:\\var\\lib\\kubelet\\pods\\75f48f65-82ad-11e9-8e99-a24a72224ed5\\volumes\\kubernetes.io~secret\\default-token-67g2m","ContainerPath":"c:\\var\\run\\secrets\\kubernetes.io\\serviceaccount","ReadOnly":true,"BandwidthMaximum":0,"IOPSMaximum":0,"CreateInUtilityVM":false}],"HvPartition":false,"NetworkSharedContainerName":"d11237887aec604bfbb9b3cd56fca586975e5a92e04dab4d4ba19b1fcc56ed99"})
      Exit Code:    128
      Started:      Thu, 30 May 2019 13:25:00 +0530
      Finished:     Thu, 30 May 2019 13:25:00 +0530
    Ready:          False
    Restart Count:  5
    Limits:
      cpu:  100m
    Requests:
      cpu:  100m
    Environment:
      dev:  samplecloudpoc-v1
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-67g2m (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-67g2m:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-67g2m
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  beta.kubernetes.io/os=windows
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason     Age                    From                      Message
  ----     ------     ----                   ----                      -------
  Normal   Scheduled  21m                    default-scheduler         Successfully assigned default/samplecloudpoc-v1-5d567d48d9-7gtx8 to akssample000000
  Normal   Pulling    21m                    kubelet, akssample000000  Pulling image "samplecloud.azurecr.io/sample:v1"
  Normal   Pulled     4m31s                  kubelet, akssample000000  Successfully pulled image "samplecloud.azurecr.io/sample:v1"
  Normal   Created    3m (x5 over 4m31s)     kubelet, akssample000000  Created container sample
  Normal   Pulled     3m (x4 over 4m28s)     kubelet, akssample000000  Container image "samplecloud.azurecr.io/sample:v1" already present on machine
  Warning  Failed     2m59s (x5 over 4m30s)  kubelet, akssample000000  Error: failed to start container "sample": Error response from daemon: CreateComputeSystem sample: The container operating system does not match the host operating system.
(extra info: {"SystemType":"Container","Name":"sample","Owner":"docker","VolumePath":"\\\\?\\Volume{f5ff1135-4e83-4baa-961d-f4533dcb6985}","IgnoreFlushesDuringBoot":true,"LayerFolderPath":"C:\\ProgramData\\docker\\windowsfilter\\sample","Layers":[{"ID":"b3b88c23-310f-5e95-86bc-117e9f6a6184","Path":"C:\\ProgramData\\docker\\windowsfilter\\0cc15446c028e2fe68601b10a1921a809dedb2a981162c4ed90344d2fde58f0e"},{"ID":"fb1ae57e-89dc-502c-996b-75804b972adc","Path":"C:\\ProgramData\\docker\\windowsfilter\\7217ca2e8bbd2c431c9db44050946ec4f8040c42fdd79f7ceae321e48dc5ca0d"},{"ID":"bb5e3864-b1af-51c8-a8e4-63d88749f082","Path":"C:\\ProgramData\\docker\\windowsfilter\\16f07ffe70a600c95bea2e8297c04cbb6af877562c2cc2ac1693267b152d3793"},{"ID":"2fae8c16-582f-5ab1-acfe-0a88980adec3","Path":"C:\\ProgramData\\docker\\windowsfilter\\a325070d766dd4af490b433d75eac6e1d71297961d89011e5798949eae2e7e4a"},{"ID":"dffd6df2-a500-5985-9c9c-1bc03c9efce3","Path":"C:\\ProgramData\\docker\\windowsfilter\\1221f773d66647fd1dc7aad44693f28843c8385612edb520231c1cb754eb2f97"},{"ID":"7e349a26-81b9-554e-aa13-a6e4286de93e","Path":"C:\\ProgramData\\docker\\windowsfilter\\67d6d22eae7f829e590fde792c6b8129aff3d9f9242850fe72e8d167e284a6b7"},{"ID":"8730db1a-385d-5e9a-a4ec-c45525b5fcb3","Path":"C:\\ProgramData\\docker\\windowsfilter\\2a53ed97b10bd4f67e62e8511e8922496651f3d343dd1889425ba1bedca134fa"},{"ID":"d1e23520-6c0b-5909-8e52-bb6961f80876","Path":"C:\\ProgramData\\docker\\windowsfilter\\d3a27083556be1bb7e36997f0eee2b544f6a16eab94797715bc21db99bf42e88"},{"ID":"18d8ab30-09e9-54e3-a991-f48cca651c8d","Path":"C:\\ProgramData\\docker\\windowsfilter\\9b4143f537ff70f6b1e05b2a5e38e3b05dd2a4b2f624822e32bb2b7cd17b7cca"},{"ID":"2acb6fa3-f27c-50cf-9033-eedb06d5bf32","Path":"C:\\ProgramData\\docker\\windowsfilter\\f71b6708cc4045bf9633f971dd4d6eddb1c5ffeda52d38e648c740e0e277b2df"},{"ID":"0dc40cf1-482a-5fed-af35-c5d1902b95ae","Path":"C:\\ProgramData\\docker\\windowsfilter\\100f3380579a77f2fb2c0f997201e34a0dd2c42e4b0d9a39fb850706aa16e474"}],"ProcessorWeight":5000,"HostName":"samplecloudpoc-v1-5d567d48d9-7gtx8","MappedDirectories":[{"HostPath":"c:\\var\\lib\\kubelet\\pods\\75f48f65-82ad-11e9-8e99-a24a72224ed5\\volumes\\kubernetes.io~secret\\default-token-67g2m","ContainerPath":"c:\\var\\run\\secrets\\kubernetes.io\\serviceaccount","ReadOnly":true,"BandwidthMaximum":0,"IOPSMaximum":0,"CreateInUtilityVM":false}],"HvPartition":false,"NetworkSharedContainerName":"d11237887aec604bfbb9b3cd56fca586975e5a92e04dab4d4ba19b1fcc56ed99"})
  Warning  BackOff  119s (x10 over 3m59s)  kubelet, akssample000000  Back-off restarting failed container

</code>```

I have tried to fix this by pulling the latest version IIS image from docker also throws the same error.

答: It seems you just need to change the apiVersion into apps/v1, then the pod will run well. I test the apiVersion as yours and also get the error "Back-off restarting failed container".</p>

Body:
I have deployed a windows container which runs successfully in my local system using docker. Moved the image to Azure container registry and deployed the image from ACR to AKS.

I have created a windows node using AKS windows preview

C:\Users\HTECH>kubectl get nodes -o wide
NAME                                STATUS   ROLES   AGE    VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                    KERNEL-VERSION      CONTAINER-RUNTIME
aks-nodepool1-36563144-vmss000000   Ready    agent   2d3h   v1.14.0   10.240.0.4    <none>        Ubuntu 16.04.6 LTS          4.15.0-1042-azure   docker://3.0.4
akssample000000                     Ready    agent   2d2h   v1.14.0   10.240.0.35   <none>        Windows Server Datacenter   10.0.17763.379      docker://18.9.2

Docker File:

FROM microsoft/iis:latest
SHELL ["powershell"]

RUN Install-WindowsFeature NET-Framework-45-ASPNET ; \
    Install-WindowsFeature Web-Asp-Net45

COPY . ewims
RUN Remove-WebSite -Name 'Default Web Site'
RUN New-Website -Name 'sample' -Port 80 \
    -PhysicalPath 'c:\sample' -ApplicationPool '.NET v4.5'
EXPOSE 80

Manifest YAML

apiVersion: apps/v1
kind: Deployment
metadata:
  name: samplecloudpoc-v1
spec:
  replicas: 1
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  minReadySeconds: 5
  selector:
    matchLabels:
      app: samplecloudpoc-v1
  template:
    metadata:
      labels:
        app: samplecloudpoc-v1
    spec:
      containers:
      - name: samplecloudpoc-v1
        image: samplecloud.azurecr.io/sample:v1
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 100m
          limits:
            cpu: 100m
        env:
        - name: dev
          value: "samplecloudpoc-v1"
      imagePullSecrets:
        - name: sampleauth
      nodeSelector:
        beta.kubernetes.io/os: windows
---
apiVersion: v1
kind: Service
metadata:
  name: samplecloudpoc-v1
spec:
  loadBalancerIP: 13.90.205.141
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: samplecloudpoc-v1

While checking the deployement status using below command, I'm getting the following error.

D:\Cloud>kubectl describe po samplecloudpoc-v1-5d567d48d9-7gtx8
Name:               samplecloudpoc-v1-5d567d48d9-7gtx8
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               akssample000000/10.240.0.35
Start Time:         Thu, 30 May 2019 13:05:13 +0530
Labels:             app=samplecloudpoc-v1
                    pod-template-hash=5d567d48d9
Annotations:        <none>
Status:             Running
IP:                 10.240.0.44
Controlled By:      ReplicaSet/samplecloudpoc-v1-5d567d48d9
Containers:
  sample:
    Container ID:  docker://0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112
    Image:         samplecloud.azurecr.io/sample:v1
    Image ID:      docker-pullable://samplecloud.azurecr.io/sample@sha256:55ac14dc512abc0f8deebb8b87ee47d51fdfbfd997ce6cee0ab521bd69d42b08
    Port:          80/TCP
    Host Port:     0/TCP
    Args:
      -it
    State:       Waiting
      Reason:    CrashLoopBackOff
    Last State:  Terminated
      Reason:    ContainerCannotRun
      Message:   CreateComputeSystem 0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112: The container operating system does not match the host operating system.
(extra info: {"SystemType":"Container","Name":"0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112","Owner":"docker","VolumePath":"\\\\?\\Volume{f5ff1135-4e83-4baa-961d-f4533dcb6985}","IgnoreFlushesDuringBoot":true,"LayerFolderPath":"C:\\ProgramData\\docker\\windowsfilter\\0cf6c92b15738c2786caca5b989aa2773c9375352cb4f1d95472ff63cc7b5112","Layers":[{"ID":"b3b88c23-310f-5e95-86bc-117e9f6a6184","Path":"C:\\ProgramData\\docker\\windowsfilter\\0cc15446c028e2fe68601b10a1921a809dedb2a981162c4ed90344d2fde58f0e"},{"ID":"fb1ae57e-89dc-502c-996b-75804b972adc","Path":"C:\\ProgramData\\docker\\windowsfilter\\7217ca2e8bbd2c431c9db44050946ec4f8040c42fdd79f7ceae321e48dc5ca0d"},{"ID":"bb5e3864-b1af-51c8-a8e4-63d88749f082","Path":"C:\\ProgramData\\docker\\windowsfilter\\16f07ffe70a600c95bea2e8297c04cbb6af877562c2cc2ac1693267b152d3793"},{"ID":"2fae8c16-582f-5ab1-acfe-0a88980adec3","Path":"C:\\ProgramData\\docker\\windowsfilter\\a325070d766dd4af490b433d75eac6e1d71297961d89011e5798949eae2e7e4a"},{"ID":"dffd6df2-a500-5985-9c9c-1bc03c9efce3","Path":"C:\\ProgramData\\docker\\windowsfilter\\1221f773d66647fd1dc7aad44693f28843c8385612edb520231c1cb754eb2f97"},{"ID":"7e349a26-81b9-554e-aa13-a6e4286de93e","Path":"C:\\ProgramData\\docker\\windowsfilter\\67d6d22eae7f829e590fde792c6b8129aff3d9f9242850fe72e8d167e284a6b7"},{"ID":"8730db1a-385d-5e9a-a4ec-c45525b5fcb3","Path":"C:\\ProgramData\\docker\\windowsfilter\\2a53ed97b10bd4f67e62e8511e8922496651f3d343dd1889425ba1bedca134fa"},{"ID":"d1e23520-6c0b-5909-8e52-bb6961f80876","Path":"C:\\ProgramData\\docker\\windowsfilter\\d3a27083556be1bb7e36997f0eee2b544f6a16eab94797715bc21db99bf42e88"},{"ID":"18d8ab30-09e9-54e3-a991-f48cca651c8d","Path":"C:\\ProgramData\\docker\\windowsfilter\\9b4143f537ff70f6b1e05b2a5e38e3b05dd2a4b2f624822e32bb2b7cd17b7cca"},{"ID":"2acb6fa3-f27c-50cf-9033-eedb06d5bf32","Path":"C:\\ProgramData\\docker\\windowsfilter\\f71b6708cc4045bf9633f971dd4d6eddb1c5ffeda52d38e648c740e0e277b2df"},{"ID":"0dc40cf1-482a-5fed-af35-c5d1902b95ae","Path":"C:\\ProgramData\\docker\\windowsfilter\\100f3380579a77f2fb2c0f997201e34a0dd2c42e4b0d9a39fb850706aa16e474"}],"ProcessorWeight":5000,"HostName":"samplecloudpoc-v1-5d567d48d9-7gtx8","MappedDirectories":[{"HostPath":"c:\\var\\lib\\kubelet\\pods\\75f48f65-82ad-11e9-8e99-a24a72224ed5\\volumes\\kubernetes.io~secret\\default-token-67g2m","ContainerPath":"c:\\var\\run\\secrets\\kubernetes.io\\serviceaccount","ReadOnly":true,"BandwidthMaximum":0,"IOPSMaximum":0,"CreateInUtilityVM":false}],"HvPartition":false,"NetworkSharedContainerName":"d11237887aec604bfbb9b3cd56fca586975e5a92e04dab4d4ba19b1fcc56ed99"})
      Exit Code:    128
      Started:      Thu, 30 May 2019 13:25:00 +0530
      Finished:     Thu, 30 May 2019 13:25:00 +0530
    Ready:          False
    Restart Count:  5
    Limits:
      cpu:  100m
    Requests:
      cpu:  100m
    Environment:
      dev:  samplecloudpoc-v1
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-67g2m (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-67g2m:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-67g2m
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  beta.kubernetes.io/os=windows
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason     Age                    From                      Message
  ----     ------     ----                   ----                      -------
  Normal   Scheduled  21m                    default-scheduler         Successfully assigned default/samplecloudpoc-v1-5d567d48d9-7gtx8 to akssample000000
  Normal   Pulling    21m                    kubelet, akssample000000  Pulling image "samplecloud.azurecr.io/sample:v1"
  Normal   Pulled     4m31s                  kubelet, akssample000000  Successfully pulled image "samplecloud.azurecr.io/sample:v1"
  Normal   Created    3m (x5 over 4m31s)     kubelet, akssample000000  Created container sample
  Normal   Pulled     3m (x4 over 4m28s)     kubelet, akssample000000  Container image "samplecloud.azurecr.io/sample:v1" already present on machine
  Warning  Failed     2m59s (x5 over 4m30s)  kubelet, akssample000000  Error: failed to start container "sample": Error response from daemon: CreateComputeSystem sample: The container operating system does not match the host operating system.
(extra info: {"SystemType":"Container","Name":"sample","Owner":"docker","VolumePath":"\\\\?\\Volume{f5ff1135-4e83-4baa-961d-f4533dcb6985}","IgnoreFlushesDuringBoot":true,"LayerFolderPath":"C:\\ProgramData\\docker\\windowsfilter\\sample","Layers":[{"ID":"b3b88c23-310f-5e95-86bc-117e9f6a6184","Path":"C:\\ProgramData\\docker\\windowsfilter\\0cc15446c028e2fe68601b10a1921a809dedb2a981162c4ed90344d2fde58f0e"},{"ID":"fb1ae57e-89dc-502c-996b-75804b972adc","Path":"C:\\ProgramData\\docker\\windowsfilter\\7217ca2e8bbd2c431c9db44050946ec4f8040c42fdd79f7ceae321e48dc5ca0d"},{"ID":"bb5e3864-b1af-51c8-a8e4-63d88749f082","Path":"C:\\ProgramData\\docker\\windowsfilter\\16f07ffe70a600c95bea2e8297c04cbb6af877562c2cc2ac1693267b152d3793"},{"ID":"2fae8c16-582f-5ab1-acfe-0a88980adec3","Path":"C:\\ProgramData\\docker\\windowsfilter\\a325070d766dd4af490b433d75eac6e1d71297961d89011e5798949eae2e7e4a"},{"ID":"dffd6df2-a500-5985-9c9c-1bc03c9efce3","Path":"C:\\ProgramData\\docker\\windowsfilter\\1221f773d66647fd1dc7aad44693f28843c8385612edb520231c1cb754eb2f97"},{"ID":"7e349a26-81b9-554e-aa13-a6e4286de93e","Path":"C:\\ProgramData\\docker\\windowsfilter\\67d6d22eae7f829e590fde792c6b8129aff3d9f9242850fe72e8d167e284a6b7"},{"ID":"8730db1a-385d-5e9a-a4ec-c45525b5fcb3","Path":"C:\\ProgramData\\docker\\windowsfilter\\2a53ed97b10bd4f67e62e8511e8922496651f3d343dd1889425ba1bedca134fa"},{"ID":"d1e23520-6c0b-5909-8e52-bb6961f80876","Path":"C:\\ProgramData\\docker\\windowsfilter\\d3a27083556be1bb7e36997f0eee2b544f6a16eab94797715bc21db99bf42e88"},{"ID":"18d8ab30-09e9-54e3-a991-f48cca651c8d","Path":"C:\\ProgramData\\docker\\windowsfilter\\9b4143f537ff70f6b1e05b2a5e38e3b05dd2a4b2f624822e32bb2b7cd17b7cca"},{"ID":"2acb6fa3-f27c-50cf-9033-eedb06d5bf32","Path":"C:\\ProgramData\\docker\\windowsfilter\\f71b6708cc4045bf9633f971dd4d6eddb1c5ffeda52d38e648c740e0e277b2df"},{"ID":"0dc40cf1-482a-5fed-af35-c5d1902b95ae","Path":"C:\\ProgramData\\docker\\windowsfilter\\100f3380579a77f2fb2c0f997201e34a0dd2c42e4b0d9a39fb850706aa16e474"}],"ProcessorWeight":5000,"HostName":"samplecloudpoc-v1-5d567d48d9-7gtx8","MappedDirectories":[{"HostPath":"c:\\var\\lib\\kubelet\\pods\\75f48f65-82ad-11e9-8e99-a24a72224ed5\\volumes\\kubernetes.io~secret\\default-token-67g2m","ContainerPath":"c:\\var\\run\\secrets\\kubernetes.io\\serviceaccount","ReadOnly":true,"BandwidthMaximum":0,"IOPSMaximum":0,"CreateInUtilityVM":false}],"HvPartition":false,"NetworkSharedContainerName":"d11237887aec604bfbb9b3cd56fca586975e5a92e04dab4d4ba19b1fcc56ed99"})
  Warning  BackOff  119s (x10 over 3m59s)  kubelet, akssample000000  Back-off restarting failed container

I have tried to fix this by pulling the latest version IIS image from docker also throws the same error.


问:
Problem to Implement intlTelInput in Laravel
I am using intlTelInput in plain HTML/CSS using below code and it's working fine you can see the demo (intl-tel-input sample).

HTML code

```<code><label for="phone" class="control-label">Mobile Phone Number</label><br/>
<input type="tel" class="form-control" id="phone" placeholder="">
</code>```

Javascript code

```<code> <script>
 var input = document.querySelector("#phone");
intlTelInput(input, {
initialCountry: "auto",
geoIpLookup: function(success, failure) {
    $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
        var countryCode = (resp && resp.country) ? resp.country : "";
        success(countryCode);
    });
},
utilsScript: "css/intl-tel-input-master/build/js/utils.js"
});
</code>```

Now, I am using the same code in laravel and it shows me nothing. Can you please tell me how to solve the issue?

GET https://ipinfo.io/?callback=jQuery1111094…1559198167627&=1559198167628 net::ERR_ABORTED 429

答:
For future reference, here is the answer

Links in head tag

```<code><link rel="stylesheet" href="{{ asset ('css/intl-tel-input/build/css/intlTelInput.css') }}"/>
<script src="{{ asset ('css/intl-tel-input/build/js/intlTelInput.min.js') }}"></script>
</code>```

Html code

```<code><input type="tel" id="phone" placeholder="">
</code>```

Script

```<code><script>
var input = document.querySelector("#phone");
window.intlTelInput(input);
</script>
</code>```

Body:
I am using intlTelInput in plain HTML/CSS using below code and it's working fine you can see the demo (intl-tel-input sample).

HTML code

Mobile Phone Number

<input type="tel" class="form-control" id="phone" placeholder="">

Javascript code

Body:
For future reference, here is the answer

Links in head tag

<link rel="stylesheet" href="{{ asset ('css/intl-tel-input/build/css/intlTelInput.css') }}"/>
<script src="{{ asset ('css/intl-tel-input/build/js/intlTelInput.min.js') }}"></script>

Html code

<input type="tel" id="phone" placeholder="">

Script

<script>
var input = document.querySelector("#phone");
window.intlTelInput(input);
</script>


问:
Android Remote Video with Titanium
Greetings all!

I'm trying to play a video that is hosted on our webserver on an android phone. I've already built this for iPhone and it works great.

Droid, however is a different issue. Instead of getting video, I'm just getting a black screen, no error or anything.

The code I am using is:

activeContent = Titanium.Media.createVideoPlayer({
      contentURL: content,
      backgroundColor:'#111',
      movieControlMode:Titanium.Media.VIDEO_CONTROL_DEFAULT
});

win.add(activeContent);
activeContent.play();

The video I'm downloading does play on the droid when not using Titanium, so I know its not a format issue. (its an .MP4 incase anyone is wondering.)

I've used Titanium SDK's 1.5.1 and am on the continuous build of 1.6.0 from earlier today.

using the 2.2 Droid SDK, and Titanium Developer 1.2.2

Does anyone have any thoughts on this? One of the big selling points for android is its ability to pull media from the net, and I'm honestly a little concerned about this shortcoming if its an issue with Titanium.

答:
For Android, the video player should not be added to the window. Android will open its video player in a new window when you call play(). So your code should instead look like this:

activeContent = Titanium.Media.createVideoPlayer({ contentURL: content, backgroundColor:'#111', movieControlMode:Titanium.Media.VIDEO_CONTROL_DEFAULT });

activeContent.play();

Blessings!

Title: Android Remote Video with Titanium

ContentLicense: CC BY-SA 3.0


问:
In Promise loop, how to wait on request response?
I'm trying to make a loop that sends requests.

However, I would like to wait to receive the answer of the request before sending the next one. How can I proceed?

```<code> private start(): Promise<string> {
    return new Promise((resolve, reject) => {
      for (let j = 0, p = Promise.resolve(); j < count; j++) {
        p = p.then(_ => new Promise<null>(res =>
          setTimeout(() => {
            if (j === (count - 1)) {
              resolve();
            } else {
              this.http.get();
              res();
            }
          }, 1000)
        ));
      }
    });
  }
</code>```

Thanks for helping

答:
you can try like this </p>

```<code>async mainFunction () {
for(let i = 0; i < count; i++) {
    await apiCallFunction();
    // other code
}
}

apiCallFunction() {
 return new Promise((resolve, reject) => {
    this.http.get().subscribe(resp => {
      resolve();
    });
 })
}

</code>```

Body:
I'm trying to make a loop that sends requests.

However, I would like to wait to receive the answer of the request before sending the next one. How can I proceed?

 private start(): Promise<string> {
    return new Promise((resolve, reject) => {
      for (let j = 0, p = Promise.resolve(); j < count; j++) {
        p = p.then(_ => new Promise<null>(res =>
          setTimeout(() => {
            if (j === (count - 1)) {
              resolve();
            } else {
              this.http.get();
              res();
            }
          }, 1000)
        ));
      }
    });
  }

Thanks for helping

Body:
you can try like this

async mainFunction () {
for(let i = 0; i < count; i++) {
    await apiCallFunction();
    // other code
}
}

apiCallFunction() {
 return new Promise((resolve, reject) => {
    this.http.get().subscribe(resp => {
      resolve();
    });
 })
}


问:
iptables gets huge because of fail2ban
fail2ban is filling my iptables even though it is releasing banned IPs after a certain time. It seems that attacks are very frequent on my server. As a result, my iptables is getting huge. Is there any issue if iptables contains 5000 entries or more? Thank you.</p>

答: To solve this issue, I reduced the bantime recidive filter from the previous value (1 week) to 1 day. Now iptables entries are recycled everyday.</p>

Title: iptables gets huge because of fail2ban


问:
MongoDB HashTable Averages
I am using c#,along with MongoDB.
I have a class that can be resembled by this.
Its a sample, that represents something, please dont comment on the class design

```<code>[CollectionName("Venues")]
public class Venue
{
   public string Name { get; set; }
   public dictionary<string,object> Properties { get; set; }
}

var venue = new Venue
{
  Name = "Venue 1",
  Properties = new Dictionary<string,object>
  {
    { "Chairs", "18" },
    { "Tables", "4" },
    { "HasWaterfall", true }
  }
}
</code>```

Assuming I have an object in a collection, that looks like that.
I would like to find out of it is possible to do two things.

1: Load from the database, only a single item from the dictionary,
   currently I can only see how this can be done, by loading the entire
   record from the database and then manually getting the value by key.

2: Determine the average of a single item within the database.
   For example, across all records I would like to work out the average
   chairs, again without loading all records and then doing it in memory with
   linq etc....

答:
here's an alternative way of doing it using MongoDB.Entities convenience library.

using System.Collections.Generic;
using System.Linq;
using MongoDB.Entities;

namespace StackOverflow
{
    class Program
    {
        [Name("Venues")]
        public class Venue : Entity
        {
            public string Name { get; set; }
            public Dictionary<string, object> Properties { get; set; }
        }

        static void Main(string[] args)
        {
            new DB("test");

            var venue1 = new Venue
            {
                Name = "Venue 1",
                Properties = new Dictionary<string, object>  {
                    { "Chairs", 28 },
                    { "Tables", 4 },
                    { "HasWaterfall", true }
                }
            };
            venue1.Save();

            var venue2 = new Venue
            {
                Name = "Venue 2",
                Properties = new Dictionary<string, object>  {
                    { "Chairs", 38 },
                    { "Tables", 4 },
                    { "HasWaterfall", true }
                }
            };
            venue2.Save();

            var chairs = DB.Find<Venue, object>()
                           .Match(v => v.Name == "Venue 1")
                           .Project(v => new { ChairCount = v.Properties["Chairs"] })
                           .Execute();

            var avgChairs = DB.Collection<Venue>()
                              .Average(v => (int)v.Properties["Chairs"]);

        }
    }
}
```

<p>results in the following queries being made to the database:</p>

<p>getting chairs in venue 1:</p>

<pre class="lang-java prettyprint-override"><code>db.runCommand({
    "find": "Venues",
    "filter": {
        "Name": "Venue 1"
    },
    "projection": {
        "Properties.Chairs": NumberInt("1"),
        "_id": NumberInt("0")
    },
    "$db": "test"
})
</code>```

getting average chair count across all venues:

db.Venues.aggregate([
    {
        "$group": {
            "_id": NumberInt("1"),
            "__result": {
                "$avg": "$Properties.Chairs"
            }
        }
    }
])
```

Title: MongoDB HashTable Averages

Body:
I am using c#,along with MongoDB.
I have a class that can be resembled by this.
Its a sample, that represents something, please dont comment on the class design

[CollectionName("Venues")]
public class Venue
{
   public string Name { get; set; }
   public dictionary<string,object> Properties { get; set; }
}

var venue = new Venue
{
  Name = "Venue 1",
  Properties = new Dictionary<string,object>
  {
    { "Chairs", "18" },
    { "Tables", "4" },
    { "HasWaterfall", true }
  }
}

Assuming I have an object in a collection, that looks like that.
I would like to find out of it is possible to do two things.

1: Load from the database, only a single item from the dictionary,
   currently I can only see how this can be done, by loading the entire
   record from the database and then manually getting the value by key.

2: Determine the average of a single item within the database.
   For example, across all records I would like to work out the average
   chairs, again without loading all records and then doing it in memory with
   linq etc....

Body:
here's an alternative way of doing it using MongoDB.Entities convenience library.

using System.Collections.Generic;
using System.Linq;
using MongoDB.Entities;

namespace StackOverflow
{
    class Program
    {
        [Name("Venues")]
        public class Venue : Entity
        {
            public string Name { get; set; }
            public Dictionary<string, object> Properties { get; set; }
        }

        static void Main(string[] args)
        {
            new DB("test");

            var venue1 = new Venue
            {
                Name = "Venue 1",
                Properties = new Dictionary<string, object>  {
                    { "Chairs", 28 },
                    { "Tables", 4 },
                    { "HasWaterfall", true }
                }
            };
            venue1.Save();

            var venue2 = new Venue
            {
                Name = "Venue 2",
                Properties = new Dictionary<string, object>  {
                    { "Chairs", 38 },
                    { "Tables", 4 },
                    { "HasWaterfall", true }
                }
            };
            venue2.Save();

            var chairs = DB.Find<Venue, object>()
                           .Match(v => v.Name == "Venue 1")
                           .Project(v => new { ChairCount = v.Properties["Chairs"] })
                           .Execute();

            var avgChairs = DB.Collection<Venue>()
                              .Average(v => (int)v.Properties["Chairs"]);

        }
    }
}

results in the following queries being made to the database:

getting chairs in venue 1:

db.runCommand({
    "find": "Venues",
    "filter": {
        "Name": "Venue 1"
    },
    "projection": {
        "Properties.Chairs": NumberInt("1"),
        "_id": NumberInt("0")
    },
    "$db": "test"
})

getting average chair count across all venues:

db.Venues.aggregate([
    {
        "$group": {
            "_id": NumberInt("1"),
            "__result": {
                "$avg": "$Properties.Chairs"
            }
        }
    }
])


问:
How can I return a user input as a variable, to be called by another script?
I want to return a user input value from a GUI I made with Tkinter, I want this to be stored as a variable, so I can use the import from function in another script to call back this value (for calculations).

I have tried assigning multiple functions to the button, and setting the variable from within a def.

The four scripts at the bottom are working perfectly with the GUI, however, I currently have them set to yardstick = input() - thus prompting the user to input the value into the console, I would like this to be done from within the GUI when selecting the model. (think yardstick = v) from the code below.

```<code>import tkinter as tk

# --- main ---

scripts = ["CPS.py", "BPS.py", "WWI.py", "WWSST.py",]

OPTIONS = ["Combined Pumping Stations", "Booster Pumping Station", "Waste Water Ionisation", "Waste Water Sludge Storage Tanks (Concrete)"]

root = tk.Tk()
root.title('Birch Forest')
root.minsize(500,200)

# --- Listbox ---

tk.Label(root, text='Element Name', bg='#00C78C').pack(fill='x')

l = tk.Listbox(root, selectmode='single')

l.pack(side="left", fill="both",expand=True)
l.insert('end', *OPTIONS)

# --- Textbox ---

def printtext():
    global e
    string = e.get()
    v = (string)
    print(v)

e = tk.Entry(root)
e.pack()
e.focus_set()

b = tk.Button(root,text='Save',command=printtext)
b.pack(side='bottom')

# --- functions ---
def on_button():

    # different examples with `curselection()`

    for idx in l.curselection():
        if OPTIONS[idx] == 'Combined Pumping Stations':
            print("Running Random Forest Simulation")
        elif OPTIONS[idx] == 'Booster Pumping Stations':
            print("Running Random Forest Simulation")
        elif OPTIONS[idx] == 'Waste Water Ionisation':
            print("Running Random Forest Simulation")
        elif OPTIONS[idx] == 'Waste Water Sludge Storage Tanks (Concrete)':
            print("Running Random Forest Simulation")

    for idx in l.curselection():
        if idx == 0:
            import CPS
        elif idx == 1:
            import BPS
        elif idx == 2:
            import WWI
        elif idx == 3:
            import WWSST

# --- Button ---

b = tk.Button(root, text='Run Simulation', bg='#76EEC6', command=on_button)
b.pack(fill = "x", side="right", expand = True)

root.mainloop()
</code>```

Image 1:

Image 2:

Put simply; I would like v on line 28 to return as a variable in the variable explorer so I can call on it in script CPS when determining the yardstick value.

答:
Essentially what you want to do is share data between the main script and some others that it imports. A good way to do this is by storing that data in a module and import`ing it into all scripts the want access to these values.

First create an empty script file, for example shared.py.

Then add an import shared to the beginning of your main script (i.e. Birchforest.py).

After that, modify the 'Save' button callback printtext() so it stores the value in a named attribute of this module:

```<code>import shared
.
.
.
# --- Textbox ---

def printtext():
    global e
    shared.v = e.get()  # Store current Entry value in shared module.
</code>```

Lastly, you must do add an import shared the beginning of the scripts that are going to be imported by the main script (i.e. CPS.py, BPS.py, etc) so they can access to this shared data.

For example:

```<code>import shared

print('in CPS')
print('  shared.v:', shared.v)

... # rest of script
</code>```

After doing this they will be able to access any values that the main script has put into the shared module's namespace.

This works because imported modules are cached in sys.modules, and if another script imports a module that has already be imported by some other script, the cached value is used instead of reloading and executing the named script again.

This effectively means that modules are implemented in a way that means they follow the Singleton design pattern—because they're instances of types.ModuleType class.

If you wish you can define defaults for values of the attributes, in which case shared.py would no longer be empty. Keep in mind however, that changes made to those values at runtime via assignment statements in any other module will not be persistent since the changes are only being made to in the in-memory version of the module (cached in the sys.modules list), not to the corresponding script .py file itself.

A similar idea is described in the How do I share global variables across modules? section of the online documentation.

Body:
I want to return a user input value from a GUI I made with Tkinter, I want this to be stored as a variable, so I can use the import from function in another script to call back this value (for calculations).

I have tried assigning multiple functions to the button, and setting the variable from within a def.

The four scripts at the bottom are working perfectly with the GUI, however, I currently have them set to yardstick = input() - thus prompting the user to input the value into the console, I would like this to be done from within the GUI when selecting the model. (think yardstick = v) from the code below.

import tkinter as tk

# --- main ---

scripts = ["CPS.py", "BPS.py", "WWI.py", "WWSST.py",]

OPTIONS = ["Combined Pumping Stations", "Booster Pumping Station", "Waste Water Ionisation", "Waste Water Sludge Storage Tanks (Concrete)"]

root = tk.Tk()
root.title('Birch Forest')
root.minsize(500,200)

# --- Listbox ---

tk.Label(root, text='Element Name', bg='#00C78C').pack(fill='x')

l = tk.Listbox(root, selectmode='single')

l.pack(side="left", fill="both",expand=True)
l.insert('end', *OPTIONS)

# --- Textbox ---

def printtext():
    global e
    string = e.get()
    v = (string)
    print(v)

e = tk.Entry(root)
e.pack()
e.focus_set()

b = tk.Button(root,text='Save',command=printtext)
b.pack(side='bottom')

# --- functions ---
def on_button():

    # different examples with `curselection()`

    for idx in l.curselection():
        if OPTIONS[idx] == 'Combined Pumping Stations':
            print("Running Random Forest Simulation")
        elif OPTIONS[idx] == 'Booster Pumping Stations':
            print("Running Random Forest Simulation")
        elif OPTIONS[idx] == 'Waste Water Ionisation':
            print("Running Random Forest Simulation")
        elif OPTIONS[idx] == 'Waste Water Sludge Storage Tanks (Concrete)':
            print("Running Random Forest Simulation")

    for idx in l.curselection():
        if idx == 0:
            import CPS
        elif idx == 1:
            import BPS
        elif idx == 2:
            import WWI
        elif idx == 3:
            import WWSST

# --- Button ---

b = tk.Button(root, text='Run Simulation', bg='#76EEC6', command=on_button)
b.pack(fill = "x", side="right", expand = True)

root.mainloop()

Image 1:

Image 2:

Put simply; I would like v on line 28 to return as a variable in the variable explorer so I can call on it in script CPS when determining the yardstick value.

Body:
Essentially what you want to do is share data between the main script and some others that it imports. A good way to do this is by storing that data in a module and import`ing it into all scripts the want access to these values.

First create an empty script file, for example shared.py.

Then add an import shared to the beginning of your main script (i.e. Birchforest.py).

After that, modify the 'Save' button callback printtext() so it stores the value in a named attribute of this module:

import shared
.
.
.
# --- Textbox ---

def printtext():
    global e
    shared.v = e.get()  # Store current Entry value in shared module.

Lastly, you must do add an import shared the beginning of the scripts that are going to be imported by the main script (i.e. CPS.py, BPS.py, etc) so they can access to this shared data.

For example:

import shared

print('in CPS')
print('  shared.v:', shared.v)

... # rest of script

After doing this they will be able to access any values that the main script has put into the shared module's namespace.

This works because imported modules are cached in sys.modules, and if another script imports a module that has already be imported by some other script, the cached value is used instead of reloading and executing the named script again.

This effectively means that modules are implemented in a way that means they follow the Singleton design pattern—because they're instances of types.ModuleType class.

If you wish you can define defaults for values of the attributes, in which case shared.py would no longer be empty. Keep in mind however, that changes made to those values at runtime via assignment statements in any other module will not be persistent since the changes are only being made to in the in-memory version of the module (cached in the sys.modules list), not to the corresponding script .py file itself.

A similar idea is described in the How do I share global variables across modules? section of the online documentation.


问:
ie6 looking for missing dll's when using Java Applet
I have a problem when I use the applet tag within Internet Explorer 6.
Here is the code I use:

```<code><APPLET
    height=1024
    archive=consignation-applet-signed.jar,httpclient-4.0.1.jar,httpcore-4.0.1.jar,commons-logging-1.1.1.jar,log4j-1.2.14.jar
    width=1280
    code=PilotageImpression.class>
<PARAM NAME="_cx" VALUE="33867">
<PARAM NAME="_cy" VALUE="27093">
</APPLET>
</code>```

The problem is that it tries to reach two URL's on Microsoft's website. It's a problem when you are in a closed environment.

I read an article here: http://support.microsoft.com/kb/323207/en-us but it says that the problem is only known when using the OBJECT tag (I use Applet tag)

Does anyone know why does this occur with the applet tag?

答:
If your user has the Next Generation Plug-In (Sun's 1.6.0_10+), it would be easy to deploy this applet along with it's natives, using Java Web Start.

JWS could also launch the applet with natives on versions prior to the next generation plug-in, but they would be free-floating, outside the browser.

Body:
I have a problem when I use the applet tag within Internet Explorer 6.
Here is the code I use:

<APPLET
    height=1024
    archive=consignation-applet-signed.jar,httpclient-4.0.1.jar,httpcore-4.0.1.jar,commons-logging-1.1.1.jar,log4j-1.2.14.jar
    width=1280
    code=PilotageImpression.class>
<PARAM NAME="_cx" VALUE="33867">
<PARAM NAME="_cy" VALUE="27093">
</APPLET>

The problem is that it tries to reach two URL's on Microsoft's website. It's a problem when you are in a closed environment.

I read an article here: http://support.microsoft.com/kb/323207/en-us but it says that the problem is only known when using the OBJECT tag (I use Applet tag)

Does anyone know why does this occur with the applet tag?


问:
Algorithm to get distinct records from cartesian product
I have two tables(say, A and B). My task is to synchronise B with A, i.e. add records to B if present in A but not in B; and delete recoreds from B if present in B but not in A.

A and B can have duplicates records, such that if records are duplicates in A, B should also have duplicates. Sample data in A and B

```<code>      **Table A**                              **Table B**
    id    identifier                      id       identifier
    100   capital                         1001     bat
    201   bat                             1002     bat
    202   bat                             1003     bat
                                          5010     keyboard
</code>```

For this I have fetched records from A and B using outer join, such that my output looks like:

```<code>    A.id  B.id   identifier
    100   null    capital
    201   1001    bat
    201   1002    bat
    201   1003    bat
    202   1001    bat
    202   1002    bat
    202   1003    bat
    null  5010    keyboard
</code>```

Thus in above case, 100 and 5010 are add and delete candidates respectively, which is easy to figure out.

The issue is to find that 1003 is also a delete candidate. Since 201 and 202 are mapped to 1001 and 1002 respectively.

I can do this in database, by numbering the duplicates in database as done in
MYSQL: Avoiding cartesian product of repeating records when self-joining
But due to some restrictions, I can only load data in above format using outer join.
Therefore I need an algorithm in JAVA to do the above.
Thanks in advance.

答:
Here is how I solved this:

Fetch data from Table A and Table B.

Bucket data for Table A and Table B by the identifier, using :

```<code>    Map<String, SameBucketObject>
</code>```

where key is 'identifier' and SameBucketObject is :

```<code>    class SameBucketObject{
      private List<String> idsOfA;
      private List<String> idsOfB;
    // getter, setters, addToList statements
    }

</code>```

Basically, I grouped all elements of Table A and Table B by identifier.

In each bucket, check count of elements of A idsOfA and elements of B idsOfB, and if

```<code>    sizeOf(idsOfA) < sizeOf(idsOfB) -> add elements with ids in idsOfB List from Table B to Table A
    sizeOf(idsOfA) > sizeOf(idsOfB) -> delete sizeOf(idsOfA) - sizeOf(idsOfB) elements from A from last.
    sizeOf(idsOfA) = sizeOf(idsOfB) -> no action.
</code>```

This approach does not use extra space

Body:
I have two tables(say, A and B). My task is to synchronise B with A, i.e. add records to B if present in A but not in B; and delete recoreds from B if present in B but not in A.

A and B can have duplicates records, such that if records are duplicates in A, B should also have duplicates. Sample data in A and B

      **Table A**                              **Table B**
    id    identifier                      id       identifier
    100   capital                         1001     bat
    201   bat                             1002     bat
    202   bat                             1003     bat
                                          5010     keyboard

For this I have fetched records from A and B using outer join, such that my output looks like:

    A.id  B.id   identifier
    100   null    capital
    201   1001    bat
    201   1002    bat
    201   1003    bat
    202   1001    bat
    202   1002    bat
    202   1003    bat
    null  5010    keyboard

Thus in above case, 100 and 5010 are add and delete candidates respectively, which is easy to figure out.

The issue is to find that 1003 is also a delete candidate. Since 201 and 202 are mapped to 1001 and 1002 respectively.

I can do this in database, by numbering the duplicates in database as done in
MYSQL: Avoiding cartesian product of repeating records when self-joining
But due to some restrictions, I can only load data in above format using outer join.
Therefore I need an algorithm in JAVA to do the above.
Thanks in advance.

Body:
Here is how I solved this:

Fetch data from Table A and Table B.

Bucket data for Table A and Table B by the identifier, using :

    Map<String, SameBucketObject>

where key is 'identifier' and SameBucketObject is :

    class SameBucketObject{
      private List<String> idsOfA;
      private List<String> idsOfB;
    // getter, setters, addToList statements
    }

Basically, I grouped all elements of Table A and Table B by identifier.

In each bucket, check count of elements of A idsOfA and elements of B idsOfB, and if

    sizeOf(idsOfA) < sizeOf(idsOfB) -> add elements with ids in idsOfB List from Table B to Table A
    sizeOf(idsOfA) > sizeOf(idsOfB) -> delete sizeOf(idsOfA) - sizeOf(idsOfB) elements from A from last.
    sizeOf(idsOfA) = sizeOf(idsOfB) -> no action.

This approach does not use extra space


问:
How to create backup of one database into another database using php
I want to create backup of my website database in which is in MySQL in another database on regular basis , is it possible to do it using php

Already tried exporting database using php but requirement is something else

答:
```<code>$host_name = "localhost";
$user_name= "root";
$password= "";
$database1 = "database_name";
$database2 = "second_database_name";
$con1 = mysqli_connect($host_name ,$user_name,$password,$database1);
$con2 = mysqli_connect($host_name ,$user_name,$password,$database2);

mysqli_select_db($con1,$database1)
mysqli_select_db($con2,$database2)

$sql = "SELECT id, firstname, lastname FROM users";
$result = mysqli_query($con1, $sql);
$result1 = mysqli_query($con2, $sql);
</code>```


问:
Truncate inline HTML for Read More/Less Button
I am trying to truncate the text which is inside inline html by the length of the text (excluding html) / 2 and add read more button and reverse - add read less button and hide the half of the text. It works if the text is only raw paragraph. But when the text is inline html like below - with ol,ul,headings, it doesn't work. Can someone give a hand on this? Thank you! </p>

```<code><div class="truncate">
 <div class="toggledText" id="toggledText">
 <h1>Lorem Ipsum is simply </h1>
  <h2>Lorem Ipsum is simply </h2>
  <p><strong>Thank you for scanning. </strong></p>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five
   <ol>
    <li>Lorem Ipsum is simply </li>
    <li>Lorem Ipsum is simply. </li>
   </ol>
   <ul>
    <li>Lorem Ipsum is simply </li>
    </ul>

   var numberOfToggled = document.getElementsByClassName('toggledText');

   for(i=0; i<numberOfToggled.length; i++){

    var el = numberOfToggled[i];

  var elText = el.innerHTML.trim();
  var charLimit = elText.length / 2;

        if(elText.length > charLimit){
            var showStr = elText.slice(0,charLimit);
            var hideStr = elText.slice(charLimit);
            el.innerHTML = showStr + '<span class="morePoints">...</span> <span class="trimmed">' + hideStr + '</span>';
            el.parentElement.innerHTML = el.parentElement.innerHTML + "<div class='read-more'><a href='#' class='more'></a>";
        }

    }

    window.onclick = function(event) {
        if (event.target.className == 'more') {
    event.preventDefault();
            event.target.parentElement.parentElement.classList.toggle('showAll');
        }
    }
</code>```

答:
Make a text in a separate div which is to show and hide.Kindly check the example code snippet.

function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#more {display: none;}
</style>
</head>
<body>

<h1>Lorem Ipsum is simply </h1>
  <h2>Lorem Ipsum is simply </h2>
  <p><strong>Thank you for scanning. </strong></p>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five
<span id="dots">...</span><div id="more">
<p>
 <ol>
    <li>Lorem Ipsum is simply </li>
    <li>Lorem Ipsum is simply. </li>
   </ol>
   <ul>
    <li>Lorem Ipsum is simply </li>
    </ul></div></p>
<button onclick="myFunction()" id="myBtn">Read more</button>

</body>
</html></code>```

Body:
I am trying to truncate the text which is inside inline html by the length of the text (excluding html) / 2 and add read more button and reverse - add read less button and hide the half of the text. It works if the text is only raw paragraph. But when the text is inline html like below - with ol,ul,headings, it doesn't work. Can someone give a hand on this? Thank you!

Lorem Ipsum is simply

Lorem Ipsum is simply

Thank you for scanning.

Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five

Lorem Ipsum is simply

Lorem Ipsum is simply.

Lorem Ipsum is simply

   var numberOfToggled = document.getElementsByClassName('toggledText');

   for(i=0; i<numberOfToggled.length; i++){

    var el = numberOfToggled[i];

  var elText = el.innerHTML.trim();
  var charLimit = elText.length / 2;

        if(elText.length > charLimit){
            var showStr = elText.slice(0,charLimit);
            var hideStr = elText.slice(charLimit);
            el.innerHTML = showStr + '... ' + hideStr + '';
            el.parentElement.innerHTML = el.parentElement.innerHTML + "
";
        }

    }

    window.onclick = function(event) {
        if (event.target.className == 'more') {
    event.preventDefault();
            event.target.parentElement.parentElement.classList.toggle('showAll');
        }
    }

Body:
Make a text in a separate div which is to show and hide.Kindly check the example code snippet.

function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#more {display: none;}
</style>
</head>
<body>

<h1>Lorem Ipsum is simply </h1>
  <h2>Lorem Ipsum is simply </h2>
  <p><strong>Thank you for scanning. </strong></p>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five
<span id="dots">...</span><div id="more">
<p>
 <ol>
    <li>Lorem Ipsum is simply </li>
    <li>Lorem Ipsum is simply. </li>
   </ol>
   <ul>
    <li>Lorem Ipsum is simply </li>
    </ul></div></p>
<button onclick="myFunction()" id="myBtn">Read more</button>

</body>
</html>


问:
Vim Search/replace: what do I need to escape?
I'm trying to search and replace $data['user'] for $data['sessionUser'].

However, no matter what search string I use, I always get a "pattern not found" as the result of it.

So, what would be the correct search string? Do I need to escape any of these characters?
:%s/$data['user']/$data['sessionUser']/g

答: Here's a list of all special search characters you need to escape in Vim: `^$.*[~)+/</p>


问:
Segmentation fault error in python embedded code in C++ code of Omnet++ simple module
I want to call a Python function from C++ code in OMNeT++ simple module.

I debugged the code using gdb. It passes all lines fine, but at the end the
segmentation fault occurs after Py_Finalize();.

I found the following issue on GitHub that describes the same problem.
But it did not help me to resolve the problem.

double result=0;
// 1) Initialise python interpretator
if (!Py_IsInitialized()) {
    Py_Initialize();
        //Py_AtExit(Py_Finalize);
}
// 2) Initialise python thread mechanism
if (!PyEval_ThreadsInitialized()) {
        PyEval_InitThreads();
        assert(PyEval_ThreadsInitialized());
}

PyGILState_STATE s = PyGILState_Ensure();
PyRun_SimpleString("import sys; sys.path.append('/home/mypath/')");
PyObject *pName = PyUnicode_DecodeFSDefault((char*)"integrationTest");
PyObject* pModule = PyImport_Import(pName);

if (pModule != NULL)
{
    PyObject* pFunction = PyObject_GetAttrString(pModule, (char*)"calculateExecutionTime");
    /// changement will be held in this level Args and function result.
    PyObject* pArgs = PyTuple_Pack(2,PyFloat_FromDouble(2.0),PyFloat_FromDouble(8.0));
    PyObject* pResult = PyObject_CallObject(pFunction, pArgs);
    result = (double)PyFloat_AsDouble(pResult);
    ///////
}
// Clean up
PyGILState_Release(s);
Py_DECREF(pName);
Py_DECREF(pModule);
Py_Finalize();
```

答:
The problem occurs after the first initialization/uninitialization of python interpreter.  What happens during the OmneT++ simulation is initializing/uninitializing/re-initializing/... the Python interpreter. However, Numpy doesn't support this;

So, I resolved this problem by initializing python interpreter just one time in the beginning of the simulation in initialize() method. Then, I called Py_Finalize(); in the destructor.


问:
Making onClickListener a static method
```<code>View.OnClickListener ocl = new View.OnClickListener(){
    public void onClick(View v) {
        this.ocl_action();
    }

    public void ocl_action() {
        // TODO Auto-generated method stub
        for(int i=0; i<5;i++){                               }
            Toast.makeText(ControllerProjMain.this,"hi",Toast.LENGTH_LONG).show();
        }
    }
};
</code>```

It does not work if I just call ocl.ocl_action();

答:
First of all, pull your function outside of the onClick() method. Inside onClick() method this will not point your activity. So remove this while you are making a function call.

```<code>View.OnClickListener ocl = new View.OnClickListener(){
public void onClick(View v) {
    ocl_action();
}};

public void ocl_action() {
 // TODO Auto-generated method stub
  for(int i=0; i<5;i++){
  Toast.makeText(getApplicationContext(), "HI", Toast.LENGTH_LONG).show();
  }
}
</code>```

Title: Making onClickListener a static method

Body:
View.OnClickListener ocl = new View.OnClickListener(){
    public void onClick(View v) {
        this.ocl_action();
    }

    public void ocl_action() {
        // TODO Auto-generated method stub
        for(int i=0; i<5;i++){                               }
            Toast.makeText(ControllerProjMain.this,"hi",Toast.LENGTH_LONG).show();
        }
    }
};

It does not work if I just call ocl.ocl_action();

Body:
First of all, pull your function outside of the onClick() method. Inside onClick() method this will not point your activity. So remove this while you are making a function call.

View.OnClickListener ocl = new View.OnClickListener(){
public void onClick(View v) {
    ocl_action();
}};

public void ocl_action() {
 // TODO Auto-generated method stub
  for(int i=0; i<5;i++){
  Toast.makeText(getApplicationContext(), "HI", Toast.LENGTH_LONG).show();
  }
}


问:
How to Draw the Gaussian Blur Effect?
I need to draw the blur effect on the UIView using Objective C.

Here is my design

```<code>    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle: UIBlurEffectStyleExtraLight];

    UIVisualEffectView *contentView = [[UIVisualEffectView alloc] initWithEffect: blurEffect];

    contentView.layer.cornerRadius = 18.0;

    contentView.layer.masksToBounds = YES;

    contentView.backgroundColor = [UIColor whiteColor];

    contentView.userInteractionEnabled = NO;

    contentView.layer.shadowRadius = 10;

    contentView.layer.shadowOpacity = 0.2f;

    contentView.layer.shadowColor = [UIColor whiteColor].CGColor;

    contentView.layer.shadowOffset =  CGSizeZero;

    [contentView setFrame: annotationFrame];

    [contentView setTranslatesAutoresizingMaskIntoConstraints: YES];

    self.contentView = contentView;
</code>```

below screenshot was current output using the above code

I have tried the above code. , but I didn't get the exact blur effect
kindly suggest me to draw this design.

I have updated the below code

```<code>- (void)drawRect:(CGRect)rect {

    [super drawRect: rect]; //i doubt we need a super drarRect here…

    [self drawMarker: self.markerView fillColor: [UIColor whiteColor]];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGPathRef path = CGPathCreateWithRoundedRect(CGRectInset(rect,  self.frame.size.width/4,  self.frame.size.height/4), self.frame.size.width/8, self.frame.size.height/8, nil);

    CGContextSetFillColorWithColor(ctx,[UIColor slateColor].CGColor);

    CGContextSetShadowWithColor(ctx, CGSizeZero, self.frame.size.height/4,  [UIColor slateColor].CGColor);

    for ( int i = 0; i<=6; i++) {
        CGContextAddPath(ctx, path);
        CGContextFillPath(ctx);
    }

}
</code>```

I need the blur effect behind my view , kindly advice the me regarding this.

Thank you.

答:
Check out below reference which I used for the blur effect :

https://dzone.com/articles/applying-gaussian-blur-to-uiviews-with-swift-proto

This applies gaussian blur effect only.

Title: How to Draw the Gaussian Blur Effect?

Body:
I need to draw the blur effect on the UIView using Objective C.

Here is my design

    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle: UIBlurEffectStyleExtraLight];

    UIVisualEffectView *contentView = [[UIVisualEffectView alloc] initWithEffect: blurEffect];

    contentView.layer.cornerRadius = 18.0;

    contentView.layer.masksToBounds = YES;

    contentView.backgroundColor = [UIColor whiteColor];

    contentView.userInteractionEnabled = NO;

    contentView.layer.shadowRadius = 10;

    contentView.layer.shadowOpacity = 0.2f;

    contentView.layer.shadowColor = [UIColor whiteColor].CGColor;

    contentView.layer.shadowOffset =  CGSizeZero;

    [contentView setFrame: annotationFrame];

    [contentView setTranslatesAutoresizingMaskIntoConstraints: YES];

    self.contentView = contentView;

below screenshot was current output using the above code

I have tried the above code. , but I didn't get the exact blur effect
kindly suggest me to draw this design.

I have updated the below code

- (void)drawRect:(CGRect)rect {

    [super drawRect: rect]; //i doubt we need a super drarRect here…

    [self drawMarker: self.markerView fillColor: [UIColor whiteColor]];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGPathRef path = CGPathCreateWithRoundedRect(CGRectInset(rect,  self.frame.size.width/4,  self.frame.size.height/4), self.frame.size.width/8, self.frame.size.height/8, nil);

    CGContextSetFillColorWithColor(ctx,[UIColor slateColor].CGColor);

    CGContextSetShadowWithColor(ctx, CGSizeZero, self.frame.size.height/4,  [UIColor slateColor].CGColor);

    for ( int i = 0; i<=6; i++) {
        CGContextAddPath(ctx, path);
        CGContextFillPath(ctx);
    }

}

I need the blur effect behind my view , kindly advice the me regarding this.

Thank you.