问:
useState does not update the state
I'm trying to update a state using useState hook, however the state won't update. I've checked how to fix it but really have no idea about it what cause this point. This is the whole code I didnt include the urls and import files...

When onchange method trigger ilceZoom  function event has value so ı can get it evt.value example values is "1234" but I can not set it using useState future

```<code>const ilceUrl = 'URL';

const AddressSearchMaks = (props) => {
    useEffect(() => {
        ilceLoad();
    }, []);

    const [ ilceler, setIlceler ] = useState([]);
    const [ selectedIlce, setSelectedIlce ] = useState(null);

    let queryTask;
    let query;
    let sfs;
    let lineSymbol;
    let polygon;
    let polyline;
    let graphic;
    let extent;
    let point;
    let wMercatorUtils;
    let rfConverter;

    loadModules([
        'esri/tasks/query',
        'esri/tasks/QueryTask',
        'esri/symbols/SimpleFillSymbol',
        'esri/symbols/SimpleLineSymbol',
        'esri/geometry/Polygon',
        'esri/geometry/Polyline',
        'esri/geometry/webMercatorUtils',
        'esri/geometry/Extent',
        'esri/geometry/Point',
        'esri/graphic',
        'esri/Color',
        'libs/ReferenceConverter'
    ]).then(
        (
            [
                Query,
                QueryTask,
                SimpleFillSymbol,
                SimpleLineSymbol,
                Polygon,
                Polyline,
                webMercatorUtils,
                Extent,
                Point,
                Graphic,
                Color,
                referenceConverter
            ]
        ) => {
            queryTask = QueryTask;
            query = Query;
            polygon = Polygon;
            polyline = Polyline;
            graphic = Graphic;
            extent = Extent;
            point = Point;
            wMercatorUtils = webMercatorUtils;
            rfConverter = referenceConverter;
            sfs = new SimpleFillSymbol(
                SimpleFillSymbol.STYLE_SOLID,
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4),
                new Color([ 140, 140, 140, 0.25 ])
            );
            lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4).setWidth(4);
        }
    );

    const getAdres = async (url) => {
        let response = await fetch(url);
        let data = await response.json();
        let list = [];
        data.AdresList.Adresler.Adres.forEach((item) => {
            list.push({
                label: item.ADI,
                value: item.ID,
                lat: item.LAT,
                lon: item.LON
            });
        });
        return list;
    };

    async function ilceLoad() {
        let ilceList = await getAdres(ilceUrl);
        setIlceler(ilceList);
    }

    const convertExtent = (lat, lon) => {
        let p;
        let ext;
        const sr = props.map.spatialReference;
        if (sr.wkid == 102100) {
            const _p = wMercatorUtils.lngLatToXY(lon, lat);
            ext = extent({
                xmin: _p[0],
                ymin: _p[1],
                xmax: _p[0],
                ymax: _p[1],
                spatialReference: props.map.spatialReference
            });
        } else {
            const res = rfConverter.WgsToItrf(lat, lon);
            ext = extent({
                xmin: res.x,
                ymin: res.y,
                xmax: res.x,
                ymax: res.y,
                spatialReference: props.map.spatialReference
            });
            p = point(res.x, res.y);
        }
        p.spatialReference = sr;
        return ext;
    };

    const ilceZoom = (evt) => {
        setSelectedIlce(evt.value);
        console.log('selectedIlce', selectedIlce);
        setError(false);
        console.log('error', error);
        const qTask = queryTask(maksIlce);
        const q = query();
        q.returnGeometry = true;
        q.outFields = [ '*' ];
        q.outSpatialReference = { wkid: 5254 };
        q.where = `KIMLIKNO=${evt.value}`;
        qTask.execute(q, (evt) => {
            const polyGon = polygon({
                rings: evt.features[0].geometry.rings
            });
            props.map.graphics.add(graphic(polyGon, sfs));
        });
        const extent = convertExtent(evt.lat, evt.lon);
        props.map.setExtent(extent);
        mahalleLoad();
    };

    return (

            <Select name='adresSelect' options={ilceler} onChange={(e) => ilceZoom(e)} placeholder='İlçe Seçiniz' />

    );
};

const mapStateToProps = (state) => ({
    map: state.map.map
});

export default connect(mapStateToProps, null)(AddressSearchMaks);

</code>```

答:
It can be related for some environment binding issue. Try to use the the setState as function: </p>

```<code>useEffect(() => {
        ilceLoad();
    }, []);

    const [ ilceler, setIlceler ] = useState([]);
    const [ selectedIlce, setSelectedIlce ] = useState(null);

async function ilceLoad() {
        let ilceList = await getAdres(ilceUrl);
        setIlceler(ilceList); // update the state, it works here
    }

const ilceZoom = (evt) => {
        setSelectedIlce(prev => {
          console.log("prev: ", prev);
          console.log("evt.value: ", evt.value);
          return evt.value;
        });
        const qTask = queryTask(url);
        const q = query();
        q.returnGeometry = true;
        q.outFields = [ '*' ];
        q.outSpatialReference = { wkid: 5254 };
        q.where = `VARIABLE NAME=${evt.value}`;
        qTask.execute(q, (evt) => {
            const polyGon = polygon({
                rings: evt.features[0].geometry.rings
            });
            props.map.graphics.add(graphic(polyGon, sfs));
        });
        const extent = convertExtent(evt.lat, evt.lon);
        props.map.setExtent(extent);
    };
</code>```

Title: useState does not update the state

Body:
I'm trying to update a state using useState hook, however the state won't update. I've checked how to fix it but really have no idea about it what cause this point. This is the whole code I didnt include the urls and import files...

When onchange method trigger ilceZoom  function event has value so ı can get it evt.value example values is "1234" but I can not set it using useState future

const ilceUrl = 'URL';

const AddressSearchMaks = (props) => {
    useEffect(() => {
        ilceLoad();
    }, []);

    const [ ilceler, setIlceler ] = useState([]);
    const [ selectedIlce, setSelectedIlce ] = useState(null);

    let queryTask;
    let query;
    let sfs;
    let lineSymbol;
    let polygon;
    let polyline;
    let graphic;
    let extent;
    let point;
    let wMercatorUtils;
    let rfConverter;

    loadModules([
        'esri/tasks/query',
        'esri/tasks/QueryTask',
        'esri/symbols/SimpleFillSymbol',
        'esri/symbols/SimpleLineSymbol',
        'esri/geometry/Polygon',
        'esri/geometry/Polyline',
        'esri/geometry/webMercatorUtils',
        'esri/geometry/Extent',
        'esri/geometry/Point',
        'esri/graphic',
        'esri/Color',
        'libs/ReferenceConverter'
    ]).then(
        (
            [
                Query,
                QueryTask,
                SimpleFillSymbol,
                SimpleLineSymbol,
                Polygon,
                Polyline,
                webMercatorUtils,
                Extent,
                Point,
                Graphic,
                Color,
                referenceConverter
            ]
        ) => {
            queryTask = QueryTask;
            query = Query;
            polygon = Polygon;
            polyline = Polyline;
            graphic = Graphic;
            extent = Extent;
            point = Point;
            wMercatorUtils = webMercatorUtils;
            rfConverter = referenceConverter;
            sfs = new SimpleFillSymbol(
                SimpleFillSymbol.STYLE_SOLID,
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4),
                new Color([ 140, 140, 140, 0.25 ])
            );
            lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4).setWidth(4);
        }
    );

    const getAdres = async (url) => {
        let response = await fetch(url);
        let data = await response.json();
        let list = [];
        data.AdresList.Adresler.Adres.forEach((item) => {
            list.push({
                label: item.ADI,
                value: item.ID,
                lat: item.LAT,
                lon: item.LON
            });
        });
        return list;
    };

    async function ilceLoad() {
        let ilceList = await getAdres(ilceUrl);
        setIlceler(ilceList);
    }

    const convertExtent = (lat, lon) => {
        let p;
        let ext;
        const sr = props.map.spatialReference;
        if (sr.wkid == 102100) {
            const _p = wMercatorUtils.lngLatToXY(lon, lat);
            ext = extent({
                xmin: _p[0],
                ymin: _p[1],
                xmax: _p[0],
                ymax: _p[1],
                spatialReference: props.map.spatialReference
            });
        } else {
            const res = rfConverter.WgsToItrf(lat, lon);
            ext = extent({
                xmin: res.x,
                ymin: res.y,
                xmax: res.x,
                ymax: res.y,
                spatialReference: props.map.spatialReference
            });
            p = point(res.x, res.y);
        }
        p.spatialReference = sr;
        return ext;
    };

    const ilceZoom = (evt) => {
        setSelectedIlce(evt.value);
        console.log('selectedIlce', selectedIlce);
        setError(false);
        console.log('error', error);
        const qTask = queryTask(maksIlce);
        const q = query();
        q.returnGeometry = true;
        q.outFields = [ '*' ];
        q.outSpatialReference = { wkid: 5254 };
        q.where = `KIMLIKNO=${evt.value}`;
        qTask.execute(q, (evt) => {
            const polyGon = polygon({
                rings: evt.features[0].geometry.rings
            });
            props.map.graphics.add(graphic(polyGon, sfs));
        });
        const extent = convertExtent(evt.lat, evt.lon);
        props.map.setExtent(extent);
        mahalleLoad();
    };

    return (

            <Select name='adresSelect' options={ilceler} onChange={(e) => ilceZoom(e)} placeholder='İlçe Seçiniz' />

    );
};

