问:
Pattern matching using regex for messy file names
I do not have very much experience with REs, but need to parse 100s of file names to generate a 'metadata' data set. I have been able to generate text files that include the file paths and the file name. It is simple for me to parse out the complete file name, but I need to be able to parse out the "sample ID" from the file name.

The issue is that the syntax of the "sample IDs" is all over the place (See attached csv for example data: The goal is to go from the 'sample' column to the 'ID' column). I have tried a series of strsplit() commands, but this is very cumbersome, and is not functional in nature. I have also tried writing a function with a number of IF statements based on syntax structure. I feel like this is still not a good solution because it is still dependent on me manually identifying the different syntax before hand, and I could easily miss something since I have to do this by eye.

It seems to me that this is a regex problem, but I could use some resources to help me get started. I would like to be able to do this in either R or Python if possible. Thank you for any resources, or packages/modules that may be useful.

```<code>dput(head(brain_ref, 25))
structure(list(file = c("/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_2_brain_total_RNA_cDNA_CAGATC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_1_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_2_brain_total_RNA_cDNA_GTGAAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_1_brain_total_RNA_cDNA_CCGTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_2_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_2_brain_total_RNA_cDNA_CTTGTA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_1_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_1_brain_total_RNA_cDNA_CGATGT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_2_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_1_brain_total_RNA_cDNA_ACAGTG.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_1_brain_total_RNA_cDNA_GCCAAT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_2_brain_total_RNA_cDNA_TGACCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/ACI-SegHsd-2-brain-total-RNA_S17.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH2-3-brain-total-RNA_S4.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH5-3-brain-total-RNA_S3.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH8-3-brain-total-RNA_S5.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Cop-CrCrl-2-brain-total-RNA_S10.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-1-brain-total-RNA_S16.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-2-brain-total-RNA_S13.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-1-brain-total-RNA_S18.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-2-brain-total-RNA_S15.genes.results"
), sample = c("BXH12_1_brain_total_RNA_cDNA_GTCCGC", "BXH12_2_brain_total_RNA_cDNA_CAGATC",
"HXB13_1_brain_total_RNA_cDNA_ATGTCA", "HXB13_2_brain_total_RNA_cDNA_GTGAAA",
"HXB17_1_brain_total_RNA_cDNA_CCGTCC", "HXB17_2_brain_total_RNA_cDNA_ATGTCA",
"HXB2_1_brain_total_RNA_cDNA_GTCCGC", "HXB2_2_brain_total_RNA_cDNA_CTTGTA",
"HXB25_1_brain_total_RNA_cDNA_AGTTCC", "HXB25_2_brain_total_RNA_cDNA_AGTCAA",
"HXB27_1_brain_total_RNA_cDNA_CGATGT", "HXB27_2_brain_total_RNA_cDNA_AGTTCC",
"HXB7_1_brain_total_RNA_cDNA_ACAGTG", "HXB7_2_brain_total_RNA_cDNA_AGTCAA",
"SHR_1_brain_total_RNA_cDNA_GCCAAT", "SHR_2_brain_total_RNA_cDNA_TGACCA",
"ACI-SegHsd-2-brain-total-RNA_S17", "BXH2-3-brain-total-RNA_S4",
"BXH5-3-brain-total-RNA_S3", "BXH8-3-brain-total-RNA_S5", "Cop-CrCrl-2-brain-total-RNA_S10",
"Dark-Agouti-1-brain-total-RNA_S16", "Dark-Agouti-2-brain-total-RNA_S13",
"F344-NCI-1-brain-total-RNA_S18", "F344-NCI-2-brain-total-RNA_S15"
), batch = c("batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch10", "batch10",
"batch10", "batch10", "batch10", "batch10", "batch10", "batch10",
"batch10"), ID = c("BXH12_1", "BXH12_2", "HXB13_1", "HXB13_2",
"HXB17_1", "HXB17_2", "HXB2_1", "HXB2_2", "HXB25_1", "HXB25_2",
"HXB27_1", "HXB27_2", "HXB7_1", "HXB7_2", "SHR_1", "SHR_2", "ACI-SegHsd_2",
"BXH2_3", "BXH5_3", "BXH8_3", "Cop-CrCrl_2", "Dark-Agouti_1",
"Dark-Agouti_2", "F344-NCI_1", "F344-NCI_2")), row.names = c(NA,
25L), class = "data.frame")
</code>```

答:
Inspired in @r2evans comment:</p>

```<code>samples <- c("SHR_1_brain_total_RNA_cDNA_GCCAAT", "SHR-1-brain-total-RNA_S6")
sub("[_-]([0-9]+)[_-]*brain.*", "_\\1", samples)
#[1] "SHR_1" "SHR_1"
</code>```

Body:
I do not have very much experience with REs, but need to parse 100s of file names to generate a 'metadata' data set. I have been able to generate text files that include the file paths and the file name. It is simple for me to parse out the complete file name, but I need to be able to parse out the "sample ID" from the file name.

The issue is that the syntax of the "sample IDs" is all over the place (See attached csv for example data: The goal is to go from the 'sample' column to the 'ID' column). I have tried a series of strsplit() commands, but this is very cumbersome, and is not functional in nature. I have also tried writing a function with a number of IF statements based on syntax structure. I feel like this is still not a good solution because it is still dependent on me manually identifying the different syntax before hand, and I could easily miss something since I have to do this by eye.

It seems to me that this is a regex problem, but I could use some resources to help me get started. I would like to be able to do this in either R or Python if possible. Thank you for any resources, or packages/modules that may be useful.

dput(head(brain_ref, 25))
structure(list(file = c("/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_2_brain_total_RNA_cDNA_CAGATC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_1_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_2_brain_total_RNA_cDNA_GTGAAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_1_brain_total_RNA_cDNA_CCGTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_2_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_2_brain_total_RNA_cDNA_CTTGTA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_1_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_1_brain_total_RNA_cDNA_CGATGT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_2_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_1_brain_total_RNA_cDNA_ACAGTG.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_1_brain_total_RNA_cDNA_GCCAAT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_2_brain_total_RNA_cDNA_TGACCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/ACI-SegHsd-2-brain-total-RNA_S17.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH2-3-brain-total-RNA_S4.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH5-3-brain-total-RNA_S3.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH8-3-brain-total-RNA_S5.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Cop-CrCrl-2-brain-total-RNA_S10.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-1-brain-total-RNA_S16.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-2-brain-total-RNA_S13.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-1-brain-total-RNA_S18.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-2-brain-total-RNA_S15.genes.results"
), sample = c("BXH12_1_brain_total_RNA_cDNA_GTCCGC", "BXH12_2_brain_total_RNA_cDNA_CAGATC",
"HXB13_1_brain_total_RNA_cDNA_ATGTCA", "HXB13_2_brain_total_RNA_cDNA_GTGAAA",
"HXB17_1_brain_total_RNA_cDNA_CCGTCC", "HXB17_2_brain_total_RNA_cDNA_ATGTCA",
"HXB2_1_brain_total_RNA_cDNA_GTCCGC", "HXB2_2_brain_total_RNA_cDNA_CTTGTA",
"HXB25_1_brain_total_RNA_cDNA_AGTTCC", "HXB25_2_brain_total_RNA_cDNA_AGTCAA",
"HXB27_1_brain_total_RNA_cDNA_CGATGT", "HXB27_2_brain_total_RNA_cDNA_AGTTCC",
"HXB7_1_brain_total_RNA_cDNA_ACAGTG", "HXB7_2_brain_total_RNA_cDNA_AGTCAA",
"SHR_1_brain_total_RNA_cDNA_GCCAAT", "SHR_2_brain_total_RNA_cDNA_TGACCA",
"ACI-SegHsd-2-brain-total-RNA_S17", "BXH2-3-brain-total-RNA_S4",
"BXH5-3-brain-total-RNA_S3", "BXH8-3-brain-total-RNA_S5", "Cop-CrCrl-2-brain-total-RNA_S10",
"Dark-Agouti-1-brain-total-RNA_S16", "Dark-Agouti-2-brain-total-RNA_S13",
"F344-NCI-1-brain-total-RNA_S18", "F344-NCI-2-brain-total-RNA_S15"
), batch = c("batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch10", "batch10",
"batch10", "batch10", "batch10", "batch10", "batch10", "batch10",
"batch10"), ID = c("BXH12_1", "BXH12_2", "HXB13_1", "HXB13_2",
"HXB17_1", "HXB17_2", "HXB2_1", "HXB2_2", "HXB25_1", "HXB25_2",
"HXB27_1", "HXB27_2", "HXB7_1", "HXB7_2", "SHR_1", "SHR_2", "ACI-SegHsd_2",
"BXH2_3", "BXH5_3", "BXH8_3", "Cop-CrCrl_2", "Dark-Agouti_1",
"Dark-Agouti_2", "F344-NCI_1", "F344-NCI_2")), row.names = c(NA,
25L), class = "data.frame")

Body:
Inspired in @r2evans comment:

samples <- c("SHR_1_brain_total_RNA_cDNA_GCCAAT", "SHR-1-brain-total-RNA_S6")
sub("[_-]([0-9]+)[_-]*brain.*", "_\\1", samples)
#[1] "SHR_1" "SHR_1"


来源: stackexchange

问:
How to properly convert string to std::chrono::system_clock::time_point?
I have followed some good answers to similar questions like this one.

Yet my code seems to give output one hour later after converting string to time_point and back to string.

The code that gives the wrong answer:

```<code>#include <string>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

using date_time = std::chrono::system_clock::time_point;

std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string &s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}

int main() {
    std::string birthday = "2000-06-05 20:20:00";
    std::cout << "Two birthday dates: \n" << birthday << " \nsecond one:\n" << dateTimeToString(stringToDateTime(birthday))
              << "\n******************\n";
    return 0;
}
</code>```

And the output:

Two birthday dates:
  2000-06-05 20:20:00
  second one:
  2000-06-05 21:20:00

I have thought that this has something to do with timezones, but I am unable to solve this problem. What is wrong with my code?

答:
Not sure it helps but works for me. Add the UTC offset and TZ info (%z and %Z) in both steps:

```<code>std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S%z %Z", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string& s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S%z %Z");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have followed some good answers to similar questions like this one.

Yet my code seems to give output one hour later after converting string to time_point and back to string.

The code that gives the wrong answer:

#include <string>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

using date_time = std::chrono::system_clock::time_point;

std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string &s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}

int main() {
    std::string birthday = "2000-06-05 20:20:00";
    std::cout << "Two birthday dates: \n" << birthday << " \nsecond one:\n" << dateTimeToString(stringToDateTime(birthday))
              << "\n******************\n";
    return 0;
}

And the output:

Two birthday dates:
  2000-06-05 20:20:00
  second one:
  2000-06-05 21:20:00

I have thought that this has something to do with timezones, but I am unable to solve this problem. What is wrong with my code?

Body:
Not sure it helps but works for me. Add the UTC offset and TZ info (%z and %Z) in both steps:

std::string dateTimeToString(date_time time) {
    std::time_t now_c = std::chrono::system_clock::to_time_t(time);
    auto tm = std::localtime(&now_c);
    char buffer[32];
    std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S%z %Z", tm);
    return std::string(buffer);
}

date_time stringToDateTime(const std::string& s) {
    std::tm timeDate = {};
    std::istringstream ss(s);
    ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S%z %Z");
    return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}


问:
In Vue JS, how can I make my APIService.js class globally available to components without requiring individual components to import it?
Almost all of my components require some kind of interaction with my apiservice.js class, which imports Axios and makes appropriate http requests depending on the method called. I know this isn't normally recommended, but, in every one of my components, I have the following:

```<code>import {APIService} from '../store/APIService.js';
const apiService = new APIService();
</code>```

My APIService.js looks roughly like this (trimmed down for simplicity):

```<code>import axios from 'axios';
const API_URL = 'http://myserver:82/services/locationmanagement';

export class APIService{

constructor(){
}

getLocations() {
    const url = `${API_URL}/api/locations/`;
    return axios.get(url).then(response => response.data);
}

saveLocation(location) {
    let url = `${API_URL}/api/locations/`;
    let id = location.id;
    let httpMethod = 'post';

    if(id > 0 ) {
        httpMethod = 'put';
        url = `${API_URL}/api/locations/${id}`;
    }

    let options = {
        method: httpMethod,
        url: url,
        headers: { 'Content-Type': 'application/json' },
        data: location
    }

    return axios(options);
   }

}
</code>```

I would prefer if this were somehow made available to the global Vue instance and my components could access it somehow.

I believe this needs to be implemented in some form within my main.js file, possibly via Vue.use, but I'm still unsure of how to implement this even after reviewing the docs.

Any input would be greatly appreciated. Thanks!

答:
Create a Vuejs Plugin import it into main.js, and call it there with Vue.use(myservice)

EDIT:

Per comment, one way is to add the plugin to the Vue prototype. For example, an axios wrapper could be defined as

```<code>import axios from 'axios'