const mapStateToProps = (state) => ({
    map: state.map.map
});

export default connect(mapStateToProps, null)(AddressSearchMaks);

Body:
It can be related for some environment binding issue. Try to use the the setState as function:

useEffect(() => {
        ilceLoad();
    }, []);

    const [ ilceler, setIlceler ] = useState([]);
    const [ selectedIlce, setSelectedIlce ] = useState(null);

async function ilceLoad() {
        let ilceList = await getAdres(ilceUrl);
        setIlceler(ilceList); // update the state, it works here
    }

const ilceZoom = (evt) => {
        setSelectedIlce(prev => {
          console.log("prev: ", prev);
          console.log("evt.value: ", evt.value);
          return evt.value;
        });
        const qTask = queryTask(url);
        const q = query();
        q.returnGeometry = true;
        q.outFields = [ '*' ];
        q.outSpatialReference = { wkid: 5254 };
        q.where = `VARIABLE NAME=${evt.value}`;
        qTask.execute(q, (evt) => {
            const polyGon = polygon({
                rings: evt.features[0].geometry.rings
            });
            props.map.graphics.add(graphic(polyGon, sfs));
        });
        const extent = convertExtent(evt.lat, evt.lon);
        props.map.setExtent(extent);
    };


来源: stackexchange

问:
Submitting data to different tabs using google sheet script editor
In my spreadsheet script editor, I have the below codes:

Code.gs

```<code>function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

function doPost1(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var checkForm = ss.getSheetByName("checkForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    var startTime = newRow[1];
    var endTime = newRow[2];
    var cal = CalendarApp.getCalendarById("ID");
    var allEvents = cal.getEvents(new Date(startTime), new Date(endTime));
    if (allEvents.length > 0) {
    return HtmlService.createTemplateFromFile('calendarAgenda.html')
    }else {
    return HtmlService.createTemplateFromFile('bookingForm.html')
    };

  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

function doPost2(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var bookForm = ss.getSheetByName("bookForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    return ContentService
    .createTextOutput(JSON.stringify('Successfully received. Thank you!'))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

</code>```

checkForm.html

```<code><!DOCTYPE html>
<body>
<form name="class1Check" id="class1Check" action="ScriptURL" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">
<br><br>
End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>
<script>
function postData(form) {
  google.script.run.withSuccessHandler(postData).doPost1(e);
}
</script>
</body>
</html>
</code>```

bookingForm.html

```<code><!DOCTYPE html>
<body>
<form name="class1Booking" id="class1Booking" action="ScriptURL" target="_self" method="POST">
<inputs> ..
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>
<script>
function postData(form) {
  google.script.run.withSuccessHandler(postData).doPost2(e);
}
</script>
</body>
</html>
</code>```

The goGet function returns the "checkForm.html" page that when submitted is supposed to run the doPost1 function to send the data to tab "checkForm" in the spreadsheet and then returns the second page "bookingForm.html" that when submitted is supposed to run the doPost2 function to send the data to tab "bookForm" and then returns a certain text output

When I submit the check form, I receive the error "Script function not found: doPost" and I think I might have some issues with google.script.run that I tried to modify several times with no luck. Any help and thanks in advance

答:
You’re not using google.script.run functions correctly, as it’s stated in the documentation you can only return values of types:

Number, Boolean, String, or null, as well as JavaScript objects and
  arrays that are composed of primitives, objects and arrays.

An in your case, you’re trying to return a textOutput object, which is not allowed, this class is intended for Web Apps functions (doGet(e) or doPost(e)).

In the documentation about [Client-to-Server communication] (https://developers.google.com/apps-script/guides/html/communication) it’s explained how to work with google.script.run. Here is an example applied to your case so you can understand better how it works:

checkForm.html

```<code><!DOCTYPE html>
<body>
<form name="class1Check" id="class1Check" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">
<br><br>
End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button onclick="postData(this.parentNode)">Check</button>
</form>
<script>
//It’s run when form button is clicked
function postData(form) {
   //Calls doSomething function in code.gs with form parameter
  google.script.run.withSuccessHandler(handlerFunction).doSomething(form);
}

//Handles the response from doSomething function
function handlerFunction(responseData) {
  //Logs ‘It worked!’ in developer console
  console.log(responseData);
}
</script>
</body>
</html>
</code>```

code.gs

```<code>//Web App function
function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

//Apps script function to receive form object and return response
function doSomething(form) {
//Do something
  return ‘It worked!’;
}
</code>```

Apps Script’s Web Apps are designed to be a single page application (one HTML page) and not a multi-page application, although there are different workaround examples you could guide from to achieve a multi-page behavior:

[1] Linking to another HTML page in Google Apps Script

[2] https://sites.google.com/corp/view/googlappsscript/recent-scripts/multiple-page-webapp-example

ContentLicense: CC BY-SA 4.0

Body:
In my spreadsheet script editor, I have the below codes:

Code.gs

function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

function doPost1(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var checkForm = ss.getSheetByName("checkForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    var startTime = newRow[1];
    var endTime = newRow[2];
    var cal = CalendarApp.getCalendarById("ID");
    var allEvents = cal.getEvents(new Date(startTime), new Date(endTime));
    if (allEvents.length > 0) {
    return HtmlService.createTemplateFromFile('calendarAgenda.html')
    }else {
    return HtmlService.createTemplateFromFile('bookingForm.html')
    };

  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

function doPost2(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var bookForm = ss.getSheetByName("bookForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    return ContentService
    .createTextOutput(JSON.stringify('Successfully received. Thank you!'))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

checkForm.html

<!DOCTYPE html>

<form name="class1Check" id="class1Check" action="ScriptURL" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">

End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>

bookingForm.html

<!DOCTYPE html>

<form name="class1Booking" id="class1Booking" action="ScriptURL" target="_self" method="POST">
<inputs> ..
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>

The goGet function returns the "checkForm.html" page that when submitted is supposed to run the doPost1 function to send the data to tab "checkForm" in the spreadsheet and then returns the second page "bookingForm.html" that when submitted is supposed to run the doPost2 function to send the data to tab "bookForm" and then returns a certain text output

When I submit the check form, I receive the error "Script function not found: doPost" and I think I might have some issues with google.script.run that I tried to modify several times with no luck. Any help and thanks in advance

Body:
You’re not using google.script.run functions correctly, as it’s stated in the documentation you can only return values of types:

Number, Boolean, String, or null, as well as JavaScript objects and
  arrays that are composed of primitives, objects and arrays.

An in your case, you’re trying to return a textOutput object, which is not allowed, this class is intended for Web Apps functions (doGet(e) or doPost(e)).

In the documentation about [Client-to-Server communication] (https://developers.google.com/apps-script/guides/html/communication) it’s explained how to work with google.script.run. Here is an example applied to your case so you can understand better how it works:

checkForm.html

<!DOCTYPE html>
<body>
<form name="class1Check" id="class1Check" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">
<br><br>
End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button onclick="postData(this.parentNode)">Check</button>
</form>
<script>
//It’s run when form button is clicked
function postData(form) {
   //Calls doSomething function in code.gs with form parameter
  google.script.run.withSuccessHandler(handlerFunction).doSomething(form);
}

//Handles the response from doSomething function
function handlerFunction(responseData) {
  //Logs ‘It worked!’ in developer console
  console.log(responseData);
}
</script>
</body>
</html>

code.gs

//Web App function
function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

//Apps script function to receive form object and return response
function doSomething(form) {
//Do something
  return ‘It worked!’;
}

Apps Script’s Web Apps are designed to be a single page application (one HTML page) and not a multi-page application, although there are different workaround examples you could guide from to achieve a multi-page behavior:

[1] Linking to another HTML page in Google Apps Script

[2] https://sites.google.com/corp/view/googlappsscript/recent-scripts/multiple-page-webapp-example


问:
Convert dictionary's array to array of dictionary
Is there any possible ways to convert the following structure into a given structure

Input:-

```<code>var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]
</code>```

Expected output:-

```<code>var result = [
    [
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ]
]
</code>```

答:
Here is a two step solution, first create an empty collection structure and then fill it with the values</p>

```<code>var converted: [[String: Int]] = []

for _ in 0..<dic.count {
    converted.append([:])
}

for (key, value) in dic {
    for (index, number) in value.enumerated() {
        converted[index][key] = number
    }
}
</code>```

Body:
Is there any possible ways to convert the following structure into a given structure

Input:-

var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]

Expected output:-

var result = [
    [
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ]
]

Body:
Here is a two step solution, first create an empty collection structure and then fill it with the values

var converted: [[String: Int]] = []

for _ in 0..<dic.count {
    converted.append([:])
}

for (key, value) in dic {
    for (index, number) in value.enumerated() {
        converted[index][key] = number
    }
}


问:
vector resizing - portable way to detect
I have a vector that I am loading with a know amount of elements (N).

The processing dynamically creates new elements, which are appended to the vector.

I am expecting about 2 * N additional elements to be created,
so I resize the vector to 3 * N.

If the additional elements exceed that, I would like a program abort, rather than a dynamic expansion of the vector.

Is there a way to detect that, that is portable between AIX/TRU64/Linux?

答:
Why are you using a vector?  The whole point of the vector is to dynamically expand when needed.

Instead of making a class to delegate to the vector, just make a class to delegate to a simple array.  Have your push_back check the size and abort when needed.

OwnerDisplayName: EvilTeach

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Ken


问:
Adding document to Sharepoint 2010 document list using List service
I am looking for an example in C#.net how to add document/file to sharepoint document list using its List service but didn't found any satisfactory example?

looking for an example to which I can refer.

Thanx!

答: I don't think you can use the List service for that. You will need to use the Copy webservice. Here is an example.</p>

ContentLicense: CC BY-SA 3.0


问:
Page service in spartacus?
If CMSService.getComponentData() is to get the component data (Component Controller in swagger).

May I know what service is needed to get page data with list of CMS content slots (Page Controller in swagger)?

答:
The CmsService from the core lib provides a method to get the current page, based on the current route:

CmsService.getCurrentPage()

This returns an observable with a Page.

Under the hood, the page is selected based on the page context, which has a page type (product, category, content) and id (product code, category code, search query).

Title: Page service in spartacus?


问:
How to sort a List of strings by multiple conditions
I have a List of strings that looks like this (completely unsorted):

```<code>[Title b] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title a] \t [text] \t complete
[Title c] \t [text] \t complete
...
</code>```

It shall be sorted to look like either this:

```<code>[Title a] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title b] \t [text] \t complete
[Title c] \t [text] \t complete
...
</code>```

Or this (which way it shall be sorted is selectable)

```<code>[Title a] \t [text] \t complete
[Title j] \t [text] \t complete
[Title s] \t [text] \t complete
...

[Title b] \t [text] \t incomplete
...
</code>```

My approach on this whole sorting thing is kinda dirty and not sleek at all and also only solves the second way of sorting.

```<code>List<string> sortedTps = new List<string>();
List<string> completeTps = new List<string>();
List<string> incompleteTps = new List<string>();
List<string> errorTps = new List<string>();

foreach (string tp in tpByProduct)
{
    if (tp.Contains("\t complete"))
    {
        completeTps.Add(tp);
    }
    else if (tp.Contains("\t incomplete"))
    {
        incompleteTps.Add(tp);
    }
 }

 completeTps.Sort();
 incompleteTps.Sort();

 foreach(string tp in completeTps)
 {
    sortedTps.Add(tp);
 }

 foreach(string tp in incompleteTps)
 {
    sortedTps.Add(tp);
 }
</code>```

Hope you guys can show me how to do this better and shorter ^^

答:
The Code you posted can be done with LINQ:

```<code>var sortedTps = tpByProduct.OrderBy(x => x.Contains("\t complete")).ThenBy(x => x).ToList();
</code>```

First it will sort after whether the string contains "\t complete", then it will sort after the string itself. In the end, the sorted result ist copied into a new list.

Body:
I have a List of strings that looks like this (completely unsorted):

[Title b] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title a] \t [text] \t complete
[Title c] \t [text] \t complete
...

It shall be sorted to look like either this:

[Title a] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title b] \t [text] \t complete
[Title c] \t [text] \t complete
...

Or this (which way it shall be sorted is selectable)

[Title a] \t [text] \t complete
[Title j] \t [text] \t complete
[Title s] \t [text] \t complete
...

[Title b] \t [text] \t incomplete
...

My approach on this whole sorting thing is kinda dirty and not sleek at all and also only solves the second way of sorting.

List<string> sortedTps = new List<string>();
List<string> completeTps = new List<string>();
List<string> incompleteTps = new List<string>();
List<string> errorTps = new List<string>();

foreach (string tp in tpByProduct)
{
    if (tp.Contains("\t complete"))
    {
        completeTps.Add(tp);
    }
    else if (tp.Contains("\t incomplete"))
    {
        incompleteTps.Add(tp);
    }
 }

 completeTps.Sort();
 incompleteTps.Sort();

 foreach(string tp in completeTps)
 {
    sortedTps.Add(tp);
 }

 foreach(string tp in incompleteTps)
 {
    sortedTps.Add(tp);
 }

Hope you guys can show me how to do this better and shorter ^^

Body:
The Code you posted can be done with LINQ:

var sortedTps = tpByProduct.OrderBy(x => x.Contains("\t complete")).ThenBy(x => x).ToList();

First it will sort after whether the string contains "\t complete", then it will sort after the string itself. In the end, the sorted result ist copied into a new list.


问:
$_FILES["imagefile"]["name"] return name but $_FILES["imagefile"]["tmp_name"] return null value?
In my case i was include enctype on myform like

```<code><form id="product_add" name="product_add" accept-charset="utf-8" action="product_add_inter.php" method="post" enctype="multipart/form-data">
</code>```

then my input type file is

```<code><input name="imagefile" class="form-control" type="file"   />
</code>```

Problem is in server side i need to upload my image to distination folder.I was tried to get file from form using

```<code>$_FILES["imagefile"]["name"]
</code>```

its worked and returned name of my image. But when i get the file using temp_name it return null values.

```<code>$_FILES["imagefile"]["tmp_name"]
</code>```

how can i solve this.

答:
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:

```<code>file_uploads = On
</code>```

Also did you check like that

```<code>echo '```'; print_r($_FILES);echo '```';
</code>```

and see the result. Are you getting file array and tmp_name?
check your php.ini file for file upload settings.

php.ini setting

Change the upload_max_filesize=2M to 8M

```<code>; Maximum allowed size for uploaded files.
upload_max_filesize = 8M

; Must be greater than or equal to upload_max_filesize
post_max_size = 8M
</code>```

Here is also solution
PHP file upload error tmp_name is empty

Body:
In my case i was include enctype on myform like

<form id="product_add" name="product_add" accept-charset="utf-8" action="product_add_inter.php" method="post" enctype="multipart/form-data">

then my input type file is

<input name="imagefile" class="form-control" type="file"   />

Problem is in server side i need to upload my image to distination folder.I was tried to get file from form using

$_FILES["imagefile"]["name"]

its worked and returned name of my image. But when i get the file using temp_name it return null values.

$_FILES["imagefile"]["tmp_name"]

how can i solve this.

Body:
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On

Also did you check like that

echo '<pre>'; print_r($_FILES);echo '</pre>';

and see the result. Are you getting file array and tmp_name?
check your php.ini file for file upload settings.

php.ini setting

Change the upload_max_filesize=2M to 8M

; Maximum allowed size for uploaded files.
upload_max_filesize = 8M

; Must be greater than or equal to upload_max_filesize
post_max_size = 8M

Here is also solution
PHP file upload error tmp_name is empty


问:
Multiple includes of the same source files through a project is correct?
I'm trying to call a method in my main, which is declared in another file.

When I try to call it with this line of code in the Main.c:

```<code>#include "SPI3.c"

void main(void) {

initSpi();

}
</code>```

it gives the following error:

```<code>SPI3.c:196:: error: (237) function "_initSpi" redefined
</code>```

The function is declared in the file SPI3.c

```<code>void initSpi()
{
     //CODE

}
</code>```

I've researched thoroughly my code and there is no redefinition of the function, and searching through the web I've seen that the error also appears when you call a function that is not declared yet or when
you include the same file more than once and it redefines the function.

I'm certain it's the former because I actually do more than one include of this file in the project, because I also need to call those methods in other files.

What am I doing wrong? There can only be one include of a source file in the whole project? Or is there another solution? Could it be that the function is just not initialized?

Thanks, feel free to ask for more details.

答:
By including any file, you paste its contents into your file. So, the function initSpi() is defined twice: within SPI3.c and Main.c => you get redefinition. You need to include only .h headers not .c files. These header files contain only declarations (opposed to definitions), e.g.:

```<code>/* SPI3.h */
void initSpi();
</code>```

So, we include header files into our file and get declarations of functions and variables that are defined elsewhere. In order to link their definitions, we can possibly need also a Makefile or a C project file.

Body:
I'm trying to call a method in my main, which is declared in another file.

When I try to call it with this line of code in the Main.c:

#include "SPI3.c"

void main(void) {

initSpi();

}

it gives the following error:

SPI3.c:196:: error: (237) function "_initSpi" redefined

The function is declared in the file SPI3.c

void initSpi()
{
     //CODE

}

I've researched thoroughly my code and there is no redefinition of the function, and searching through the web I've seen that the error also appears when you call a function that is not declared yet or when
you include the same file more than once and it redefines the function.

I'm certain it's the former because I actually do more than one include of this file in the project, because I also need to call those methods in other files.

What am I doing wrong? There can only be one include of a source file in the whole project? Or is there another solution? Could it be that the function is just not initialized?

Thanks, feel free to ask for more details.

Body:
By including any file, you paste its contents into your file. So, the function initSpi() is defined twice: within SPI3.c and Main.c => you get redefinition. You need to include only .h headers not .c files. These header files contain only declarations (opposed to definitions), e.g.:

/* SPI3.h */
void initSpi();

So, we include header files into our file and get declarations of functions and variables that are defined elsewhere. In order to link their definitions, we can possibly need also a Makefile or a C project file.


问:
Override the style in one component A when the component B is present on the view - Angular
I have two components on same level:

```<code><app-parent>
    <app-component-a></app-component-a>
    <app-component-b></app-component-b>
</app-parent>
</code>```

The Component-A:

Has the below styles:

```<code>:host {
    .container {
       height: 10rem;
     }
}
</code>```

But I want to change the height of the container of the component-a, when the component-b is present on the view. So let's say the componen-b is hidden and the default height from above can be used, but when component-b is visible the style below should override the height given above.

```<code>height: 2rem;
</code>```

Any suggestions on how to achieve this.
I have tried using the below on component-b but it doesn't help:

```<code>:host-context(.container) {
 height: 2rem;
}
</code>```

Have updated the code to make this work if there is a [ngClass] added to the code:

```<code><div class="container" [ngClass]="{'area-height': showArea}">
</code>```

Adding the Stackblitz code for easy understanding

Now I want to see if there is a way if we can connect the boolean value from the other component?
Added the random boolean generator, for now, to show/hide the component-b

答:
Maybe you can handle it using simple CSS? For example, you can make different style in case if component-a is last-child(see your modified example here):

```<code>:host {
  .container {
    height: 10rem;
    background: blueviolet;
  }
  .area-height{
    height: 2rem;
  }
}

// if component-b is present
:host:not(:last-child) {
  .container {
    height: 2rem;
  }
}
</code>```

Body:
I have two components on same level:

<app-parent>
    <app-component-a></app-component-a>
    <app-component-b></app-component-b>
</app-parent>

The Component-A:

Has the below styles:

:host {
    .container {
       height: 10rem;
     }
}

But I want to change the height of the container of the component-a, when the component-b is present on the view. So let's say the componen-b is hidden and the default height from above can be used, but when component-b is visible the style below should override the height given above.

height: 2rem;

Any suggestions on how to achieve this.
I have tried using the below on component-b but it doesn't help:

:host-context(.container) {
 height: 2rem;
}

Have updated the code to make this work if there is a [ngClass] added to the code:

Adding the Stackblitz code for easy understanding

Now I want to see if there is a way if we can connect the boolean value from the other component?
Added the random boolean generator, for now, to show/hide the component-b

Body:
Maybe you can handle it using simple CSS? For example, you can make different style in case if component-a is last-child(see your modified example here):

:host {
  .container {
    height: 10rem;
    background: blueviolet;
  }
  .area-height{
    height: 2rem;
  }
}

// if component-b is present
:host:not(:last-child) {
  .container {
    height: 2rem;
  }
}


问:
datepicker does not display months but days
Hello I have a problem with the datepicker. I see the days and not only the months I mean instead of having this :

I get this :

Here is my code :

```<code> <input type="text" id="datepicker" />
</code>```

and here is the js :

```<code>$("#datepicker").datepicker( {
    format: "mm-yyyy",
    viewMode: "months",
    minViewMode: "months"
});
</code>```

Could you help me please ?

Thank you very much !

答:
Hope this will help you:</p>

```<code>$('#you-date-picker-element').datepicker({
    autoclose: true,
    minViewMode: 1,
    orientation: 'left',
    container: '.your-date-picker-container',
    format: 'M-yyyy'
}).on('changeDate', function(selected){
    startDate = new Date(selected.date.valueOf());
    startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
    $('#your-field-name').datepicker('setStartDate', startDate);
});
</code>```

Body:
Hello I have a problem with the datepicker. I see the days and not only the months I mean instead of having this :

I get this :

Here is my code :

 <input type="text" id="datepicker" />

and here is the js :

$("#datepicker").datepicker( {
    format: "mm-yyyy",
    viewMode: "months",
    minViewMode: "months"
});

Could you help me please ?

Thank you very much !

Body:
Hope this will help you:

$('#you-date-picker-element').datepicker({
    autoclose: true,
    minViewMode: 1,
    orientation: 'left',
    container: '.your-date-picker-container',
    format: 'M-yyyy'
}).on('changeDate', function(selected){
    startDate = new Date(selected.date.valueOf());
    startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
    $('#your-field-name').datepicker('setStartDate', startDate);
});


问:
LINQ to return empty result
I want to write a LINQ to return empty list always. I can do that in SQL as

```<code>SELECT * FROM EMPLOYEES WHERE 1=2
</code>```

How to do it in LINQ?

My exact scenario is

```<code>private IQueryable <EMPLOYEE> getEmployee()
{
   IQueryable <EMPLOYEE> employees;

   //code

   if(condition)
   {
     return employees
   }
   else
   {
     //here I want to return a empty result.
   }
}
</code>```

答:
There is no need to hit database. You can use following:</p>

```<code>private IQueryable <EMPLOYEE> getEmployee()
{
    return Enumerable.Empty<EMPLOYEE>().AsQueryable();
}
</code>```

Title: LINQ to return empty result

Body:
I want to write a LINQ to return empty list always. I can do that in SQL as

SELECT * FROM EMPLOYEES WHERE 1=2

How to do it in LINQ?

My exact scenario is

private IQueryable <EMPLOYEE> getEmployee()
{
   IQueryable <EMPLOYEE> employees;

   //code

   if(condition)
   {
     return employees
   }
   else
   {
     //here I want to return a empty result.
   }
}

Body:
There is no need to hit database. You can use following:

private IQueryable <EMPLOYEE> getEmployee()
{
    return Enumerable.Empty<EMPLOYEE>().AsQueryable();
}


问:
Using catchError() inside the pipe() shows an error at the .subscribe variable
I wanted to handle the errors for a method in angular. I read that I can use the catchError() inside of the .pipe().
When I added an catchError check I get the variable roomId marked with the red squiggly line, which says TS2345: Argument of type 'unknown' is not assignable to parameter of type 'number'

This is the part where I do the error check.

```<code>this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
             if(error.status != 200){
               // handle error
             }else{
               // return error
               return throwError(error);
            }
         }),
</code>```

And here is the complete method.

```<code>public findRoom(room: Room): Observable<house> {
    return new Observable(house => {
      this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
                  if(error.status != 200){
                    // handle error
                  }else{
                    // return error
                    return throwError(error);
                  }
                }),
      ).subscribe(roomId =>
        this.gointToThisRoom(roomId).pipe( <----- roomId throws that argument type unknown
          first()
        ).subscribe(roomInfo => {
            if (roomInfo.status === "failed") {
              house.next(house.failed);
            } else {
              this.downloadRoom(roomId).pipe(
                first()
              ).subscribe(blobFile =>
                this.getRoom(blobFile, name)
              );
              house.next(house.ready)
            }
          }
        )
      )
    });
  }
</code>```

Any idea why this is the case?

答:
catchError expects you to return an observable, which can be throwError or, if you handled it, a new observable as a fallback value.

In your case you could do something like this:

```<code>import { of } from 'rxjs';
</code>```

...

```<code>catchError((error: HttpErrorResponse) => {
  if (error.status != 200) {
    // handle error and use any value you like to return if that's your goal.
    // This could be anything, like a number, string or an object, depending on your use-case.
    const fallbackValue: Room = { properties... };
    return of(fallbackValue); // You will get this in your subscription callback
  } else {
    // return error
    return throwError(error);
  }
}),
</code>```

Body:
I wanted to handle the errors for a method in angular. I read that I can use the catchError() inside of the .pipe().
When I added an catchError check I get the variable roomId marked with the red squiggly line, which says TS2345: Argument of type 'unknown' is not assignable to parameter of type 'number'

This is the part where I do the error check.

this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
             if(error.status != 200){
               // handle error
             }else{
               // return error
               return throwError(error);
            }
         }),

And here is the complete method.

public findRoom(room: Room): Observable<house> {
    return new Observable(house => {
      this.firstRoom(room).pipe(
        first(),
        catchError((error: HttpErrorResponse)=>{
                  if(error.status != 200){
                    // handle error
                  }else{
                    // return error
                    return throwError(error);
                  }
                }),
      ).subscribe(roomId =>
        this.gointToThisRoom(roomId).pipe( <----- roomId throws that argument type unknown
          first()
        ).subscribe(roomInfo => {
            if (roomInfo.status === "failed") {
              house.next(house.failed);
            } else {
              this.downloadRoom(roomId).pipe(
                first()
              ).subscribe(blobFile =>
                this.getRoom(blobFile, name)
              );
              house.next(house.ready)
            }
          }
        )
      )
    });
  }

Any idea why this is the case?

Body:
catchError expects you to return an observable, which can be throwError or, if you handled it, a new observable as a fallback value.

In your case you could do something like this:

import { of } from 'rxjs';

...

catchError((error: HttpErrorResponse) => {
  if (error.status != 200) {
    // handle error and use any value you like to return if that's your goal.
    // This could be anything, like a number, string or an object, depending on your use-case.
    const fallbackValue: Room = { properties... };
    return of(fallbackValue); // You will get this in your subscription callback
  } else {
    // return error
    return throwError(error);
  }
}),


问:
Remove specific cookie from session python requests
Remove specific cookie from session python requests.

Only found

```<code>s.cookies.clear()
</code>```

Would like to ONLY remove a specific cookie. e.g. s.cookies['basketid']

答:
A simple delete should work, the syntax would be

del s.cookies['basketid']
```

Body:
Remove specific cookie from session python requests.

Only found

s.cookies.clear()

Would like to ONLY remove a specific cookie. e.g. s.cookies['basketid']


问:
Turn off auto formatting for json files in Visual Studio Code
I have checked my preference multiple times and ensured that all options related to format-on-save are set to false. And yet everytime I save a .json file I see my file getting formatted.</p>

答:
In addition to answers here, there are settings other than "editor.formatOnSave" that might be having a similar effect, which you might also want to disable - for example, I had enabled the following in my User Preferences (settings.json):

```<code>"editor.codeActionsOnSave": {
  "source.organizeImports": true
},
</code>```

Body:
In addition to answers here, there are settings other than "editor.formatOnSave" that might be having a similar effect, which you might also want to disable - for example, I had enabled the following in my User Preferences (settings.json):

"editor.codeActionsOnSave": {
  "source.organizeImports": true
},


问:
Downloading multiple files writes same data to all files
Attempting to download multiple files from an XML feed. There are several Categories and each category has an unknown amount of images. I create a subdirectory for each category, no problem. When I try to download each file to the respective category, every file is written with the same data for every image there is in the feed.

I guess my question is how can I download 1 file at a time to the corresponding directory without overwriting all of the images with the same data?

```<code>-(void)parsingComplete:(XMLDataSource*)theParser
{
    /*  iterate through the Categories and create the
        sub-directory if it does not exist
     */

    for (int i = 0; i < [categories count]; i++)
    {
        NSString *cat      = [NSString stringWithFormat:@"%@/%@",BASE_DIR,[[categories objectAtIndex:i] objectForKey:@"name"]];
        NSString *catName  = [[categories objectAtIndex:i] objectForKey:@"name"];
        NSArray  *catArray = [[categories objectAtIndex:i] objectForKey:@"images"];

        /*  create the sub-direcotry naming it the #category# key  */
        if (![FILEMANAGER fileExistsAtPath:cat]) {
            [FILEMANAGER createDirectoryAtPath:cat withIntermediateDirectories:NO attributes:nil error:nil];
        }

        //NSLog(@"\n\nCategory: %@",cat);
        for (int x = 0; x < [catArray count]; x++)
        {
            /*  download each file to the corresponding category sub-directory  */

            fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];

            NSURLRequest * imageRequest =
            [NSURLRequest requestWithURL:[NSURL URLWithString:[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]]
                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
            [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self];
        }
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [receivedData writeToFile:fileOut atomically:YES];
}
</code>```

答:
Yes, this is what I mentioned in my comment. Each time connectionDidFinishLoading: is called, you've got the result of just one connection. If you loop through all the file names, you will write that same chunk of data out to all those names, repeatedly. Each time through the for loop in parsingComplete: you create a new connection, get a new data object, and then write that same object out multiple times. After the end of the parsing... loop, you're left with a list of files all with the data from the last connection.

I'm pretty tired and I'm not sure: am I being clear?

Addressing your comment:

You'll either have to make the correct file name for the current connection available to the delegate methods, probably by putting it in an ivar, or go the synchronous route. Putting in it in some ivar like currFileName so that all the methods in this class can access it is probably the least painless way to get the job done.

```<code>/* In parsingCompleted: */
for (int x = 0; x < [catArray count]; x++)
{
    /*  download each file to the corresponding category sub-directory  */
    // fileOut is an instance variable
    fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];
    imageRequest = [NSURLRequest etc...
</code>```

```<code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // No loop; just use that file name that you set up earlier;
    // it correctly corresponds to the current NSURLConnection
    [receivedData writeToFile:fileOut atomically:YES];
</code>```

Body:
Attempting to download multiple files from an XML feed. There are several Categories and each category has an unknown amount of images. I create a subdirectory for each category, no problem. When I try to download each file to the respective category, every file is written with the same data for every image there is in the feed.

I guess my question is how can I download 1 file at a time to the corresponding directory without overwriting all of the images with the same data?

-(void)parsingComplete:(XMLDataSource*)theParser
{
    /*  iterate through the Categories and create the
        sub-directory if it does not exist
     */

    for (int i = 0; i < [categories count]; i++)
    {
        NSString *cat      = [NSString stringWithFormat:@"%@/%@",BASE_DIR,[[categories objectAtIndex:i] objectForKey:@"name"]];
        NSString *catName  = [[categories objectAtIndex:i] objectForKey:@"name"];
        NSArray  *catArray = [[categories objectAtIndex:i] objectForKey:@"images"];

        /*  create the sub-direcotry naming it the #category# key  */
        if (![FILEMANAGER fileExistsAtPath:cat]) {
            [FILEMANAGER createDirectoryAtPath:cat withIntermediateDirectories:NO attributes:nil error:nil];
        }

        //NSLog(@"\n\nCategory: %@",cat);
        for (int x = 0; x < [catArray count]; x++)
        {
            /*  download each file to the corresponding category sub-directory  */

            fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];

            NSURLRequest * imageRequest =
            [NSURLRequest requestWithURL:[NSURL URLWithString:[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]]
                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
            [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self];
        }
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [receivedData writeToFile:fileOut atomically:YES];
}

Body:
Yes, this is what I mentioned in my comment. Each time connectionDidFinishLoading: is called, you've got the result of just one connection. If you loop through all the file names, you will write that same chunk of data out to all those names, repeatedly. Each time through the for loop in parsingComplete: you create a new connection, get a new data object, and then write that same object out multiple times. After the end of the parsing... loop, you're left with a list of files all with the data from the last connection.

I'm pretty tired and I'm not sure: am I being clear?

Addressing your comment:

You'll either have to make the correct file name for the current connection available to the delegate methods, probably by putting it in an ivar, or go the synchronous route. Putting in it in some ivar like currFileName so that all the methods in this class can access it is probably the least painless way to get the job done.

/* In parsingCompleted: */
for (int x = 0; x < [catArray count]; x++)
{
    /*  download each file to the corresponding category sub-directory  */
    // fileOut is an instance variable
    fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];
    imageRequest = [NSURLRequest etc...

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // No loop; just use that file name that you set up earlier;
    // it correctly corresponds to the current NSURLConnection
    [receivedData writeToFile:fileOut atomically:YES];


问:
Best way to convert String to Boolean in Java
I currently have a question about the database of my work.

They use a String based on 0 and 1 to indicate whether it is active or not. But for my logic I would like to use true or false.

Why? Because have redundant code. For example:

```<code>if(foo.getStateClient().equals("1"))
   //Do things...
</code>```

Imagine that with 6 or 7 fields more.

Cant modify the database. And I dont know if use Strings like the before example, or do anything to cast the String a Boolean.

And, always the state is 0 or 1

I appreciate any advice to be more optimal

Edit 1
I am not asking how doing, i am asking the Best practice to do that.

I am using Spring with Hibernate that for people ask me what ORM i am using.

答:
Just create a helper method that you can reuse for this type of thing

i.e.

public class BooleanHelper {

    public static boolean fromString(String value) {
        if (value == null) {
            return false;
        }
        if ("1".equals(value) || "true".equalsIgnoreCase(value)) {
            return true;
        }
        return false;
    }

}
```

<p>that way you you can use it where ever you need</p>

<pre class="lang-java prettyprint-override"><code>if(BooleanHelper.fromString(foo.getStateClient()))
   //Do things...

</code>```

You could also statically import the method, to reduce your boilerplate

EDIT: OP indicated using Spring and Hibernate

As you have indicated you are using Spring and Hibernate, you can create an AttributeConverter for this

public class BooleanAttributeConverter implements AttributeConverter<Boolean, String> {
    @Override
    public String convertToDatabaseColumn(Boolean value) {
        if (value == null) {
            return "0";
        }
        return value ? "1" : "0";
    }

    @Override
    public Boolean convertToEntityAttribute(String value) {
        if (value == null) {
            return false;
        }
        if ("1".equals(value) || "true".equalsIgnoreCase(value)) {
            return true;
        }
        return false;
    }
}
```

<p>Then specify this on your entity </p>

<pre class="lang-java prettyprint-override"><code>@Entity
public class Foo {

    @Column
    @Convert(converter = BooleanAttributeConverter.class)
    private boolean stateClient;

    public boolean isStateClient() {
        return stateClient;
    }

    public void setStateClient(boolean stateClient) {
        this.stateClient = stateClient;
    }
}
</code>```

Body:
I currently have a question about the database of my work.

They use a String based on 0 and 1 to indicate whether it is active or not. But for my logic I would like to use true or false.

Why? Because have redundant code. For example:

if(foo.getStateClient().equals("1"))
   //Do things...

Imagine that with 6 or 7 fields more.

Cant modify the database. And I dont know if use Strings like the before example, or do anything to cast the String a Boolean.

And, always the state is 0 or 1

I appreciate any advice to be more optimal

Edit 1
I am not asking how doing, i am asking the Best practice to do that.

I am using Spring with Hibernate that for people ask me what ORM i am using.

Body:
Just create a helper method that you can reuse for this type of thing

i.e.

public class BooleanHelper {

    public static boolean fromString(String value) {
        if (value == null) {
            return false;
        }
        if ("1".equals(value) || "true".equalsIgnoreCase(value)) {
            return true;
        }
        return false;
    }

}

that way you you can use it where ever you need

if(BooleanHelper.fromString(foo.getStateClient()))
   //Do things...

You could also statically import the method, to reduce your boilerplate

EDIT: OP indicated using Spring and Hibernate

As you have indicated you are using Spring and Hibernate, you can create an AttributeConverter for this

public class BooleanAttributeConverter implements AttributeConverter<Boolean, String> {
    @Override
    public String convertToDatabaseColumn(Boolean value) {
        if (value == null) {
            return "0";
        }
        return value ? "1" : "0";
    }

    @Override
    public Boolean convertToEntityAttribute(String value) {
        if (value == null) {
            return false;
        }
        if ("1".equals(value) || "true".equalsIgnoreCase(value)) {
            return true;
        }
        return false;
    }
}

Then specify this on your entity

@Entity
public class Foo {

    @Column
    @Convert(converter = BooleanAttributeConverter.class)
    private boolean stateClient;

    public boolean isStateClient() {
        return stateClient;
    }

    public void setStateClient(boolean stateClient) {
        this.stateClient = stateClient;
    }
}


问:
How do I get a reflection on a property's property in Kotlin?
say we have a class with a property subClass.

```<code>class TestClass(val property: SubClass)
</code>```

The SubClass has its own property

```<code>class SubClass(val subProperty: Any?)
</code>```

When I only have access to the class itself, I know that I can easily get a reflection to the property via

```<code>val reflection = TestClass::property
</code>```

However, how do I get access to the subProperty via reflection? The following does not work:

```<code>val subReflection = TestClass::property::subProperty
</code>```

I'd apprectiate any insight on that! Thanks!

答:
```<code>TestClass::property.returnType.jvmErasure
</code>```

will give you SubClass::class, so you can do something like

```<code>val subReflection = TestClass::property.returnType.jvmErasure.declaredMemberProperties.find { it.name == "subProperty" }!!
</code>```

(!! to simplify code, you may want to actually check for null in practice.)

Body:
say we have a class with a property subClass.

class TestClass(val property: SubClass)

The SubClass has its own property

class SubClass(val subProperty: Any?)

When I only have access to the class itself, I know that I can easily get a reflection to the property via

val reflection = TestClass::property

However, how do I get access to the subProperty via reflection? The following does not work:

val subReflection = TestClass::property::subProperty

I'd apprectiate any insight on that! Thanks!

Body:
TestClass::property.returnType.jvmErasure

will give you SubClass::class, so you can do something like

val subReflection = TestClass::property.returnType.jvmErasure.declaredMemberProperties.find { it.name == "subProperty" }!!

(!! to simplify code, you may want to actually check for null in practice.)


问:
React Cannot read property 'lastName' of undefined
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}
</code>```

API2 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}
</code>```

Merged API look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}
</code>```

Fetched data:

```<code>const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});
</code>```

答:
You can use inline || operator:

```<code>${d.lastName || ""}
</code>```

Also you have to change the object here:

```<code>return  object.name === getData.name; //<----change here.
</code>```

Body:
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}

API2 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}