export default {

  install:function(Vue,options) {

    Vue.prototype.$dataservice = axios.create({...})
    ...
</code>```

then it can be called from a component like other global vue functions, e.g., $refs, $set, $emit:

```<code> ...
 this.$dataservice.get(...)
 // or
 this.$dataservice.post(...)
 ...
</code>```

With a data service api, if using Vuex, it may be useful to use this primarily in "actions".

Body:
Almost all of my components require some kind of interaction with my apiservice.js class, which imports Axios and makes appropriate http requests depending on the method called. I know this isn't normally recommended, but, in every one of my components, I have the following:

import {APIService} from '../store/APIService.js';
const apiService = new APIService();

My APIService.js looks roughly like this (trimmed down for simplicity):

import axios from 'axios';
const API_URL = 'http://myserver:82/services/locationmanagement';

export class APIService{

constructor(){
}

getLocations() {
    const url = `${API_URL}/api/locations/`;
    return axios.get(url).then(response => response.data);
}

saveLocation(location) {
    let url = `${API_URL}/api/locations/`;
    let id = location.id;
    let httpMethod = 'post';

    if(id > 0 ) {
        httpMethod = 'put';
        url = `${API_URL}/api/locations/${id}`;
    }

    let options = {
        method: httpMethod,
        url: url,
        headers: { 'Content-Type': 'application/json' },
        data: location
    }

    return axios(options);
   }

}

I would prefer if this were somehow made available to the global Vue instance and my components could access it somehow.

I believe this needs to be implemented in some form within my main.js file, possibly via Vue.use, but I'm still unsure of how to implement this even after reviewing the docs.

Any input would be greatly appreciated. Thanks!

Body:
Create a Vuejs Plugin import it into main.js, and call it there with Vue.use(myservice)

EDIT:

Per comment, one way is to add the plugin to the Vue prototype. For example, an axios wrapper could be defined as

import axios from 'axios'

export default {

  install:function(Vue,options) {

    Vue.prototype.$dataservice = axios.create({...})
    ...

then it can be called from a component like other global vue functions, e.g., $refs, $set, $emit:

 ...
 this.$dataservice.get(...)
 // or
 this.$dataservice.post(...)
 ...

With a data service api, if using Vuex, it may be useful to use this primarily in "actions".


问:
UITextfield leftView/rightView padding on iOS7
The leftView and rightView views of an UITextField on iOS7 are really close to the textfield border.

How may I add some (horizontal) padding to those items?

I tried modifying the frame, but did not work

```<code>uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
textField.leftView = iconImageView;
</code>```

Please, note that I'm not interested in adding padding to the textfield's text, like this Set padding for UITextField with UITextBorderStyleNone

答:
I realize this an old post and this answer is a bit specific to my use case, but I posted it in case others are seeking a similar solution. I want to move a UITextField's leftView or rightView but I am not putting images in them and do not want any hard coded constants.

My UI calls for hiding the text field's clear button and displaying a UIActivityIndicatorView where the clear button was located.

I add a spinner to the rightView, but out of the box (on iOS 13) it is shifted 20 pixels to the right of the clearButton. I don't like to use magic numbers since the position of the clearButton and rightView are subject to change at any time by Apple. The UI design intent is "spinner where the clear button is" so my solution was to subclass UITextField and override rightViewRect(forBounds).

```<code>override func rightViewRect(forBounds bounds: CGRect) -> CGRect {

    // Use clearButton's rectangle
    return self.clearButtonRect(forBounds: bounds)
}
</code>```

Below is a working example (sans Storyboard):

```<code>//------------------------------------------------------------------------------
class myCustomTextField: UITextField {

    override func rightViewRect(forBounds bounds: CGRect) -> CGRect {

        // Use clearButton rectangle
        return self.clearButtonRect(forBounds: bounds)
    }
}

//------------------------------------------------------------------------------
class myViewController: UIViewController {

    var activityView: UIActivityIndicatorView = {
        let activity = UIActivityIndicatorView()
        activity.startAnimating()
        return activity
    }()

    @IBOutlet weak var searchTextField: myCustomTextField!

    //------------------------------------------------------------------------------
    // MARK: - Lifecycle
    //------------------------------------------------------------------------------
    override func viewDidLoad() {

        super.viewDidLoad()

        searchTextField.rightView = activityView
        searchTextField.rightViewMode = .never // Hide spinner
        searchTextField.clearButtonMode = .never // Hide clear button

        setupUIForTextEntry()
    }

    // ...
    // More code to switch between user text entry and "search progress"
    // by calling setupUI... functions below
    // ...

    //------------------------------------------------------------------------------
    // MARK: - UI
    //------------------------------------------------------------------------------
    func setupUIForTextEntry() {

        // Hide spinner
        searchTextField.rightViewMode = .never

        // Show clear button
        searchTextField.clearButtonMode = .whileEditing
        searchTextField.becomeFirstResponder()
    }

    //------------------------------------------------------------------------------
    func setupUIForSearching() {

        // Show spinner
        searchTextField.rightViewMode = .always

        // Hide clear button
        searchTextField.clearButtonMode = .never
        searchTextField.resignFirstResponder()
    }

    //------------------------------------------------------------------------------

}

//------------------------------------------------------------------------------
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The leftView and rightView views of an UITextField on iOS7 are really close to the textfield border.

How may I add some (horizontal) padding to those items?

I tried modifying the frame, but did not work

uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
textField.leftView = iconImageView;

Please, note that I'm not interested in adding padding to the textfield's text, like this Set padding for UITextField with UITextBorderStyleNone

Body:
I realize this an old post and this answer is a bit specific to my use case, but I posted it in case others are seeking a similar solution. I want to move a UITextField's leftView or rightView but I am not putting images in them and do not want any hard coded constants.

My UI calls for hiding the text field's clear button and displaying a UIActivityIndicatorView where the clear button was located.

I add a spinner to the rightView, but out of the box (on iOS 13) it is shifted 20 pixels to the right of the clearButton. I don't like to use magic numbers since the position of the clearButton and rightView are subject to change at any time by Apple. The UI design intent is "spinner where the clear button is" so my solution was to subclass UITextField and override rightViewRect(forBounds).

override func rightViewRect(forBounds bounds: CGRect) -> CGRect {

    // Use clearButton's rectangle
    return self.clearButtonRect(forBounds: bounds)
}

Below is a working example (sans Storyboard):

//------------------------------------------------------------------------------
class myCustomTextField: UITextField {

    override func rightViewRect(forBounds bounds: CGRect) -> CGRect {

        // Use clearButton rectangle
        return self.clearButtonRect(forBounds: bounds)
    }
}

//------------------------------------------------------------------------------
class myViewController: UIViewController {

    var activityView: UIActivityIndicatorView = {
        let activity = UIActivityIndicatorView()
        activity.startAnimating()
        return activity
    }()

    @IBOutlet weak var searchTextField: myCustomTextField!

    //------------------------------------------------------------------------------
    // MARK: - Lifecycle
    //------------------------------------------------------------------------------
    override func viewDidLoad() {

        super.viewDidLoad()

        searchTextField.rightView = activityView
        searchTextField.rightViewMode = .never // Hide spinner
        searchTextField.clearButtonMode = .never // Hide clear button

        setupUIForTextEntry()
    }

    // ...
    // More code to switch between user text entry and "search progress"
    // by calling setupUI... functions below
    // ...

    //------------------------------------------------------------------------------
    // MARK: - UI
    //------------------------------------------------------------------------------
    func setupUIForTextEntry() {

        // Hide spinner
        searchTextField.rightViewMode = .never

        // Show clear button
        searchTextField.clearButtonMode = .whileEditing
        searchTextField.becomeFirstResponder()
    }

    //------------------------------------------------------------------------------
    func setupUIForSearching() {

        // Show spinner
        searchTextField.rightViewMode = .always

        // Hide clear button
        searchTextField.clearButtonMode = .never
        searchTextField.resignFirstResponder()
    }

    //------------------------------------------------------------------------------

}

//------------------------------------------------------------------------------


问:
How to toggle div's on and of on a daily basis?
I am currently working on a project, my employer wants to change his daily offer every day in a week, now I have tried to get my 7 div's in js and turn them on and off whit if statements ex:

```<code>var day = new Date().get Day()
if(day == 5){
div.style.display = "block";
//all the other div's would be display none//
</code>```

I tried searching for a similar problem online but there is no solution.
I hope I clearly explained the problem. keep in mind that I am currently a beginner in js and i would love to hear out a more simpler solution.

答:
Below code will display offer div based on today's day.

I have used jQuery to keep the script short and simple.

ask if you don't get any part.

Edited: Added one more easy solution without jQuery

```<code>// Solution without jQuery.
// get div for all days. It gives you an array of div
var allDaysDiv = document.getElementsByClassName('weekDay');

// hide all div
allDaysDiv[0].style.display = 'none';
allDaysDiv[1].style.display = 'none';
allDaysDiv[2].style.display = 'none';
allDaysDiv[3].style.display = 'none';
allDaysDiv[4].style.display = 'none';
allDaysDiv[5].style.display = 'none';
allDaysDiv[6].style.display = 'none';

// get numeric for today
var day = new Date().getDay();

// display today's div
document.getElementById(day).style.display = 'block';
</code>```

$(document).ready(function(){
  $(".weekDay").hide(); // hide all div with class as 'weekDay'
  var day = new Date().getDay();  // get numeric for today, 0-6 for sunday to saturday
  $("#"+day).show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
  <div class="weekDay" id="0">  Sunday Offer</div>
  <div class="weekDay" id="1">  Monday Offer</div>
  <div class="weekDay" id="2">  Tuesday Offer</div>
  <div class="weekDay" id="3">  Wednesday Offer</div>
  <div class="weekDay" id="4">  Thursday Offer</div>
  <div class="weekDay" id="5">  Friday Offer</div>
  <div class="weekDay" id="6">  Saturday Offer</div>
</body>
</html></code>```

Body:
I am currently working on a project, my employer wants to change his daily offer every day in a week, now I have tried to get my 7 div's in js and turn them on and off whit if statements ex:

var day = new Date().get Day()
if(day == 5){
div.style.display = "block";
//all the other div's would be display none//

I tried searching for a similar problem online but there is no solution.
I hope I clearly explained the problem. keep in mind that I am currently a beginner in js and i would love to hear out a more simpler solution.

Body:
Below code will display offer div based on today's day.

I have used jQuery to keep the script short and simple.

ask if you don't get any part.

Edited: Added one more easy solution without jQuery

// Solution without jQuery.
// get div for all days. It gives you an array of div
var allDaysDiv = document.getElementsByClassName('weekDay');

// hide all div
allDaysDiv[0].style.display = 'none';
allDaysDiv[1].style.display = 'none';
allDaysDiv[2].style.display = 'none';
allDaysDiv[3].style.display = 'none';
allDaysDiv[4].style.display = 'none';
allDaysDiv[5].style.display = 'none';
allDaysDiv[6].style.display = 'none';

// get numeric for today
var day = new Date().getDay();

// display today's div
document.getElementById(day).style.display = 'block';

$(document).ready(function(){
  $(".weekDay").hide(); // hide all div with class as 'weekDay'
  var day = new Date().getDay();  // get numeric for today, 0-6 for sunday to saturday
  $("#"+day).show();
});

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
  <div class="weekDay" id="0">  Sunday Offer</div>
  <div class="weekDay" id="1">  Monday Offer</div>
  <div class="weekDay" id="2">  Tuesday Offer</div>
  <div class="weekDay" id="3">  Wednesday Offer</div>
  <div class="weekDay" id="4">  Thursday Offer</div>
  <div class="weekDay" id="5">  Friday Offer</div>
  <div class="weekDay" id="6">  Saturday Offer</div>
</body>
</html>


问:
How to separate HTML and Javascript
I am styding JS right now.
I need to get the HTML and JS as many as possible getting seperated.
So that everything is in a HTML and a loose JS file.
How do I seperate this:

   <!DOCTYPE html>

        <title>Inzendopgave 242S2 - F.W.J.C. de Graaff

        </title>

Inzendopgave 242S2 - F.W.J.C. de Graaff

Voer uw bedragen in:

    <input type="text" id="invoer1">

Uw ingevoerde totaal:

0

```

When I place everything that is inside the script-tags and save that to a seperate js-file, the event-listener doesn't work anymore... Well is it possible at all to separate it?

Greetings,
--Tech

答:
When you use inline javascript the document is rendering so if you reference an element by ID that existed before the script tag the element has likely already been registered which is why you can attach an event listener to it.  When you link an external javascript file it will typically be loaded before the document is rendered and therefore the element doesn't exist yet.  To resolve this problem simply have your code which attaches event listeners to the document elements run after the document has loaded.

See related issue: best way of unobtrusive onload in plain javascript

Title: How to separate HTML and Javascript

Body:
I am styding JS right now.
I need to get the HTML and JS as many as possible getting seperated.
So that everything is in a HTML and a loose JS file.
How do I seperate this:

   <!DOCTYPE html>

        <title>Inzendopgave 242S2 - F.W.J.C. de Graaff

        </title>

Inzendopgave 242S2 - F.W.J.C. de Graaff

Voer uw bedragen in:

    <input type="text" id="invoer1">

Uw ingevoerde totaal:

0

When I place everything that is inside the script-tags and save that to a seperate js-file, the event-listener doesn't work anymore... Well is it possible at all to separate it?

Greetings,
--Tech


问:
How do I get a GameObject to rotate and face away from a MouseClick location in Unity?
So in my Unity exercise, I have to rotate a GameObject to face away from where I clicked my mouse. Also, I can only rotate around the Y-axis i.e. the GameObject is only allowed to rotate either purely to the right or purely to the left, and cannot tip towards the ground at any point. Also, I've got to do this without RayCasting (I've already done it WITH RayCasting, so as an exercise, I've got to do it without). Here's the code I've written after multiple attempts but it doesn't seem to be effective enough:

```<code>Vector3 clickLocation = Input.mousePosition;
Vector3 clickWorldLocation = Camera.main.ScreenToWorldPoint(new Vector3(clickLocation.x, clickLocation.y, transform.position.x)); //the transform.position.x is just to add some depth
transform.LookAt(new Vector3(clickWorldLocation.x, transform.position.y, clickWorldLocation.z), Vector3.up);
</code>```

This code works fine if my GameObject remains in its starting position, but fails if I move it to another location and attempt the same action. Could someone help me out please?

答:
First, call Camera.main as infrequently as you can, as it uses an expensive operation (FindGameObjectsWithTag) and doesn't cache the result.

```<code>private Camera mainCamera;
void Awake()
{
    mainCamera = Camera.main;
}
</code>```

To answer your question, don't use ScreenToWorldPoint in this situation, because a depth isn't most easily calculated. You don't have anything meaningful to use for the z component, and transform.position.x makes no sense here.

Instead, create a Plane that you want to click into (such as the plane parallel to the view plane and intersecting the object), use ScreenPointToRay to turn the mouse position into a Ray, then find where the ray and plane intersect. Plane.Raycast is much, much faster than a physics raycast.  Then, find the direction from the mouse world position to the object, and use Quaternion.LookRotation to turn that direction into a rotation you can assign to the object's rotation:

```<code>Ray mouseRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane mousePlane = new Plane(mainCamera.transform.forward, transform.position);
float rayDistance;
if (mousePlane.Raycast(mouseRay, out rayDistance))
{
    Vector3 mouseWorldPos = mouseRay.GetPoint(rayDistance);

    // make the z component of mouseWorldPos the same as transform.position
    mouseWorldPos.z = transform.position.z;

    Vector3 awayFromMouseDir = transform.position - mouseWorldPos;

    transform.rotation = Quaternion.LookRotation(awayFromMouseDir, Vector3.up);
}
</code>```

Body:
So in my Unity exercise, I have to rotate a GameObject to face away from where I clicked my mouse. Also, I can only rotate around the Y-axis i.e. the GameObject is only allowed to rotate either purely to the right or purely to the left, and cannot tip towards the ground at any point. Also, I've got to do this without RayCasting (I've already done it WITH RayCasting, so as an exercise, I've got to do it without). Here's the code I've written after multiple attempts but it doesn't seem to be effective enough:

Vector3 clickLocation = Input.mousePosition;
Vector3 clickWorldLocation = Camera.main.ScreenToWorldPoint(new Vector3(clickLocation.x, clickLocation.y, transform.position.x)); //the transform.position.x is just to add some depth
transform.LookAt(new Vector3(clickWorldLocation.x, transform.position.y, clickWorldLocation.z), Vector3.up);

This code works fine if my GameObject remains in its starting position, but fails if I move it to another location and attempt the same action. Could someone help me out please?

Body:
First, call Camera.main as infrequently as you can, as it uses an expensive operation (FindGameObjectsWithTag) and doesn't cache the result.

private Camera mainCamera;
void Awake()
{
    mainCamera = Camera.main;
}

To answer your question, don't use ScreenToWorldPoint in this situation, because a depth isn't most easily calculated. You don't have anything meaningful to use for the z component, and transform.position.x makes no sense here.

Instead, create a Plane that you want to click into (such as the plane parallel to the view plane and intersecting the object), use ScreenPointToRay to turn the mouse position into a Ray, then find where the ray and plane intersect. Plane.Raycast is much, much faster than a physics raycast.  Then, find the direction from the mouse world position to the object, and use Quaternion.LookRotation to turn that direction into a rotation you can assign to the object's rotation:

Ray mouseRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane mousePlane = new Plane(mainCamera.transform.forward, transform.position);
float rayDistance;
if (mousePlane.Raycast(mouseRay, out rayDistance))
{
    Vector3 mouseWorldPos = mouseRay.GetPoint(rayDistance);

    // make the z component of mouseWorldPos the same as transform.position
    mouseWorldPos.z = transform.position.z;

    Vector3 awayFromMouseDir = transform.position - mouseWorldPos;

    transform.rotation = Quaternion.LookRotation(awayFromMouseDir, Vector3.up);
}


问:
How to zip each element from a 1D array with the elements from each row of a 2D array?
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

```<code>x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
</code>```

Into:

```<code>r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

Body:
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

Into:

r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

Body:
A variation on your repeat and reshape approach:

In [89]: x = [1, 2, 3]
    ...: y = [[4, 5], [6, 7], [8, 9]]
In [90]: res = np.zeros((3,2,2),int)
In [91]: res[:,:,1]=y
In [92]: res[:,:,0]=np.array(x)[:,None]
In [93]: res
Out[93]:
array([[[1, 4],
        [1, 5]],

       [[2, 6],
        [2, 7]],

       [[3, 8],
        [3, 9]]])
In [94]: res.reshape(6,2)
Out[94]:
array([[1, 4],
       [1, 5],
       [2, 6],
       [2, 7],
       [3, 8],
       [3, 9]])

It's using broadcasting to map the x and y onto the res array.


问:
image border not displaying html email
I am trying to send an html email with an image border as

```<code><p align="center">
    <img src="images/pic1.jpg" width="443" height="148" align="middle"
         style="border: 1px solid grey; padding:10px;" border="1"/>
</p>
</code>```

However, the border just does not display in any of the email clients. How can i fix this?

答:
According to this: http://www.campaignmonitor.com/css/ border should be working properly.

I would try two things:

First add the following to the image, which will also help with Gmail rendering bugs

```<code>display:block;
</code>```

And also, maybe try:

```<code>border-top: 1px solid gray;
border-right: 1px solid gray;
border-bottom: 1px solid gray;
border-left: 1px solid gray;
</code>```

Title: image border not displaying html email

Body:
I am trying to send an html email with an image border as

However, the border just does not display in any of the email clients. How can i fix this?

Body:
According to this: http://www.campaignmonitor.com/css/ border should be working properly.

I would try two things:

First add the following to the image, which will also help with Gmail rendering bugs

display:block;

And also, maybe try:

border-top: 1px solid gray;
border-right: 1px solid gray;
border-bottom: 1px solid gray;
border-left: 1px solid gray;


问:
Batch check if mapped network drive exists
I'm currently writing a script that should map a network drive to the letter Z , i'm using the command
net use z: \\path , the thing is that if the user is already using this letter i won't be able to map it, is there any way to check the existense of this drive (z) and if it exists to unmount it and mount it to a different letter and still use the z drive which i need for my script, this is a part of an installation, and it should be on Z drive.

答:
My requirements were slightly different than the OP's: I needed to map a network drive, always to the same path, but only if it didn't exist already</p>

```<code>if not exist z:\ (
    net use z: \\ComputerName\ShareName
)
</code>```

Body:
My requirements were slightly different than the OP's: I needed to map a network drive, always to the same path, but only if it didn't exist already

if not exist z:\ (
    net use z: \\ComputerName\ShareName
)


问:
Run kafka producer with a fixed/static list of brokers
Usually the kafka java client (used within Spring boot, but that does not really matter here, I think, just as a side node) uses the boostrap.servers config (which expects a list of broker addresses:port) to establish an initial connection. Afterwards, a metadata request is used to discover all members of the cluster, which are currently registered.

My question now is, how this discovery can be disabled in the java client. I want to have the KafkaProducer use the list of brokers I supply to it as a fixed, static one.

A little bit more background

The platform my Spring application is deployed to, does not allow internet access to any port, except when using an HTTP proxy (443 or 80). The other alternative is to use a TCP proxy, which works similar to this:

The proxy provides a hostname and port an application can connect to

Once connected, the data stream is forwarded to the previously (during the creation of the proxy) named hostname and port

In that way, the platform can control what traffic is coming from who and is going where, which is a security requirement in my organisation. The communication path then looks like:

```<code>----------------------         -------------         -----------------------
| Application client |  <--->  | TCP Proxy |  <--->  | Target (e.g. kafka) |
----------------------         -------------         -----------------------
</code>```

However, this method does not really work with the public kafka cluster I need to talk to, as the kafka broker in the boostrap.servers list (which I can connect to perfectly fine) will return the list of nodes with the public endpoint names I can not connect to (as they're not going through the proxy).

So, instead of using the discovery functionality of the Kafka client, I would like to use a fixed, pre-defined list of brokers, which I can setup to use the TCP proxy. However, I didn't see any solution for that in the API so far and hope for some help here.

I'm aware, that not using this functionality makes it impossible for the application to use the dynamic changes of the kafka cluster state (when a broker goes away and another one is spinned up), however, this is ok in my scenario and all given circumstances.

答:
While there is not a way to not use Metadata requests, you might consider the advertised.listeners config, which will let your internal-network brokers advertise the hostname and port you have configured on the proxy for that particular broker, in responses to the Metadata request.

More details can be found here

Body:
Usually the kafka java client (used within Spring boot, but that does not really matter here, I think, just as a side node) uses the boostrap.servers config (which expects a list of broker addresses:port) to establish an initial connection. Afterwards, a metadata request is used to discover all members of the cluster, which are currently registered.

My question now is, how this discovery can be disabled in the java client. I want to have the KafkaProducer use the list of brokers I supply to it as a fixed, static one.

A little bit more background

The platform my Spring application is deployed to, does not allow internet access to any port, except when using an HTTP proxy (443 or 80). The other alternative is to use a TCP proxy, which works similar to this:

The proxy provides a hostname and port an application can connect to

Once connected, the data stream is forwarded to the previously (during the creation of the proxy) named hostname and port

In that way, the platform can control what traffic is coming from who and is going where, which is a security requirement in my organisation. The communication path then looks like:

----------------------         -------------         -----------------------
| Application client |  <--->  | TCP Proxy |  <--->  | Target (e.g. kafka) |
----------------------         -------------         -----------------------

However, this method does not really work with the public kafka cluster I need to talk to, as the kafka broker in the boostrap.servers list (which I can connect to perfectly fine) will return the list of nodes with the public endpoint names I can not connect to (as they're not going through the proxy).

So, instead of using the discovery functionality of the Kafka client, I would like to use a fixed, pre-defined list of brokers, which I can setup to use the TCP proxy. However, I didn't see any solution for that in the API so far and hope for some help here.

I'm aware, that not using this functionality makes it impossible for the application to use the dynamic changes of the kafka cluster state (when a broker goes away and another one is spinned up), however, this is ok in my scenario and all given circumstances.


问:
Dumping SQL Query/ Recordset in to LO Calc Sheet using basic code and Range
I’m new to Calc and I use to be able to do something similar to this in Excel / VB. The code below pulls a SP from MySql, and does exactly what I want, except for the While loop. In VB I was able to loop through the recordset and dump it into a Range like so, “ActiveWorkbook.Sheets(1).Range("A5").CopyFromRecordset rs”.  Without having to go column by column. Is there anything in Basic-Calc like this?  I’ve looked all over and haven't come across anything.

...

```<code>Sub  RetriveData()
Dim RowSetObj As Object, ConnectToDatabase As Object

DATABASE_NAME = "file:///home/jod/Documents/test.odb"

DBContext=createUnoService("com.sun.star.sdb.DatabaseContext")
DataSource=DBContext.getByName(DATABASE_NAME)

If Not DataSource.IsPasswordRequired Then
ConnectToDatabase = DataSource.GetConnection("","")
Else
  InteractionHandler = createUnoService("com.sun.star.sdb.InteractionHandler")
ConnectToDatabase = DataSource.ConnectWithCompletion(InteractionHandler)
End If

oURL="file:///home/jod/Documents/CodExm3.ods"
oDoc=StarDesktop.loadComponentFromURL(oURL, "_blank", 0, Array())
oSheet=oDoc.Sheets(0)
oSheet.Name="Tasks"

SQLQuery= "call GVWC_DB.TestSP();"
SQLStatement=ConnectToDatabase.createStatement
RowSetObj=SQLStatement.executeQuery (SQLQuery)

While RowSetObj.Next
i=i+1
oCell=oSheet.getCellByPosition(0,i)
oCell.String=RowSetObj.getString(1)
oCell=oSheet.getCellByPosition(1,i)
oCell.String=RowSetObj.getString(2)
oCell=oSheet.getCellByPosition(2,i)
oCell.String=RowSetObj.getString(3)
oCell=oSheet.getCellByPosition(3,i)
oCell.String=RowSetObj.getString(4)
oCell=oSheet.getCellByPosition(4,i)
oCell.String=RowSetObj.getString(5)
oCell=oSheet.getCellByPosition(5,i)
oCell.String=RowSetObj.getString(6)
oCell=oSheet.getCellByPosition(6,i)
oCell.String=RowSetObj.getString(7)
oCell=oSheet.getCellByPosition(7,i)
oCell.String=RowSetObj.getString(8)
oCell=oSheet.getCellByPosition(8,i)
oCell.String=RowSetObj.getString(9)
oCell=oSheet.getCellByPosition(9,i)
oCell.String=RowSetObj.getString(10)
oCell=oSheet.getCellByPosition(10,i)
oCell.String=RowSetObj.getString(11)
oCell=oSheet.getCellByPosition(11,i)
oCell.String=RowSetObj.getString(12)
oCell=oSheet.getCellByPosition(12,i)
oCell.String=RowSetObj.getString(13)
oCell=oSheet.getCellByPosition(13,i)
oCell.String=RowSetObj.getString(14)
oCell=oSheet.getCellByPosition(14,i)
oCell.String=RowSetObj.getString(15)
oCell=oSheet.getCellByPosition(15,i)

Wend

oSheet.getRows.insertByIndex( 0, 6 )

'Sheet.Columns.removeByIndex(5, 1)

End Sub
...
</code>```

答:
The LibreOffice API doesn't like gigantic do-everything-all-in-one-shot commands as VBA does. Instead, all it takes is a simple For loop.

```<code>resultSet = SQLStatement.executeQuery(SQLQuery)
While resultSet.next()
    For iCol = 1 To resultSet.getMetaData().getColumnCount()
        oCell = oSheet.getCellByPosition(iCol - 1, resultSet.getRow())
        oCell.String = resultSet.getString(iCol)
    Next
Wend
</code>```

This works if all you need is a string representation of the data. When using methods such as getInt() with some columns, a For loop may not be the best choice.

Documentation: ResultSet

Body:
I’m new to Calc and I use to be able to do something similar to this in Excel / VB. The code below pulls a SP from MySql, and does exactly what I want, except for the While loop. In VB I was able to loop through the recordset and dump it into a Range like so, “ActiveWorkbook.Sheets(1).Range("A5").CopyFromRecordset rs”.  Without having to go column by column. Is there anything in Basic-Calc like this?  I’ve looked all over and haven't come across anything.

...

Sub  RetriveData()
Dim RowSetObj As Object, ConnectToDatabase As Object

DATABASE_NAME = "file:///home/jod/Documents/test.odb"

DBContext=createUnoService("com.sun.star.sdb.DatabaseContext")
DataSource=DBContext.getByName(DATABASE_NAME)

If Not DataSource.IsPasswordRequired Then
ConnectToDatabase = DataSource.GetConnection("","")
Else
  InteractionHandler = createUnoService("com.sun.star.sdb.InteractionHandler")
ConnectToDatabase = DataSource.ConnectWithCompletion(InteractionHandler)
End If

oURL="file:///home/jod/Documents/CodExm3.ods"
oDoc=StarDesktop.loadComponentFromURL(oURL, "_blank", 0, Array())
oSheet=oDoc.Sheets(0)
oSheet.Name="Tasks"

SQLQuery= "call GVWC_DB.TestSP();"
SQLStatement=ConnectToDatabase.createStatement
RowSetObj=SQLStatement.executeQuery (SQLQuery)

While RowSetObj.Next
i=i+1
oCell=oSheet.getCellByPosition(0,i)
oCell.String=RowSetObj.getString(1)
oCell=oSheet.getCellByPosition(1,i)
oCell.String=RowSetObj.getString(2)
oCell=oSheet.getCellByPosition(2,i)
oCell.String=RowSetObj.getString(3)
oCell=oSheet.getCellByPosition(3,i)
oCell.String=RowSetObj.getString(4)
oCell=oSheet.getCellByPosition(4,i)
oCell.String=RowSetObj.getString(5)
oCell=oSheet.getCellByPosition(5,i)
oCell.String=RowSetObj.getString(6)
oCell=oSheet.getCellByPosition(6,i)
oCell.String=RowSetObj.getString(7)
oCell=oSheet.getCellByPosition(7,i)
oCell.String=RowSetObj.getString(8)
oCell=oSheet.getCellByPosition(8,i)
oCell.String=RowSetObj.getString(9)
oCell=oSheet.getCellByPosition(9,i)
oCell.String=RowSetObj.getString(10)
oCell=oSheet.getCellByPosition(10,i)
oCell.String=RowSetObj.getString(11)
oCell=oSheet.getCellByPosition(11,i)
oCell.String=RowSetObj.getString(12)
oCell=oSheet.getCellByPosition(12,i)
oCell.String=RowSetObj.getString(13)
oCell=oSheet.getCellByPosition(13,i)
oCell.String=RowSetObj.getString(14)
oCell=oSheet.getCellByPosition(14,i)
oCell.String=RowSetObj.getString(15)
oCell=oSheet.getCellByPosition(15,i)

Wend

oSheet.getRows.insertByIndex( 0, 6 )

'Sheet.Columns.removeByIndex(5, 1)

End Sub
...

Body:
The LibreOffice API doesn't like gigantic do-everything-all-in-one-shot commands as VBA does. Instead, all it takes is a simple For loop.

resultSet = SQLStatement.executeQuery(SQLQuery)
While resultSet.next()
    For iCol = 1 To resultSet.getMetaData().getColumnCount()
        oCell = oSheet.getCellByPosition(iCol - 1, resultSet.getRow())
        oCell.String = resultSet.getString(iCol)
    Next
Wend

This works if all you need is a string representation of the data. When using methods such as getInt() with some columns, a For loop may not be the best choice.

Documentation: ResultSet


问:
How can I modify text that is already printed?
I am aware that this has been posted many times, but I can't find a working solution for my problem. Here is my script:

from time import sleep
x = 100
for i in range(0, 100):
    print(x, end="\r")
    x -=1
    sleep(1)
```

<p>When I run this it prints:</p>

```100
990
980
970
```

<p>except on one line and the text gets replaced and it continues. I want it to do this:</p>

```100
99
98
97
```

on one line and it goes all the way to zero and the text gets replaced. How can I do this?

答:
You can use str.ljust():

```<code>print(str(x).ljust(3), end="\r")
</code>```

Body:
I am aware that this has been posted many times, but I can't find a working solution for my problem. Here is my script:

from time import sleep
x = 100
for i in range(0, 100):
    print(x, end="\r")
    x -=1
    sleep(1)

When I run this it prints:

100
990
980
970

except on one line and the text gets replaced and it continues. I want it to do this:

100
99
98
97

on one line and it goes all the way to zero and the text gets replaced. How can I do this?

Body:
You can use str.ljust():

print(str(x).ljust(3), end="\r")


答:
In R, we can also remove the substring instead of capturing

```<code>sub("[-_]brain.*", "", names)
#[1] "ABBA-1_2"  "BABBA-2_2" "ARA_1-1_2"
</code>```

Or with trimws

```<code>trimws(names, whitespace = "[-_]brain.*")
#[1] "ABBA-1_2"  "BABBA-2_2" "ARA_1-1_2"
</code>```

Using the OP's example

```<code>library(dplyr)
library(stringr)
brain_ref <-  brain_ref %>%
                 mutate(newsample = str_remove(sample,  "[_-]brain.*"))
</code>```

data

```<code>names <- c("ABBA-1_2-brain-total2", "BABBA-2_2_brain-total2", "ARA_1-1_2-brain-total2")
</code>```

Title: Pattern matching using regex for messy file names

Body:
I do not have very much experience with REs, but need to parse 100s of file names to generate a 'metadata' data set. I have been able to generate text files that include the file paths and the file name. It is simple for me to parse out the complete file name, but I need to be able to parse out the "sample ID" from the file name.

The issue is that the syntax of the "sample IDs" is all over the place (See attached csv for example data: The goal is to go from the 'sample' column to the 'ID' column). I have tried a series of strsplit() commands, but this is very cumbersome, and is not functional in nature. I have also tried writing a function with a number of IF statements based on syntax structure. I feel like this is still not a good solution because it is still dependent on me manually identifying the different syntax before hand, and I could easily miss something since I have to do this by eye.

It seems to me that this is a regex problem, but I could use some resources to help me get started. I would like to be able to do this in either R or Python if possible. Thank you for any resources, or packages/modules that may be useful.

dput(head(brain_ref, 25))
structure(list(file = c("/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/BXH12_2_brain_total_RNA_cDNA_CAGATC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_1_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB13_2_brain_total_RNA_cDNA_GTGAAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_1_brain_total_RNA_cDNA_CCGTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB17_2_brain_total_RNA_cDNA_ATGTCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_1_brain_total_RNA_cDNA_GTCCGC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB2_2_brain_total_RNA_cDNA_CTTGTA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_1_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB25_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_1_brain_total_RNA_cDNA_CGATGT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB27_2_brain_total_RNA_cDNA_AGTTCC.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_1_brain_total_RNA_cDNA_ACAGTG.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/HXB7_2_brain_total_RNA_cDNA_AGTCAA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_1_brain_total_RNA_cDNA_GCCAAT.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch1/ensembl_v96/SHR_2_brain_total_RNA_cDNA_TGACCA.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/ACI-SegHsd-2-brain-total-RNA_S17.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH2-3-brain-total-RNA_S4.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH5-3-brain-total-RNA_S3.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/BXH8-3-brain-total-RNA_S5.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Cop-CrCrl-2-brain-total-RNA_S10.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-1-brain-total-RNA_S16.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/Dark-Agouti-2-brain-total-RNA_S13.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-1-brain-total-RNA_S18.genes.results",
"/data/rn6/quantitation/brainTotalRNA/RI/batch10/ensembl_v96/F344-NCI-2-brain-total-RNA_S15.genes.results"
), sample = c("BXH12_1_brain_total_RNA_cDNA_GTCCGC", "BXH12_2_brain_total_RNA_cDNA_CAGATC",
"HXB13_1_brain_total_RNA_cDNA_ATGTCA", "HXB13_2_brain_total_RNA_cDNA_GTGAAA",
"HXB17_1_brain_total_RNA_cDNA_CCGTCC", "HXB17_2_brain_total_RNA_cDNA_ATGTCA",
"HXB2_1_brain_total_RNA_cDNA_GTCCGC", "HXB2_2_brain_total_RNA_cDNA_CTTGTA",
"HXB25_1_brain_total_RNA_cDNA_AGTTCC", "HXB25_2_brain_total_RNA_cDNA_AGTCAA",
"HXB27_1_brain_total_RNA_cDNA_CGATGT", "HXB27_2_brain_total_RNA_cDNA_AGTTCC",
"HXB7_1_brain_total_RNA_cDNA_ACAGTG", "HXB7_2_brain_total_RNA_cDNA_AGTCAA",
"SHR_1_brain_total_RNA_cDNA_GCCAAT", "SHR_2_brain_total_RNA_cDNA_TGACCA",
"ACI-SegHsd-2-brain-total-RNA_S17", "BXH2-3-brain-total-RNA_S4",
"BXH5-3-brain-total-RNA_S3", "BXH8-3-brain-total-RNA_S5", "Cop-CrCrl-2-brain-total-RNA_S10",
"Dark-Agouti-1-brain-total-RNA_S16", "Dark-Agouti-2-brain-total-RNA_S13",
"F344-NCI-1-brain-total-RNA_S18", "F344-NCI-2-brain-total-RNA_S15"
), batch = c("batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch1", "batch1", "batch1",
"batch1", "batch1", "batch1", "batch1", "batch10", "batch10",
"batch10", "batch10", "batch10", "batch10", "batch10", "batch10",
"batch10"), ID = c("BXH12_1", "BXH12_2", "HXB13_1", "HXB13_2",
"HXB17_1", "HXB17_2", "HXB2_1", "HXB2_2", "HXB25_1", "HXB25_2",
"HXB27_1", "HXB27_2", "HXB7_1", "HXB7_2", "SHR_1", "SHR_2", "ACI-SegHsd_2",
"BXH2_3", "BXH5_3", "BXH8_3", "Cop-CrCrl_2", "Dark-Agouti_1",
"Dark-Agouti_2", "F344-NCI_1", "F344-NCI_2")), row.names = c(NA,
25L), class = "data.frame")

Body:
In R, we can also remove the substring instead of capturing

sub("[-_]brain.*", "", names)
#[1] "ABBA-1_2"  "BABBA-2_2" "ARA_1-1_2"

Or with trimws

trimws(names, whitespace = "[-_]brain.*")
#[1] "ABBA-1_2"  "BABBA-2_2" "ARA_1-1_2"

Using the OP's example

library(dplyr)
library(stringr)
brain_ref <-  brain_ref %>%
                 mutate(newsample = str_remove(sample,  "[_-]brain.*"))

data

names <- c("ABBA-1_2-brain-total2", "BABBA-2_2_brain-total2", "ARA_1-1_2-brain-total2")


答:
Why not just:</p>

```<code>for name in names:
    m = re.match(r'(.*)[_\-]brain[_\-]total', name)
    print(m.group(1))
</code>```

Body:
Why not just:

for name in names:
    m = re.match(r'(.*)[_\-]brain[_\-]total', name)
    print(m.group(1))


问:
How can we do object filtering in Entity Framework?
When defining an object context, using code first in entity framework, for example:

```<code>public class DomainContext : DbContext
{
    public DomainContext() { }
    public virtual DbSet<News> News { get; set; }
}
</code>```

We all know that you can query "News" doing something like (for example, to get all news that were published today):

```<code>var ctx = new DomainContext();
ctx.News.Where(x => x.PublishedDate == DateTime.Now.Date)
</code>```

But, and this is the question: Is there a way to apply a pre-defined filtering/condition to all queries that pass through ctx.News? Say that I wanted that all queries on ctx.News to have the "Published Today" filtering implicit applied?

答:
You could add a new property to your context:

```<code>public IEnumerable<News> TodaysNews
{
    get
    {
        return this.News.Where(x => x.PublishedDate == DateTime.Now.Date);
    }
}
</code>```

Any further filtering/sorting/etc can then be applied to the property.

Update:

If you're not able to just use a pre-filtered query, another option is to create a view in your database and map your entity to that view.  The view could be based on the current date.

Body:
When defining an object context, using code first in entity framework, for example:

public class DomainContext : DbContext
{
    public DomainContext() { }
    public virtual DbSet<News> News { get; set; }
}

We all know that you can query "News" doing something like (for example, to get all news that were published today):

var ctx = new DomainContext();
ctx.News.Where(x => x.PublishedDate == DateTime.Now.Date)

But, and this is the question: Is there a way to apply a pre-defined filtering/condition to all queries that pass through ctx.News? Say that I wanted that all queries on ctx.News to have the "Published Today" filtering implicit applied?

Body:
You could add a new property to your context:

public IEnumerable<News> TodaysNews
{
    get
    {
        return this.News.Where(x => x.PublishedDate == DateTime.Now.Date);
    }
}

Any further filtering/sorting/etc can then be applied to the property.

Update:

If you're not able to just use a pre-filtered query, another option is to create a view in your database and map your entity to that view.  The view could be based on the current date.


问:
Unreal: I get "fatal error: 'IMotionController.h' file not found" when trying to build
The IMotionController.h file is included in my external dependencies folder in Visual Studio, so I can compile my code in the Editor, but when I try to build to an application I get:

```<code>fatal error: 'IMotionController.h' file not found
</code>```

Do I need to include something in my Build.cs dependencies?

Currently, just using the defaults:

```<code>PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore"});
</code>```

答:
I had to add the HeadMountedDisplay module to the Build.cs:

```<code> PublicDependencyModuleNames.AddRange(new string[] { "HeadMountedDisplay", "Core", "CoreUObject", "Engine", "InputCore" });
</code>```

Body:
The IMotionController.h file is included in my external dependencies folder in Visual Studio, so I can compile my code in the Editor, but when I try to build to an application I get:

fatal error: 'IMotionController.h' file not found

Do I need to include something in my Build.cs dependencies?

Currently, just using the defaults:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore"});

Body:
I had to add the HeadMountedDisplay module to the Build.cs:

 PublicDependencyModuleNames.AddRange(new string[] { "HeadMountedDisplay", "Core", "CoreUObject", "Engine", "InputCore" });


问:
SwiftUI crash: "precondition failure: attribute failed to set an initial value: 71”
I have a very interesting crash, that only happens under very specific circumstances. I've already submitted a bug report to Apple, but maybe someone here has seen a similar crash, knows what's going on, and knows a workaround?

A minimal project showing the crash can be found at https://github.com/kevinrenskers/SwiftUICrash but I've also added the related code below. The project has 3 views: RootView, DetailsView and ListView. RootView embeds either the DetailsView or the ListView.

The crash happens when you press the trailing navigation bar button in DetailsView to switch back to the ListView. The app crashes with the error "precondition failure: attribute failed to set an initial value: 71”.

When you use the Button in the middle of the screen to switch back to the ListView however, the crash does NOT happen. And when you remove the .resizable() modifier from the background image, the crash also does NOT happen.

Also, if you change Group into NavigationView inside of RootView, the app doesn't crash. Sadly that's not an option for my real-world app though.

import SwiftUI

final class AppStore: ObservableObject {
  @Published var showingDetails = true
}

struct RootView: View {
  @EnvironmentObject private var store: AppStore

  var body: some View {
    Group {
      if store.showingDetails {
        DetailsView()
      } else {
        ListView()
      }
    }
  }
}

struct DetailsView: View {
  @EnvironmentObject private var store: AppStore

  var body: some View {
    NavigationView {
      ZStack {
        GeometryReader { geo in
          Image("bg")
            .resizable()
            .aspectRatio(contentMode: .fill)
            .edgesIgnoringSafeArea(.all)
            .frame(width: geo.size.width, height: geo.size.height)
        }

        Button("List") {
          self.store.showingDetails = false // <- this works fine
        }
        .padding(20)
        .background(Color.white)
      }
      .navigationBarTitle(Text("Details"))
      .navigationBarItems(trailing: trailingNavigationBarItem)
    }
  }

  private var trailingNavigationBarItem: some View {
    Button("List") {
      self.store.showingDetails = false // <- this crashes the app!
    }
  }
}

struct ListView: View {
  @EnvironmentObject private var store: AppStore

  var body: some View {
    NavigationView {
      Button("Load details") {
        self.store.showingDetails = true
      }
      .padding(20)
      .background(Color.white)
      .navigationBarTitle("List")
    }
  }
}
```

答:
Try replacing the group in RootView with a @ViewBuilder annotation:

```<code>struct RootView: View {
  @EnvironmentObject private var store: AppStore

  @ViewBuilder
  var body: some View {
    if store.showingDetails {
      DetailsView()
    } else {
      ListView()
    }
  }
}
</code>```

I am not sure how reliable that is in general. I had mixed success inserting @ViewBuilder annotations in the past, but this seems to fix the issue with the nested NavigationView.

Body:
Try replacing the group in RootView with a @ViewBuilder annotation:

struct RootView: View {
  @EnvironmentObject private var store: AppStore

  @ViewBuilder
  var body: some View {
    if store.showingDetails {
      DetailsView()
    } else {
      ListView()
    }
  }
}

I am not sure how reliable that is in general. I had mixed success inserting @ViewBuilder annotations in the past, but this seems to fix the issue with the nested NavigationView.


问:
Terraform: Conditional creation of a resource based on a variable in .tfvars
I have resources defined in .tf files that are generic to several applications. I populate many of the fields via a .tfvars file. I need to omit some of the resources entirely based on variables in the .tfvars.

For example if I have a resource like:

```<code>resource "cloudflare_record" "record" {
  zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
  name    = "${var.subdomain}"
  value   = "${var.origin_server}"
  type    = "CNAME"
  ttl     = 1
  proxied = true
}
</code>```

But then I declare something like cloudflare = false in my .tfvars file I'd like to be able to do something like this:

```<code>if var.cloudflare {
  resource "cloudflare_record" "record" {
    zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
    name    = "${var.subdomain}"
    value   = "${var.origin_server}"
    type    = "CNAME"
    ttl     = 1
    proxied = true
 }
}
</code>```

I've looked at dynamic blocks but that looks like you can only use those to edit fields and blocks within a resource. I need to be able to ignore an entire resource.

答:
Add a count parameter with a ternary conditional using the variable declared in .tfvars like this:

```<code>resource "cloudflare_record" "record" {
  count = var.cloudflare ? 1 : 0
  zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
  name    = "${var.subdomain}"
  value   = "${var.origin_server}"
  type    = "CNAME"
  ttl     = 1
  proxied = true
}
</code>```

In this example var.cloudflare is a boolean declared in the .tfvars file. If it is true a count of 1 record will be created. If it is false a count of 0 record will be created.

After the count apply the resource becomes a group, so later in the reference use 0-index of the group:

```<code>cloudflare_record.record[0].some_field
</code>```

Body:
I have resources defined in .tf files that are generic to several applications. I populate many of the fields via a .tfvars file. I need to omit some of the resources entirely based on variables in the .tfvars.

For example if I have a resource like:

resource "cloudflare_record" "record" {
  zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
  name    = "${var.subdomain}"
  value   = "${var.origin_server}"
  type    = "CNAME"
  ttl     = 1
  proxied = true
}

But then I declare something like cloudflare = false in my .tfvars file I'd like to be able to do something like this:

if var.cloudflare {
  resource "cloudflare_record" "record" {
    zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
    name    = "${var.subdomain}"
    value   = "${var.origin_server}"
    type    = "CNAME"
    ttl     = 1
    proxied = true
 }
}

I've looked at dynamic blocks but that looks like you can only use those to edit fields and blocks within a resource. I need to be able to ignore an entire resource.

Body:
Add a count parameter with a ternary conditional using the variable declared in .tfvars like this:

resource "cloudflare_record" "record" {
  count = var.cloudflare ? 1 : 0
  zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
  name    = "${var.subdomain}"
  value   = "${var.origin_server}"
  type    = "CNAME"
  ttl     = 1
  proxied = true
}

In this example var.cloudflare is a boolean declared in the .tfvars file. If it is true a count of 1 record will be created. If it is false a count of 0 record will be created.

After the count apply the resource becomes a group, so later in the reference use 0-index of the group:

cloudflare_record.record[0].some_field


问:
fopen (php) from remote server works only for reading
I need to open a text file from a remote server and to write some information in it, using PHP fopen().

allow_url_fopen is ON (in my php.ini).

I can read this remote file, but can't write in it.

Code:

```<code><?php
$data = 'some text';
$filename = 'ftp://admin:password@192.168.254.1/web/domain.com/public_html/test2.txt';
$fh = fopen($filename, 'r');
echo fread($fh, filesize($filename));
fclose($fh);

$fh = fopen($filename, 'w+');
if ($fh) {
  echo 'remote file is opened, writing data';
  fwrite($fh, $data);
  fclose($fh);
} else {
  echo 'remote file not opened';
}
?>
</code>```

Shows:
some text
remote file not opened

What can i do make in write to file?

答:
From PHP: ftp://

Allows read access to existing files and creation of new files via FTP.

You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing but have not specified the context option overwrite, the connection will fail. If you need to overwrite existing files over ftp, specify the overwrite option in the context and open the file for writing. Alternatively, you can use the FTP extension.

Also a note:

Note: Appending

Files may be appended via the ftp:// URL wrapper.

I'm not sure if overwrite means truncate or not.  If so, you can download, modify and then upload and overwrite or look at PHP: FTP Functions.

More from PHP: Using remote files:

You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.

And then a note:

Note:

You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().

So it seems that you can create a file or completely overwrite an existing one.  I haven't seen an example for append.

Body:
I need to open a text file from a remote server and to write some information in it, using PHP fopen().

allow_url_fopen is ON (in my php.ini).

I can read this remote file, but can't write in it.

Code:

<?php
$data = 'some text';
$filename = 'ftp://admin:password@192.168.254.1/web/domain.com/public_html/test2.txt';
$fh = fopen($filename, 'r');
echo fread($fh, filesize($filename));
fclose($fh);

$fh = fopen($filename, 'w+');
if ($fh) {
  echo 'remote file is opened, writing data';
  fwrite($fh, $data);
  fclose($fh);
} else {
  echo 'remote file not opened';
}
?>

Shows:
some text
remote file not opened

What can i do make in write to file?


问:
Flutter StreamBuilder with Firestore Pagination
I'm trying to build a basic chat feature where all of a users chat messages are stored as documents in a "chats" collection. I have successfully implemented pagination to ensure I am not overpulling data until the user scrolls.

However, even though I have a StreamBuilder, new chat documents are not appearing automatically like they normally would. Why is the streambuilder not registering and displaying these new messages?

Here is my code:

```<code>class MotivatorChat extends StatefulWidget {
  @override
  _MotivatorChatState createState() => _MotivatorChatState();
}

class _MotivatorChatState extends State<MotivatorChat> {

  Firestore firestore = Firestore.instance;
  List<DocumentSnapshot> chats = [];
  bool isLoading = false;
  bool hasMore = true;
  int documentLimit = 10;
  DocumentSnapshot lastDocument;
  ScrollController _scrollController = ScrollController();

  StreamController<List<DocumentSnapshot>> _controller = StreamController<List<DocumentSnapshot>>();

  Stream<List<DocumentSnapshot>> get _streamController => _controller.stream;

  @override
  void initState() {
    super.initState();
    getChats();
    _scrollController.addListener(() {
      double maxScroll = _scrollController.position.maxScrollExtent;
      double currentScroll = _scrollController.position.pixels;
      double delta = MediaQuery.of(context).size.height * 0.20;
      if (maxScroll - currentScroll <= delta) {
        getChats();
      }

    });
  }

  getChats() async {
    if (!hasMore) {
      print('No More Chats');
      return;
    }
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
    });
    QuerySnapshot querySnapshot;
    if (lastDocument == null) {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .limit(documentLimit)
          .getDocuments();
    } else {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .startAfterDocument(lastDocument)
          .limit(documentLimit)
          .getDocuments();
      print(1);
    }
    if (querySnapshot.documents.length < documentLimit) {
      hasMore = false;
    }

    lastDocument = querySnapshot.documents[querySnapshot.documents.length - 1];

    chats.addAll(querySnapshot.documents);
    _controller.sink.add(chats);

    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination with Firestore'),
      ),
      body: Column(children: [
        Expanded(
          child: StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              print(snapshot.connectionState);
              if (snapshot.hasData && snapshot.data.length > 0) {
                return ListView.builder(
                  reverse: true,
                  controller: _scrollController,
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Container(
                        height: 20,
                        child: Text(snapshot.data[index].data['text']),
                      ),
                    );
                  },
                );
              } else {
                return Center(
                  child: Text('No Data...'),
                );
              }
            },
          ),
        ),
        isLoading
            ? Container(
          width: MediaQuery
              .of(context)
              .size
              .width,
          padding: EdgeInsets.all(5),
          color: Colors.yellowAccent,
          child: Text(
            'Loading',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        )
            : Container(),

      ]),
    );
  }
}
</code>```

Updated StreamBuilder

```<code>StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              if (snapshot.connectionState == ConnectionState.none) {
                return Text("None");
              } else if (snapshot.connectionState == ConnectionState.waiting) {
                return Text("Loading");
              } else if (snapshot.connectionState == ConnectionState.active) {
                if (snapshot.hasData && snapshot.data.length > 0) {
                  return ListView.builder(
                    reverse: true,
                    controller: _scrollController,
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.only(top: 20),
                        child: Container(
                          height: 20,
                          child: Text(snapshot.data[index].data['text']),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(
                    child: Text('No Data...'),
                  );
                }
              } else {
                return Text("return list");
              }
            },
          ),