Merged API look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}

Fetched data:

const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});

Body:
You can use inline || operator:

${d.lastName || ""}

Also you have to change the object here:

return  object.name === getData.name; //<----change here.


问:
Move seaborn plot legend to a different position
I'm using factorplot(kind="bar") with seaborn.

The plot is fine except the legend is misplaced: too much to the right, text goes out of the plot's shaded area.

How do I make seaborn place the legend somewhere else, such as in top-left instead of middle-right?

答:
If you wish to customize your legend, just use the add_legend method. It takes the same parameters as matplotlib plt.legend.

```<code>import seaborn as sns
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                    data=titanic, kind="bar",
                    size=6, palette="muted",
                   legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")
g.add_legend(bbox_to_anchor=(1.05, 0), loc=2, borderaxespad=0.)
</code>```

Body:
If you wish to customize your legend, just use the add_legend method. It takes the same parameters as matplotlib plt.legend.

import seaborn as sns
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                    data=titanic, kind="bar",
                    size=6, palette="muted",
                   legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")
g.add_legend(bbox_to_anchor=(1.05, 0), loc=2, borderaxespad=0.)


问:
Is the rule of ReactJS re-rendering just: if the state of component changes, then the whole sub-tree is re-rendered?
First of all, by "re-render", here it means either

the render() method of any class component is called, OR

the function of the function component is called.

Let's called the element in the actual DOM changing a "refresh", to distinguish it from "re-render".

Is the rule of "re-render" as simple as:

When any state of a component is changed, then the component and all the subtree down from this component is re-rendered

and that's it?  For example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div></code>```

Component A is so simple: it doesn't even take any props and is just outputting static text, yet it is still called every time (by looking at the console.log() output).

But even though it is "re-rendered", the actual DOM element is not "refreshed", as seen in Google Chrome's Inspect Element that the DOM element is not flashing for Component A, but is only flashing for the counter number.

So is this how it works?

Whenever any state of a component is changed, that component and the whole subtree will be "re-rendered".

But ReactJS will "reconcile" the content of the "Virtual DOM" that it built using those JSX with the content of the actual DOM, and if the content is different, "refresh the actual DOM".

But having said that, it seems ReactJS doesn't actually reconcile with the actual DOM, but reconcile with probably the "previous virtual DOM". Why?  Because if I use a setTimeout() to change the actual DOM of Component A to some other content after 3 seconds, and click the button, ReactJS doesn't change the content of Component A back to "Hello World". Example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

setTimeout(function() {
  document.querySelector("#foo").innerText = "hi"
}, 3000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div></code>```

答:
After reading the React docs on Reconciliation, it seems a simplified way to think about it is:

Whenever the props provided to the component COMPO1 or the state of this component changes, then all the render() of class components and the function components under COMPO1 are called, to form a virtual DOM tree, and the whole subtree is compared to the previous subtree -- not to the actual DOM but to a previous virtual DOM subtree

It is compared to see if the nodes are different and recursively do that for all children.

Only the minimum subtrees from the component and down that are different would cause a refresh of content to the actual DOM -- meaning if node A has children B and C, and B stayed the same while node C became different, then only C will cause that part of the actual DOM to be refreshed. (of course if node C has node D and E and D stayed the same while E became different, then only E is refreshed to actual DOM).

Body:
First of all, by "re-render", here it means either

the render() method of any class component is called, OR

the function of the function component is called.

Let's called the element in the actual DOM changing a "refresh", to distinguish it from "re-render".

Is the rule of "re-render" as simple as:

When any state of a component is changed, then the component and all the subtree down from this component is re-rendered

and that's it?  For example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

Component A is so simple: it doesn't even take any props and is just outputting static text, yet it is still called every time (by looking at the console.log() output).

But even though it is "re-rendered", the actual DOM element is not "refreshed", as seen in Google Chrome's Inspect Element that the DOM element is not flashing for Component A, but is only flashing for the counter number.

So is this how it works?

Whenever any state of a component is changed, that component and the whole subtree will be "re-rendered".

But ReactJS will "reconcile" the content of the "Virtual DOM" that it built using those JSX with the content of the actual DOM, and if the content is different, "refresh the actual DOM".

But having said that, it seems ReactJS doesn't actually reconcile with the actual DOM, but reconcile with probably the "previous virtual DOM". Why?  Because if I use a setTimeout() to change the actual DOM of Component A to some other content after 3 seconds, and click the button, ReactJS doesn't change the content of Component A back to "Hello World". Example:

function A() {
  console.log("Component A re-render");

  return
Component A says Hello World
;
}

function App() {
  const [counter, setCounter] = React.useState(0);

  console.log("Component App re-render");

  function increaseCount() {
    setCounter(c => c + 1);
  }

  return (

      {counter}
      <button onClick={increaseCount} >Increment</button>

  )
}

ReactDOM.render(<App />, document.querySelector("#root"));

setTimeout(function() {
  document.querySelector("#foo").innerText = "hi"
}, 3000);


问:
empty textbox controls after the data is inserted / saved/ submitted in a c# winform application
I need to empty all the textbox controls after the SAVE button is clicked but the user. I have around 10 of them. How do i clear text from them all simultaneously. I just know about:

```<code>textbox1.Text="";
</code>```

But, if i do this, then i need to repeat this for the no. of textbox controls on my Form, that would be a labor task instead of programmer?

Please guide.

答:
You could use the Linq API described in the following article:

http://www.codeproject.com/KB/linq/LinqToTree.aspx#linqforms

This allows you to apply Linq-to-XML style queries on Windows Forms. The following will clear all the TextBox controls that are descendants of 'this':

```<code>foreach(TextBox textbox in this.Descendants<TextBox>()
                               .Cast<TextBox>())
{
   textbox.Text = string.Empty;
}
</code>```

Body:
I need to empty all the textbox controls after the SAVE button is clicked but the user. I have around 10 of them. How do i clear text from them all simultaneously. I just know about:

textbox1.Text="";

But, if i do this, then i need to repeat this for the no. of textbox controls on my Form, that would be a labor task instead of programmer?

Please guide.

Body:
You could use the Linq API described in the following article:

http://www.codeproject.com/KB/linq/LinqToTree.aspx#linqforms

This allows you to apply Linq-to-XML style queries on Windows Forms. The following will clear all the TextBox controls that are descendants of 'this':

foreach(TextBox textbox in this.Descendants<TextBox>()
                               .Cast<TextBox>())
{
   textbox.Text = string.Empty;
}


问:
convert to unsigned char and unsigned short in Android
I have to convert my bytes to unsigned char and unsigned short , it is done like this  in iOS

```<code>latitude = (unsigned char)(bytebuffr.getchar(0)) + ((unsigned short)(bytebuffr.getchar(1)& 0xF)) << 8);
</code>```

How can I achieve this in my android code. please help
already tried this in android but not working,

```<code>lattitude = (short) ((getUnsignedByte((byte) (bb.getChar(0) & 0xFF))) +
                    getUnsignedByte((byte) ((bb.getChar(1) & 0x0F))) << 8);