</code>```

答:
I try your code and set document limit to 20, it work fine.

Example on DartPad

Body:
I'm trying to build a basic chat feature where all of a users chat messages are stored as documents in a "chats" collection. I have successfully implemented pagination to ensure I am not overpulling data until the user scrolls.

However, even though I have a StreamBuilder, new chat documents are not appearing automatically like they normally would. Why is the streambuilder not registering and displaying these new messages?

Here is my code:

class MotivatorChat extends StatefulWidget {
  @override
  _MotivatorChatState createState() => _MotivatorChatState();
}

class _MotivatorChatState extends State<MotivatorChat> {

  Firestore firestore = Firestore.instance;
  List<DocumentSnapshot> chats = [];
  bool isLoading = false;
  bool hasMore = true;
  int documentLimit = 10;
  DocumentSnapshot lastDocument;
  ScrollController _scrollController = ScrollController();

  StreamController<List<DocumentSnapshot>> _controller = StreamController<List<DocumentSnapshot>>();

  Stream<List<DocumentSnapshot>> get _streamController => _controller.stream;

  @override
  void initState() {
    super.initState();
    getChats();
    _scrollController.addListener(() {
      double maxScroll = _scrollController.position.maxScrollExtent;
      double currentScroll = _scrollController.position.pixels;
      double delta = MediaQuery.of(context).size.height * 0.20;
      if (maxScroll - currentScroll <= delta) {
        getChats();
      }

    });
  }

  getChats() async {
    if (!hasMore) {
      print('No More Chats');
      return;
    }
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
    });
    QuerySnapshot querySnapshot;
    if (lastDocument == null) {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .limit(documentLimit)
          .getDocuments();
    } else {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .startAfterDocument(lastDocument)
          .limit(documentLimit)
          .getDocuments();
      print(1);
    }
    if (querySnapshot.documents.length < documentLimit) {
      hasMore = false;
    }

    lastDocument = querySnapshot.documents[querySnapshot.documents.length - 1];

    chats.addAll(querySnapshot.documents);
    _controller.sink.add(chats);

    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination with Firestore'),
      ),
      body: Column(children: [
        Expanded(
          child: StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              print(snapshot.connectionState);
              if (snapshot.hasData && snapshot.data.length > 0) {
                return ListView.builder(
                  reverse: true,
                  controller: _scrollController,
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Container(
                        height: 20,
                        child: Text(snapshot.data[index].data['text']),
                      ),
                    );
                  },
                );
              } else {
                return Center(
                  child: Text('No Data...'),
                );
              }
            },
          ),
        ),
        isLoading
            ? Container(
          width: MediaQuery
              .of(context)
              .size
              .width,
          padding: EdgeInsets.all(5),
          color: Colors.yellowAccent,
          child: Text(
            'Loading',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        )
            : Container(),

      ]),
    );
  }
}

Updated StreamBuilder

StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              if (snapshot.connectionState == ConnectionState.none) {
                return Text("None");
              } else if (snapshot.connectionState == ConnectionState.waiting) {
                return Text("Loading");
              } else if (snapshot.connectionState == ConnectionState.active) {
                if (snapshot.hasData && snapshot.data.length > 0) {
                  return ListView.builder(
                    reverse: true,
                    controller: _scrollController,
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.only(top: 20),
                        child: Container(
                          height: 20,
                          child: Text(snapshot.data[index].data['text']),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(
                    child: Text('No Data...'),
                  );
                }
              } else {
                return Text("return list");
              }
            },
          ),


问:
Python selenium grecaptcha_cfg Callback
I successfully receive the recaptcha response, but since there isn't a submit button i'm thinking i need to send it via a callback.  I'm using the below command to send the response, but it's coming back as not defined and I'm not sure why.  Any help is greatly appreciated.

```<code>driver.execute_script("__grecaptcha_cfg.clients[0].EL.w.callback(arguments[0]);",TOKEN_FROM_2CAPTCHA)
</code>```

JavascriptException: Message: javascript error: __grecaptcha_cfg is not defined

答:
My bad I was missing an extra underscore. It should be this:</p>

```<code>driver.execute_script("___grecaptcha_cfg.clients[0].EL.w.callback(arguments[0]);",TOKEN_FROM_2CAPTCHA)
</code>```

Title: Python selenium grecaptcha_cfg Callback

Body:
I successfully receive the recaptcha response, but since there isn't a submit button i'm thinking i need to send it via a callback.  I'm using the below command to send the response, but it's coming back as not defined and I'm not sure why.  Any help is greatly appreciated.

driver.execute_script("__grecaptcha_cfg.clients[0].EL.w.callback(arguments[0]);",TOKEN_FROM_2CAPTCHA)

JavascriptException: Message: javascript error: __grecaptcha_cfg is not defined

Body:
My bad I was missing an extra underscore. It should be this:

driver.execute_script("___grecaptcha_cfg.clients[0].EL.w.callback(arguments[0]);",TOKEN_FROM_2CAPTCHA)