</code>```

bb is bytebuffer and bb.getchar is giving me the bytes which is being read from bytebuffer

答:
You don't need to convert from char to short in this case. Since bb is a ByteBuffer, use getShort if you want to read two bytes from the buffer and use them as a signed 16-bit number. Use getChar if you need to read two bytes from the buffer (not one!) and use them as an unsigned 16-bit number. I suspect you're thinking that getChar only reads a single byte. It doesn't. char is 16 bits wide. Also, char is an unsigned integral type in Java. Although it's used to represent characters (loosely) in strings, it's an integral (whole number) type. The integral types are:

byte: 8-bit signed: -128 to 127, inclusive

short: 16-bit signed; -32768 to 32767, inclusive

char: 16-bit unsigned: 0 to 65535, inclusive (aka '\u0000' to '\uffff')

int: 32-bit signed: -2147483648 to 2147483647, inclusive

long: 32-bit signed: -9223372036854775808 to 9223372036854775807, inclusive

If you did need to convert: char is an unsigned 16-bit type. short is a signed 16-bit type. To use the same bits in a short as you have in a char, you do this:

```<code>short s = (short)ch;
</code>```

No need for masking off the first byte or anything like that.

Body:
I have to convert my bytes to unsigned char and unsigned short , it is done like this  in iOS

latitude = (unsigned char)(bytebuffr.getchar(0)) + ((unsigned short)(bytebuffr.getchar(1)& 0xF)) << 8);

How can I achieve this in my android code. please help
already tried this in android but not working,

lattitude = (short) ((getUnsignedByte((byte) (bb.getChar(0) & 0xFF))) +
                    getUnsignedByte((byte) ((bb.getChar(1) & 0x0F))) << 8);

bb is bytebuffer and bb.getchar is giving me the bytes which is being read from bytebuffer

Body:
You don't need to convert from char to short in this case. Since bb is a ByteBuffer, use getShort if you want to read two bytes from the buffer and use them as a signed 16-bit number. Use getChar if you need to read two bytes from the buffer (not one!) and use them as an unsigned 16-bit number. I suspect you're thinking that getChar only reads a single byte. It doesn't. char is 16 bits wide. Also, char is an unsigned integral type in Java. Although it's used to represent characters (loosely) in strings, it's an integral (whole number) type. The integral types are:

byte: 8-bit signed: -128 to 127, inclusive

short: 16-bit signed; -32768 to 32767, inclusive

char: 16-bit unsigned: 0 to 65535, inclusive (aka '\u0000' to '\uffff')

int: 32-bit signed: -2147483648 to 2147483647, inclusive

long: 32-bit signed: -9223372036854775808 to 9223372036854775807, inclusive

If you did need to convert: char is an unsigned 16-bit type. short is a signed 16-bit type. To use the same bits in a short as you have in a char, you do this:

short s = (short)ch;

No need for masking off the first byte or anything like that.


问:
iOS Application: Firebase Dynamic Links are not working with latest Pod file
We integrated the latest Dynamic link Pod to our iOS application.

Whenever we open the link of firebase no function in triggered in our Appdelegate.
Check the method we implemented in App delegate

```<code>    func application(_ application: UIApplication, continue userActivity: NSUserActivity,     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
 DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
     if(dynamiclink != nil){
         let aStr = dynamiclink!.url!.absoluteString
         print("reopen url :\(String(describing: aStr.removingPercentEncoding))")
         let decodeUrl = aStr.removingPercentEncoding!
     }
 }
 return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
 print("got link1")
 print(" first time url :\(url)")
 let aStr = url.absoluteString
 print("url :\(String(describing: aStr.removingPercentEncoding))")
 let decodeUrl = aStr.removingPercentEncoding!
 if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
     if dynamicLink.url != nil{
         let aStr = dynamicLink.url!.absoluteString
         let decodUrl = aStr.removingPercentEncoding!
     }
 }
return true }
</code>```

We are using a custom domain in our application, we added them in info.plist too

```<code><key>FirebaseDynamicLinksCustomDomains</key>
<array>
    <string>https://page.google.com/newrequest</string>
</array>
<key>FirebaseAppDelegateProxyEnabled</key>
<string>YES</string>
</code>```

We added a dynamic link URL to our AssociatedDomains with a prefix of app links like applinks:page.google.com

答:
Try this: https://stackoverflow.com/a/59765601/2781088 This might solve your initial problem for DL and follow the below code for the problem mentioned in the comments.

You can get the URL in the following functions (Add these methods into your App Delegate):

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    if DynamicLinks.dynamicLinks().shouldHandleDynamicLink(fromCustomSchemeURL: url) {
            let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url)
            self.handleDynamicLink(dynamicLink)
            return true
    }
}
</code>```

And

```<code>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if let incomingURL = userActivity.webpageURL {
            print(incomingURL)

            let linkHandled = DynamicLinks.dynamicLinks().handleUniversalLink(incomingURL) { (dynamicLink, error) in
                guard error == nil else {
                    print("Found an error! \(error!.localizedDescription)")
                    return
                }

                if let dynamicLink = dynamicLink {
                    self.handleDynamicLink(dynamicLink)
                }
            }

            if linkHandled {
                return true
            }
            else {
                //May be do other things with our incoming URL?
                return false
            }
        }

        return false
    }
</code>```

handleDynamicLink method:

```<code>func handleDynamicLink(_ dynamicLink: DynamicLink?) {
        guard let dynamicLink = dynamicLink else { return }
        guard let deepLink = dynamicLink.url else { return }
    }
</code>```

Don't forget to add this:

Hope that will solve your issue.

Body:
We integrated the latest Dynamic link Pod to our iOS application.

Whenever we open the link of firebase no function in triggered in our Appdelegate.
Check the method we implemented in App delegate

    func application(_ application: UIApplication, continue userActivity: NSUserActivity,     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
 DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
     if(dynamiclink != nil){
         let aStr = dynamiclink!.url!.absoluteString
         print("reopen url :\(String(describing: aStr.removingPercentEncoding))")
         let decodeUrl = aStr.removingPercentEncoding!
     }
 }
 return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
 print("got link1")
 print(" first time url :\(url)")
 let aStr = url.absoluteString
 print("url :\(String(describing: aStr.removingPercentEncoding))")
 let decodeUrl = aStr.removingPercentEncoding!
 if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
     if dynamicLink.url != nil{
         let aStr = dynamicLink.url!.absoluteString
         let decodUrl = aStr.removingPercentEncoding!
     }
 }
return true }

We are using a custom domain in our application, we added them in info.plist too

<key>FirebaseDynamicLinksCustomDomains</key>
<array>
    <string>https://page.google.com/newrequest</string>
</array>
<key>FirebaseAppDelegateProxyEnabled</key>
<string>YES</string>

We added a dynamic link URL to our AssociatedDomains with a prefix of app links like applinks:page.google.com

Body:
Try this: https://stackoverflow.com/a/59765601/2781088 This might solve your initial problem for DL and follow the below code for the problem mentioned in the comments.

You can get the URL in the following functions (Add these methods into your App Delegate):

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    if DynamicLinks.dynamicLinks().shouldHandleDynamicLink(fromCustomSchemeURL: url) {
            let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url)
            self.handleDynamicLink(dynamicLink)
            return true
    }
}

And

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if let incomingURL = userActivity.webpageURL {
            print(incomingURL)

            let linkHandled = DynamicLinks.dynamicLinks().handleUniversalLink(incomingURL) { (dynamicLink, error) in
                guard error == nil else {
                    print("Found an error! \(error!.localizedDescription)")
                    return
                }

                if let dynamicLink = dynamicLink {
                    self.handleDynamicLink(dynamicLink)
                }
            }

            if linkHandled {
                return true
            }
            else {
                //May be do other things with our incoming URL?
                return false
            }
        }

        return false
    }

handleDynamicLink method:

func handleDynamicLink(_ dynamicLink: DynamicLink?) {
        guard let dynamicLink = dynamicLink else { return }
        guard let deepLink = dynamicLink.url else { return }
    }

Don't forget to add this:

Hope that will solve your issue.


问:
image alignment has when the website is hosted
I have a column where the images are aligned in the center when it is locally seen when I hosted the alignment of the images changed

This is the image when it is locally hosted

and this is the remote host image

This is the code I have tried

```<code><div class="col-lg-3 col-md-12 px-sm-0 px-4 w3_agile-footer1 f3 powered">
    <h5 class="mb-3">Powered By</h5>
    <ul class="tweet-agile" style="list-style: none; text-align: center;">
        <li>
            <img class="vivox" src="rummy_den\payment\vivox.jpeg" alt="">
        </li>
        <li>
            <img class="secure" src="rummy_den\payment\secure.jpeg" alt="">
        </li>
    </ul>
</div>
</code>```

This is the CSS part of that section

```<code>ul.tweet-agile span.fab {
    width: 25px;
    color: pink;
    padding-left: 0;
}
.tweet-agile {
    height: 100px;
    width: 100px;
    margin-bottom: 10px;
    margin-left: 12px;
}
@media (min-width:425px) {
    .tweet-agile {
        margin-left: 63px !important;
    }
}

@media (min-width:375px) and (max-width:425px) {
    .tweet-agile {
        margin-left: 75px !important;
    }
}
</code>```

Where did I go wrong?

update: it is perfect when I viewed in the desktop all the dimensions as shown below

But when I check in my mobile it is not aligned as shown in image

答:
Please add these styles under media query, issue is with unwanted margin you were using to style the images to middle.

```<code>@media (min-width: 425px){
  .tweet-agile {
    height: 100px;
    width: 100px;
    width: 100%;
    padding: 0;
    margin-left: 0;
   }
  .tweet-agile img {
    margin-left: 0 !important;
   }
}
</code>```

and remove

```<code>@media (min-width:425px) {
    .tweet-agile {
        margin-left: 63px !important;
    }
}

@media (min-width:375px) and (max-width:425px) {
    .tweet-agile {
        margin-left: 75px !important;
    }
}
</code>```

Body:
I have a column where the images are aligned in the center when it is locally seen when I hosted the alignment of the images changed

This is the image when it is locally hosted

and this is the remote host image

This is the code I have tried

Powered By

This is the CSS part of that section

ul.tweet-agile span.fab {
    width: 25px;
    color: pink;
    padding-left: 0;
}
.tweet-agile {
    height: 100px;
    width: 100px;
    margin-bottom: 10px;
    margin-left: 12px;
}
@media (min-width:425px) {
    .tweet-agile {
        margin-left: 63px !important;
    }
}

@media (min-width:375px) and (max-width:425px) {
    .tweet-agile {
        margin-left: 75px !important;
    }
}

Where did I go wrong?

update: it is perfect when I viewed in the desktop all the dimensions as shown below

But when I check in my mobile it is not aligned as shown in image

Body:
Please add these styles under media query, issue is with unwanted margin you were using to style the images to middle.

@media (min-width: 425px){
  .tweet-agile {
    height: 100px;
    width: 100px;
    width: 100%;
    padding: 0;
    margin-left: 0;
   }
  .tweet-agile img {
    margin-left: 0 !important;
   }
}

and remove

@media (min-width:425px) {
    .tweet-agile {
        margin-left: 63px !important;
    }
}

@media (min-width:375px) and (max-width:425px) {
    .tweet-agile {
        margin-left: 75px !important;
    }
}


问:
Using a Power BI Custom Shape Map
I have been trying to use a custom shape map in Power BI and I can not get it to work.
The idea behind all this is to start from a .shp file, .dbf file and a .prj file and export it to a TopoJson file that actually works in Power BI in order to show the difference between County through color saturation.

I have been using the https://mapshaper.org site in order to do this.

This are the files that I have started from:

https://drive.google.com/open?id=17EtWd5YqEV4k5ctuJIFI9JDJIK8joCnG

This is what I would like it to work in Power BI with:

Map Shaper .shp file without .dbf file

I found this information that may have helped me if I could understand it

Power BI. Using custom map as base map

https://moriartynaps.org/

答:
From using mapshaper you should be left with a topojson file, this json file I'm going to assume you have already imported into Power BI in the shape map visual.

Within the topojson file, each of the individual sections of that map "should" be assigned an ID or identifier. So view the json file in a text/scripting editor to identify these.

Import your dataset into Power BI and then you will need to map each of the datavalues to the identifier. Obviously, how you do this is up to you...You could write a huge "if/else" dax formula if you wanted to, but the key thing is that each row of imported data has another column with an equivalent ID for the json file.

Title: Using a Power BI Custom Shape Map


问:
How can I delete the SQLite DLL when I'm finished with it if the OS thinks it's still in use?
How can I unlock or delete a file that is in use, so that I can delete it? The file in question is used by my own application.

More specifically, my application is using the freeware Zeos Lib. When opening and saving my database the sqlite3.dll file must reside in the same directory as my application to work correctly.

I want my application to be 100% standalone, so I have added the sqlite3.dll as RC_DATA to my project, and whenever I need to use it (ie, open or save database), I extract it to the same folder as my application. Once the open or save operation has completed, I would like to delete the sqlite3.dll file, and no one would even know it was there or have to worry about missing libraries etc. (While I can appreciate that some of you may not like the idea of storing the libraries inside the application, I have my reasons for doing this: I don't want my end-users knowing what is behind the functioning of my application (SQL), and they also don't need to worry about missing dynamic link libraries.)

The problem is, I can successfully extract the sqlite3.dll and use it for my operations, but the file becomes locked by my application (until I close my application), which brings me to either:

Force unlock the sqlite3.dll file, without closing my application

Force delete the sqlite3.dll file

Unless of course there is another suggestion?

Here is a sample of extracting and using it. No direct calls need to be made such as LoadLibrary etc from my part; the Zeos Lib units must take care of this, so long as the sqlite3.dll is in the same directory as the application.

```<code>procedure ExtractResource(ResName: String; Filename: String);
var
  ResStream: TResourceStream;
begin
  ResStream:= TResourceStream.Create(HInstance, ResName, RT_RCDATA);
  try
    ResStream.Position:= 0;
    ResStream.SaveToFile(Filename);
  finally
    ResStream.Free;
  end;
end;

//Open procedure
var
  sFileName: String = ExtractFilePath(ParamStr(0)) + 'Sqlite3.dll';

if OpenDialog1.Execute then
begin
  ExtractResource('RES_SQLITE3', sFileName);
  ... //process my database
  ...
  ... // finished opening database
  if FileExists(sFileName) then
        DeleteFile(sFileName);
end;
</code>```

EDIT

I think what I am attempting to do is not very practical, it is not a good idea to this as STATUS_ACCESS_DENIED earlier commented on. I have decided it is best not to proceed with what I set out to do.

答:
You should better use static linking of the SQLite3 engine instead of relying on an external dll. By including the .obj into your .dcu SQLite3 unit.

It will also add some nice features like ability to use FastMM4 as the memory manager for the SQlite3 engine also (speed up), and potentially some nice low-level features (like encryption).

See for instance:

our Open Source wrapper (which will include on-the-fly file encryption and some nice features like Virtual Tables coded as Delphi classes);

DISQlite which is not free;

AnyDAC which is not free at all but an open door to other DB engines;

Aducom free but old version (some updated information).

Body:
How can I unlock or delete a file that is in use, so that I can delete it? The file in question is used by my own application.

More specifically, my application is using the freeware Zeos Lib. When opening and saving my database the sqlite3.dll file must reside in the same directory as my application to work correctly.

I want my application to be 100% standalone, so I have added the sqlite3.dll as RC_DATA to my project, and whenever I need to use it (ie, open or save database), I extract it to the same folder as my application. Once the open or save operation has completed, I would like to delete the sqlite3.dll file, and no one would even know it was there or have to worry about missing libraries etc. (While I can appreciate that some of you may not like the idea of storing the libraries inside the application, I have my reasons for doing this: I don't want my end-users knowing what is behind the functioning of my application (SQL), and they also don't need to worry about missing dynamic link libraries.)

The problem is, I can successfully extract the sqlite3.dll and use it for my operations, but the file becomes locked by my application (until I close my application), which brings me to either:

Force unlock the sqlite3.dll file, without closing my application

Force delete the sqlite3.dll file

Unless of course there is another suggestion?

Here is a sample of extracting and using it. No direct calls need to be made such as LoadLibrary etc from my part; the Zeos Lib units must take care of this, so long as the sqlite3.dll is in the same directory as the application.

procedure ExtractResource(ResName: String; Filename: String);
var
  ResStream: TResourceStream;
begin
  ResStream:= TResourceStream.Create(HInstance, ResName, RT_RCDATA);
  try
    ResStream.Position:= 0;
    ResStream.SaveToFile(Filename);
  finally
    ResStream.Free;
  end;
end;

//Open procedure
var
  sFileName: String = ExtractFilePath(ParamStr(0)) + 'Sqlite3.dll';

if OpenDialog1.Execute then
begin
  ExtractResource('RES_SQLITE3', sFileName);
  ... //process my database
  ...
  ... // finished opening database
  if FileExists(sFileName) then
        DeleteFile(sFileName);
end;

EDIT

I think what I am attempting to do is not very practical, it is not a good idea to this as STATUS_ACCESS_DENIED earlier commented on. I have decided it is best not to proceed with what I set out to do.