问:
iOS Charts X Axis labels are not all showing
My app manages the score of a sport that has 4 quarter periods. My bar chart will not display the x-axis labels correctly. It only shows Qtr 1 and Qtr 3, whereas it should show all 4 quarters under each respective pair of bars.
Screen shot of Bar Chart

```<code>    func setChart(dataPoints: [String], values1: [Double], values2: [Double]) {

    let legend = barChartView.legend
    legend.enabled = true
    legend.textColor = Style.labelTextColor

    let xaxis = barChartView.xAxis
    xaxis.drawGridLinesEnabled = true
    xaxis.labelPosition = .bottom
    xaxis.axisMinimum = 0
    xaxis.centerAxisLabelsEnabled = true
    xaxis.granularityEnabled = true
    xaxis.labelCount = 4
    xaxis.granularity = 2
    xaxis.labelTextColor = Style.labelTextColor

    let leftAxisFormatter = NumberFormatter()
    leftAxisFormatter.maximumFractionDigits = 1

    let yaxis = barChartView.leftAxis
    yaxis.spaceTop = 0.35
    yaxis.axisMinimum = 0
    yaxis.drawGridLinesEnabled = true
    yaxis.labelTextColor = Style.labelTextColor
    yaxis.gridColor = Style.labelTextColor
    yaxis.zeroLineColor = Style.labelTextColor
    yaxis.axisLineColor = Style.labelTextColor

    barChartView.rightAxis.enabled = false

    barChartView.noDataText = "You need to provide data for the chart."
    barChartView.chartDescription?.text = nil

    var dataEntries1: [BarChartDataEntry] = []; var dataEntries2: [BarChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry1 = BarChartDataEntry(x: Double(i), y: values1[i])
        dataEntries1.append(dataEntry1)

        let dataEntry2 = BarChartDataEntry(x: Double(i), y: values2[i])
        dataEntries2.append(dataEntry2)
    }

    let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: gCurrentMatch.teamA)
    let chartDataSet2 = BarChartDataSet(values: dataEntries2, label: gCurrentMatch.teamB)
    chartDataSet1.colors = [Style.chartColorA]; chartDataSet1.valueColors = [Style.labelTextColor]
    chartDataSet2.colors = [Style.chartColorB]; chartDataSet2.valueColors = [Style.labelTextColor]

    let dataSets: [BarChartDataSet] = [chartDataSet1, chartDataSet2]
    let chartData = BarChartData(dataSets: dataSets)

    let groupSpace = 0.3
    let barSpace = 0.05
    let barWidth = 1.0
    // (0.3 + 0.05) * 2 + 0.3 = 1.00 -> interval per "group"

    let groupCount = self.qtr.count

    chartData.barWidth = barWidth
    let gg = chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)

    barChartView.xAxis.axisMaximum = Double(0) + gg * Double(groupCount)
    barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints)

    chartData.groupBars(fromX: Double(0), groupSpace: groupSpace, barSpace: barSpace)
    barChartView.notifyDataSetChanged()
    barChartView.data = chartData
    //chart animation
    barChartView.animate(yAxisDuration: 0.5, easingOption: .linear)

}
</code>```

dataPoints is a string array containing "Qtr 1", "Qtr 2" etc...

I cannot work out why it is not working.

答:
use the following code in your xaxis formatting : </p>

```<code>xaxis.setLabelCount(4, force: true)
</code>```

Body:
My app manages the score of a sport that has 4 quarter periods. My bar chart will not display the x-axis labels correctly. It only shows Qtr 1 and Qtr 3, whereas it should show all 4 quarters under each respective pair of bars.
Screen shot of Bar Chart

    func setChart(dataPoints: [String], values1: [Double], values2: [Double]) {

    let legend = barChartView.legend
    legend.enabled = true
    legend.textColor = Style.labelTextColor

    let xaxis = barChartView.xAxis
    xaxis.drawGridLinesEnabled = true
    xaxis.labelPosition = .bottom
    xaxis.axisMinimum = 0
    xaxis.centerAxisLabelsEnabled = true
    xaxis.granularityEnabled = true
    xaxis.labelCount = 4
    xaxis.granularity = 2
    xaxis.labelTextColor = Style.labelTextColor

    let leftAxisFormatter = NumberFormatter()
    leftAxisFormatter.maximumFractionDigits = 1

    let yaxis = barChartView.leftAxis
    yaxis.spaceTop = 0.35
    yaxis.axisMinimum = 0
    yaxis.drawGridLinesEnabled = true
    yaxis.labelTextColor = Style.labelTextColor
    yaxis.gridColor = Style.labelTextColor
    yaxis.zeroLineColor = Style.labelTextColor
    yaxis.axisLineColor = Style.labelTextColor

    barChartView.rightAxis.enabled = false

    barChartView.noDataText = "You need to provide data for the chart."
    barChartView.chartDescription?.text = nil

    var dataEntries1: [BarChartDataEntry] = []; var dataEntries2: [BarChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry1 = BarChartDataEntry(x: Double(i), y: values1[i])
        dataEntries1.append(dataEntry1)

        let dataEntry2 = BarChartDataEntry(x: Double(i), y: values2[i])
        dataEntries2.append(dataEntry2)
    }

    let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: gCurrentMatch.teamA)
    let chartDataSet2 = BarChartDataSet(values: dataEntries2, label: gCurrentMatch.teamB)
    chartDataSet1.colors = [Style.chartColorA]; chartDataSet1.valueColors = [Style.labelTextColor]
    chartDataSet2.colors = [Style.chartColorB]; chartDataSet2.valueColors = [Style.labelTextColor]

    let dataSets: [BarChartDataSet] = [chartDataSet1, chartDataSet2]
    let chartData = BarChartData(dataSets: dataSets)

    let groupSpace = 0.3
    let barSpace = 0.05
    let barWidth = 1.0
    // (0.3 + 0.05) * 2 + 0.3 = 1.00 -> interval per "group"

    let groupCount = self.qtr.count

    chartData.barWidth = barWidth
    let gg = chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)

    barChartView.xAxis.axisMaximum = Double(0) + gg * Double(groupCount)
    barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints)

    chartData.groupBars(fromX: Double(0), groupSpace: groupSpace, barSpace: barSpace)
    barChartView.notifyDataSetChanged()
    barChartView.data = chartData
    //chart animation
    barChartView.animate(yAxisDuration: 0.5, easingOption: .linear)

}

dataPoints is a string array containing "Qtr 1", "Qtr 2" etc...

I cannot work out why it is not working.

Body:
use the following code in your xaxis formatting :

xaxis.setLabelCount(4, force: true)


来源: stackexchange

问:
I am getting persistent but intermittent "Violation of PRIMARY KEY constraint" Errors
I am the person in my company who tries to solve coldfusion errors and bugs. We get daily emails with full details of coldfusion errors etc, as well we store this information in our database.

And for a few different applications in ColdFusion, they seem to sporadically generated "Violation of PRIMARY KEY constraint" errors.

In the code we always check for the existence of a row in the database before we try to do an insert, and it still generate's that error.

So my thinking is, either we need to a cftransaction around these each of the check, insert or update blocks. But I am not sure this will truly solve the problem.

These are coded in standard coldfusion style/framework. Here is an example in pseudo-code.

cfquery name="check_sometable" datasource="#dsn#"
select id
from sometable
/cfquery

if check_sometable.recordcount gt 0
-do insert
else
-do update
/endif

So why would this intermittently, cause primary key violations?

Is this a sql server problem, are we missing a configuration option?

Are we getting all of this because we are not on the latest hotfixed version of coldfusion 8 standard?

Do we need to upgrade our jdbc/odbc drivers?

Thank You.

答:
Sounds like race conditions to me. Two connections check for the next available id at the same time, get the same one and then the insert fails on the second one. Why are you not using an identity field to create the PK if it is a surrogate key?

If you have a PK that is a natural key, then the violation is a good thing, you have two users trying to insert the same record which you do not want. I would try to fail it gracefully though, with an error that says someone else has created the same record. And then ask if they want to update it after loading the new values to their screen. I'm not sure I would want it to set up so that the data is automatically updated by the second person without them seeing what the first person put into the database.

Further this might be an indication that your natural key is not as unique as you think it is.  Not sure what this application does, but how likely is it that two people would want to be working with the same data at a the same time? So if your natural key were something like company name, be aware that they are not guaranteed to be unique and you might have users overwriting good data for one company with data for another company already. I've found in life there are truly very few really unique, never changing natural keys. So if your natural key really isn't unique, you may already have bad data and the PK violations are just a symptom of a differnt problem not the real problem.

ContentLicense: CC BY-SA 2.5


问:
cant fetch recent tweets of a user
when i print $tweets it gives me array with error like

[body] => {"errors":[{"message":"Sorry, that page does not exist","code":34}]}

```<code>private function fetch_tweets($tweet_count,$username){
    $tweets = wp_remote_get("http://twitter.com/statuses/user_timeline/$username.json");

    print_r($tweets);

    if(isset($tweet->error) ) return false;

    foreach($tweets as $tweet){
        if($tweet_count-- === 0) break;
        echo $tweet->text;
    }
}
</code>```

答:
As ardavey mentioned, you need to read the API Documentation:

Example Request

GET https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2

So, for your PHP:

```<code>$tweets = wp_remote_get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=$username");
</code>```

Also, not that you will need to authenticate your request:

Please note that the API requires that the request be authenticated (check Authentication & Authorization documentation...

See Auth Overview to get started.

ContentLicense: CC BY-SA 3.0

Title: cant fetch recent tweets of a user

Body:
when i print $tweets it gives me array with error like

[body] => {"errors":[{"message":"Sorry, that page does not exist","code":34}]}

private function fetch_tweets($tweet_count,$username){
    $tweets = wp_remote_get("http://twitter.com/statuses/user_timeline/$username.json");

    print_r($tweets);

    if(isset($tweet->error) ) return false;

    foreach($tweets as $tweet){
        if($tweet_count-- === 0) break;
        echo $tweet->text;
    }
}

Body:
As ardavey mentioned, you need to read the API Documentation:

Example Request

GET https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2

So, for your PHP:

$tweets = wp_remote_get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=$username");

Also, not that you will need to authenticate your request:

Please note that the API requires that the request be authenticated (check Authentication & Authorization documentation...

See Auth Overview to get started.


问:
Relaunch app from code inside app iOS swift
I need to relaunch my app when the user completes an in app purchase. Is this possible without any user action.

What I really need is to avoid the navigation controller that is associated with the subscribe link in a table view controller.

Once a user subscribes I can get from the subscribe table view to the main app but the navigation controller tags along covering up all of my navigation items in all of the views in the main app.

答:
Make use of a navigationContoller it will not actually relaunch your app but will update all UI to show as app is relaunched just connect a navigation controller on first screen of your application and don't make navigationConroller as initial Controller</p>

```<code>let rootviewcontroller: UIWindow = ((UIApplication.shared.delegate?.window)!)!
        rootviewcontroller.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "rootnav")
        let mainwindow = (UIApplication.shared.delegate?.window!)!
        mainwindow.backgroundColor = UIColor(hue: 0.6477, saturation: 0.6314, brightness: 0.6077, alpha: 0.8)
        UIView.transition(with: mainwindow, duration: 0.55001, options: transition, animations: { () -> Void in
        }) { (finished) -> Void in

        }
</code>```

Body:
Make use of a navigationContoller it will not actually relaunch your app but will update all UI to show as app is relaunched just connect a navigation controller on first screen of your application and don't make navigationConroller as initial Controller

let rootviewcontroller: UIWindow = ((UIApplication.shared.delegate?.window)!)!
        rootviewcontroller.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "rootnav")
        let mainwindow = (UIApplication.shared.delegate?.window!)!
        mainwindow.backgroundColor = UIColor(hue: 0.6477, saturation: 0.6314, brightness: 0.6077, alpha: 0.8)
        UIView.transition(with: mainwindow, duration: 0.55001, options: transition, animations: { () -> Void in
        }) { (finished) -> Void in

        }


问:
Retrieve Dropbox Images in Website with png or jpg format
I have build a app. With that app i upload image to Dropbox. Each user has a Profil image save in Dropbox. I Save the Referenz in the Server to know which Image is for each user. Now i want to Display that image in my Website in Format png or jpg. I found a Dropbox api to Display image in Website but the give me the Image as blob format. The Image is rendering slow and it can not caching I'm Browser.

Somebody can help me to retrieve Dropbox Images in Website as a normal format (jpg,png,gif)

Thanks for help

答: it has explained completly here Hosting images with Dropbox on your website</p>


问:
SetTimout not properly functioning
I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                console.log("hello world")
            },5000)
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">
start
</button></code>```

The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?

答:
You can use a for loop, but you need to give different timeouts so they'll run at different times.

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                alert("hello world")
            }, 5000 * (i + 1))
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">
start
</button></code>```

Title: SetTimout not properly functioning

Body:
I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                console.log("hello world")
            },5000)
        }
    })
})

<button id="start">
start
</button>

The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?

Body:
You can use a for loop, but you need to give different timeouts so they'll run at different times.

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                alert("hello world")
            }, 5000 * (i + 1))
        }
    })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">
start
</button>


问:
#SQL - Compare different tables and create a new table
I have 4 tables with various columns where ID being the common value in all 4 tables. There is a column called EventDate in all 4 tables but with different values or NULL values for the same ID. The new table should have only ID and EventDate.

I would like to compare all the 4 tables based on the EventDate (ie) if two tables have the same date, it should insert the min date into the new table.

答:
Use UNION ALL to combine all and take Minimum date for every ID

```<code>SELECT ID, MIN(EventDate) AS MIN_DTE INTO NEW_TABLE FROM (
SELECT ID, EventDate from TABLE1
UNION ALL
SELECT ID, EventDate from TABLE2
UNION ALL
SELECT ID, EventDate from TABLE3
UNION ALL
SELECT ID, EventDate from TABLE4
)A
GROUP BY ID
</code>```

Body:
Use UNION ALL to combine all and take Minimum date for every ID

SELECT ID, MIN(EventDate) AS MIN_DTE INTO NEW_TABLE FROM (
SELECT ID, EventDate from TABLE1
UNION ALL
SELECT ID, EventDate from TABLE2
UNION ALL
SELECT ID, EventDate from TABLE3
UNION ALL
SELECT ID, EventDate from TABLE4
)A
GROUP BY ID


问:
Process the command without launching MainActivity, in Android
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

```<code><application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>
</code>```

MainActivity.java

```<code>public class MainActivity extends Activity {

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}
</code>```

ScreenOffAdminReceiver.java

```<code>public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}
</code>```

permissions.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>
</code>```

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks

答:
I think it'll be faster if instead of locking the screen from the app you can create a widget to do the same. It will be faster and more efficient.
This might help you</p>

Body:
I am new to android and stuck at one point with my new screen off test application. I am trying to develop an Android application to turn off or lock the screen directly by clicking the app launcher icon of the application.

I am able to lock the screen with the functionality I want but with one problem. While i click on the screen lock icon in the launcher it takes around a second and then locks the screen (Time is taken by to MainActivity to launch).

I want that time delay to be removed and just wanted to process the command to lock phone when user tap on the app icon in the launcher. But am not able to figure it out.

Here is AndroidManifest.xml

<application
    android:theme="@android:style/Theme.NoDisplay"
    android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:allowBackup="true">

    <activity android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="ScreenOffAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data android:name="android.app.device_admin"
            android:resource="@xml/permissions" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

</application>

MainActivity.java

public class MainActivity extends Activity {

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        DevicePolicyManager deviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName compName = new ComponentName(this, ScreenOffAdminReceiver.class);
        if (deviceManger.isAdminActive(compName)) {
            deviceManger.lockNow();
            finish();
        } else {
            Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
            intent.putExtra("android.app.extra.DEVICE_ADMIN", compName);
            intent.putExtra("android.app.extra.ADD_EXPLANATION", getString(R.string.devicePolicyManagerMsg));
            startActivityForResult(intent, 0);
        }
        Process.killProcess(Process.myPid());
    }
}

ScreenOffAdminReceiver.java

public class ScreenOffAdminReceiver extends DeviceAdminReceiver {
    public void onDisabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminDisabled, Toast.LENGTH_SHORT).show();
    }

    public void onEnabled(Context context, Intent intent) {
        Toast.makeText(context, R.string.deviceAdminEnabled, Toast.LENGTH_SHORT).show();
    }
}

permissions.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

I just want to remove the DELAY while locking the screen. Any help will be highly appreciated. Thanks


问:
How do I perform HTML decoding/encoding using Python/Django?
I have a string that is HTML encoded:

```<code>'''<img class="size-medium wp-image-113"\
 style="margin-left: 15px;" title="su1"\
 src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg"\
 alt="" width="300" height="194" />'''
</code>```

I want to change that to:

```

I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text.

The string is stored like that because I am using a web-scraping tool called BeautifulSoup, it "scans" a web-page and gets certain content from it, then returns the string in that format.

I've found how to do this in C# but not in Python. Can someone help me out?

Related

Convert XML/HTML Entities into Unicode String in Python

答:
For html encoding, there's cgi.escape from the standard library:

```<code>>> help(cgi.escape)
cgi.escape = escape(s, quote=None)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.
</code>```

For html decoding, I use the following:

```<code>import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39

def unescape(s):
    "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
    return re.sub('&(%s);' % '|'.join(name2codepoint),
              lambda m: unichr(name2codepoint[m.group(1)]), s)
</code>```

For anything more complicated, I use BeautifulSoup.

OwnerDisplayName: rksprst

ContentLicense: CC BY-SA 4.0

Body:
I have a string that is HTML encoded:

''''''

I want to change that to:

I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text.

The string is stored like that because I am using a web-scraping tool called BeautifulSoup, it "scans" a web-page and gets certain content from it, then returns the string in that format.

I've found how to do this in C# but not in Python. Can someone help me out?

Related

Convert XML/HTML Entities into Unicode String in Python

LastEditorDisplayName: J.F. Sebastian

Body:
For html encoding, there's cgi.escape from the standard library:

>> help(cgi.escape)
cgi.escape = escape(s, quote=None)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

For html decoding, I use the following:

import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39

def unescape(s):
    "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
    return re.sub('&(%s);' % '|'.join(name2codepoint),
              lambda m: unichr(name2codepoint[m.group(1)]), s)

For anything more complicated, I use BeautifulSoup.


问:
computer organization
Could you explain to me in detail what a "Clock Cycle" is?</p>

答:
Clock cycle, is a duration of a single, complete transition of a device clock. Essentially, digital electronic is synchronous, i.e., there is a central source of timing commands synchronizing all elements of a processor to occur simultaneously.

It is similar to the officer leading a brigade of infantry, ordering them to shout "left" every time they put their left foot forward - this way, soldiers don't stumble into each other.

A computer has a device fulfilling a similar purpose - it synchronizes the different portions of a processor, for instance, memory access units, arithmetic units, etc. It has a direct impact on the speed of the computer - it synchronizes the execution of sequences of operations, that together result in the speed of execution of a software program.

Title: computer organization


问:
Type UIRectCorner has no member isRightPage in Swift 3
We have the following variable of type UIImage that no longer works in Swift 3. Is there anyone with this same issue facing with UIImage class in such a way. Here is the code:

```<code>var image: UIImage? {
        didSet {
            var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft
            imageView.image = image!.imageByScalingAndCroppingForSize(bounds.size).imageWithRoundedCornersSize(20, corners: corners)
        }
    }
</code>```

The error we're getting is "Type of expression is ambigouos without more context" for var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft

答:
Swift 2 introduced a new type, OptionSet, for handling sets of flags. You can combine multiple flags using literal array notation ([a, b, c]) instead of using bitwise operators like |.

The Swift API Design Guidelines, introducing during Swift 3's development, say that only type and protocol names begin with an upper case letter, and everything else starts with a lower-case letter. The iOS 10 API was changed to follow the guidelines.

So define corners like this:

```<code>let corners: UIRectCorner = isRightPage ? [.topRight, .bottomRight] : [.topLeft, .bottomLeft]
</code>```

Body:
We have the following variable of type UIImage that no longer works in Swift 3. Is there anyone with this same issue facing with UIImage class in such a way. Here is the code:

var image: UIImage? {
        didSet {
            var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft
            imageView.image = image!.imageByScalingAndCroppingForSize(bounds.size).imageWithRoundedCornersSize(20, corners: corners)
        }
    }

The error we're getting is "Type of expression is ambigouos without more context" for var corners: UIRectCorner = isRightPage ? .TopRight | .BottomRight : .TopLeft | .BottomLeft

Body:
Swift 2 introduced a new type, OptionSet, for handling sets of flags. You can combine multiple flags using literal array notation ([a, b, c]) instead of using bitwise operators like |.

The Swift API Design Guidelines, introducing during Swift 3's development, say that only type and protocol names begin with an upper case letter, and everything else starts with a lower-case letter. The iOS 10 API was changed to follow the guidelines.

So define corners like this:

let corners: UIRectCorner = isRightPage ? [.topRight, .bottomRight] : [.topLeft, .bottomLeft]


问:
Java Simple date format - dd/MM/yy v/s dd/MM/yyyy
I need to parse a String into dd/MM/YY hh:mm:ss format.

Suppose if a String has value 09/06/17 05:59:59 then it should be parsed but if a String has value 09/06/2017 05:59:59 then this is also a valid format and getting parsed but in my requirement, a parse exception should be thrown for the later.

Code:

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {

    public static void main(String[] args) {

        String line=" 09/06/17 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
        //String line=" 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";

        String dt=null;
        dt=line.substring(1, 19);

        SimpleDateFormat org_format = new SimpleDateFormat("dd/MM/YY hh:mm:ss");
        SimpleDateFormat tgt_format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
              dt=line.substring(1, 19);

              System.out.println(dt);
              Date date = org_format.parse(dt);
              System.out.println(date);

              String tgt_date=tgt_format.format(date);
              System.out.println(tgt_date);
         } catch (ParseException e) {
              System.out.println(line);
         }
    }
}
</code>```

Problem - In the code, uncommented line variable and commented line variable, both are giving result successfully. but the commented line should throw parsable exception as it's the pattern dd/MM/yyyy, not dd/MM/yy.

fmt.setLenient(false) is not working.

I'm using Java 7. Don't have option to use Java 8 or later so can't use java.time.

答:
Regex to match any of these date formats</p>

```<code>String regex = "^(([0]?[1-9]|1[0-2])/([0-2]?[0-9]|3[0-1])/[1-2]\d{3}) (20|21|22|23|[0-1]?\d{1}):([0-5]?\d{1})$";
Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher("09/06/17 05:59:59");

if(matcher.matches()){
    //your next code
}
</code>```

Body:
I need to parse a String into dd/MM/YY hh:mm:ss format.

Suppose if a String has value 09/06/17 05:59:59 then it should be parsed but if a String has value 09/06/2017 05:59:59 then this is also a valid format and getting parsed but in my requirement, a parse exception should be thrown for the later.

Code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {

    public static void main(String[] args) {

        String line=" 09/06/17 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
        //String line=" 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";

        String dt=null;
        dt=line.substring(1, 19);

        SimpleDateFormat org_format = new SimpleDateFormat("dd/MM/YY hh:mm:ss");
        SimpleDateFormat tgt_format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
              dt=line.substring(1, 19);

              System.out.println(dt);
              Date date = org_format.parse(dt);
              System.out.println(date);

              String tgt_date=tgt_format.format(date);
              System.out.println(tgt_date);
         } catch (ParseException e) {
              System.out.println(line);
         }
    }
}

Problem - In the code, uncommented line variable and commented line variable, both are giving result successfully. but the commented line should throw parsable exception as it's the pattern dd/MM/yyyy, not dd/MM/yy.

fmt.setLenient(false) is not working.

I'm using Java 7. Don't have option to use Java 8 or later so can't use java.time.

Body:
Regex to match any of these date formats

String regex = "^(([0]?[1-9]|1[0-2])/([0-2]?[0-9]|3[0-1])/[1-2]\d{3}) (20|21|22|23|[0-1]?\d{1}):([0-5]?\d{1})$";
Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher("09/06/17 05:59:59");

if(matcher.matches()){
    //your next code
}


问:
Silent push notification (APNS) can not received
I have set up the silent push notification for my app:
1. I configured the push notification from all places, i.e., XCode, Apple Developer portal with proper certificate
2. I enabled background capability
3. I included "content-available" in the json payload.

However, my App can not receive silent push sometimes.

To be more specific, neither

```<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    ......
}
</code>```

nor

```<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (_: UIBackgroundFetchResult) -> Void) {
    ......
}
</code>```

has been invoked when the push message arrives.

How can I get the information in the push notification in such state?

I'm waiting online.

答:
You question is twofold:
1. why the two delegate callbacks can not be invoked
2. what should you do to receive the data.

I did some hand test and here is the result:

1, when an app is in killed state, the two callback can not be invoked indeed
2. however, when you open the app next time,

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    ......
}
</code>```

can be invoked and you can get the data from there.

I hope this is useful.

Body:
I have set up the silent push notification for my app:
1. I configured the push notification from all places, i.e., XCode, Apple Developer portal with proper certificate
2. I enabled background capability
3. I included "content-available" in the json payload.

However, my App can not receive silent push sometimes.

To be more specific, neither

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    ......
}

nor

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (_: UIBackgroundFetchResult) -> Void) {
    ......
}

has been invoked when the push message arrives.

How can I get the information in the push notification in such state?

I'm waiting online.

Body:
You question is twofold:
1. why the two delegate callbacks can not be invoked
2. what should you do to receive the data.

I did some hand test and here is the result:

1, when an app is in killed state, the two callback can not be invoked indeed
2. however, when you open the app next time,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    ......
}

can be invoked and you can get the data from there.

I hope this is useful.


问:
How do I utilize dot notation when rendering components?
I have a simple component which is supposed to render different kind of fields into my form component:

```<code>import React from "react";

export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (
          <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>
          )
      }
      case 'text': {
        return (
          <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>
        )
      }
    }
  }
}
</code>```

And I'm using this component in my form component like this:

```<code>export default class SubmitForm extends React.Component {

  render() {
    return (
        .
        .
        .
        <Field
          type="text"
          placeholder="something"
          name="something"
        />
        <Field
          type="textarea"
          placeholder="another"
          name="othername"
        />
        .
        .
        .
    )
  }
}
</code>```

What I have in mind is to somehow implement my field component to be able to use dot notation as explained in Using Dot Notation for JSX components which I have seen many other libraries and I want to be able to use this component like this:

```<code><Field.Text name="sth" placeholder="sth" />
<Field.TextArea name="other" placeholder="other stuff" />
</code>```

But I can't do it the way mentioned in React docs. How can I do this?

答:
Just create individual components and export them under names:

```<code>//Field.js
class TextArea extends React.Component {
  ...
}

class Text extends React.Component {
  ...
}

export { Text, TextArea };
</code>```

Then import all the names from the module:

```<code>import * as Field from './path/to/Field.js';
</code>```

Or if you prefer exporting a default object like so (which is exactly what the example from the documentation is doing, just in a different way):

```<code>export default { Text, TextArea };
</code>```

Which will use object shorthand properties and export a default member -- an object literal. Then you can import it like so:

```<code>import Field from './path/to/Field.js';
</code>```

And finally:

```<code><Field.TextArea ... />
</code>```

Or, to get rid of dot notation (you can't do this with the default export option!):

```<code>import { Text, TextArea } from './path/to/Field.js';

<Text ... />
<TextArea ... />
</code>```

Of course, going exactly by the React documentation, you could do, with class expressions:

```<code>const Field = {
  Text: class Text extends React.Component { //you can omit the class name here
    //can be stateless functional component if you don't need state
  },
  TextArea: class TextArea extends React.Component {

  }
}

export default Field;
</code>```

Then importing as a default member and using dot notation.

Body:
I have a simple component which is supposed to render different kind of fields into my form component:

import React from "react";

export default class Field extends React.Component {

  render() {
    switch (this.props.type) {
      case 'textarea': {
        return (

            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>

          )
      }
      case 'text': {
        return (

            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />

        )
      }
    }
  }
}

And I'm using this component in my form component like this:

export default class SubmitForm extends React.Component {

  render() {
    return (
        .
        .
        .
        <Field
          type="text"
          placeholder="something"
          name="something"
        />
        <Field
          type="textarea"
          placeholder="another"
          name="othername"
        />
        .
        .
        .
    )
  }
}

What I have in mind is to somehow implement my field component to be able to use dot notation as explained in Using Dot Notation for JSX components which I have seen many other libraries and I want to be able to use this component like this:

<Field.Text name="sth" placeholder="sth" />
<Field.TextArea name="other" placeholder="other stuff" />

But I can't do it the way mentioned in React docs. How can I do this?

Body:
Just create individual components and export them under names:

//Field.js
class TextArea extends React.Component {
  ...
}

class Text extends React.Component {
  ...
}

export { Text, TextArea };

Then import all the names from the module:

import * as Field from './path/to/Field.js';

Or if you prefer exporting a default object like so (which is exactly what the example from the documentation is doing, just in a different way):

export default { Text, TextArea };

Which will use object shorthand properties and export a default member -- an object literal. Then you can import it like so:

import Field from './path/to/Field.js';

And finally:

<Field.TextArea ... />

Or, to get rid of dot notation (you can't do this with the default export option!):

import { Text, TextArea } from './path/to/Field.js';

<Text ... />
<TextArea ... />

Of course, going exactly by the React documentation, you could do, with class expressions:

const Field = {
  Text: class Text extends React.Component { //you can omit the class name here
    //can be stateless functional component if you don't need state
  },
  TextArea: class TextArea extends React.Component {

  }
}

export default Field;

Then importing as a default member and using dot notation.


问:
Label is displayed below the input textbox
This is my input code sample. So whenever an error is generated, this error label would be visible. But it is coming up below the input element. I want it to be on the right side of the input.

I am able to modify the css for this bit using the label.error code bit I have. Label being the type and error is the class of that label being generated.

```<code>label.error
{
display:inline;
float:right;
}

> <td><input
> name="answer_engineeringjobs_1^11"
> id="answer_engineeringjobs_1"
> class="reqfield required zipUS error"
> type="text"><label class="error"
> generated="true"
> for="answer_engineeringjobs_1">This
> field is required.</label></td>
</code>```

答: One or the other is a block. If one of them is a block it will cause the elements to stack on top of each other. Either float as David Dorward suggested or set them to display inline</p>

Body:
This is my input code sample. So whenever an error is generated, this error label would be visible. But it is coming up below the input element. I want it to be on the right side of the input.

I am able to modify the css for this bit using the label.error code bit I have. Label being the type and error is the class of that label being generated.

label.error
{
display:inline;
float:right;
}

> <input
> name="answer_engineeringjobs_1^11"
> id="answer_engineeringjobs_1"
> class="reqfield required zipUS error"
> type="text"> generated="true"
> for="answer_engineeringjobs_1">This
> field is required.


问:
Sending data with Segue with Swift
I have two view controllers and two views.
In my first view, I set the variable 'currentUser' to false.
I need to be able to set 'currentUser' to true in the second view controller.

When trying to reference 'currentUser' from the second view it's not picking it up as 'currentUser' is defined in the first view controller.

How do I carry across variables with segue?

答:
Since you're using same variable across the two Viewcontrollers, namely currentUser (type Bool).

So its better to make it a global variable in both classes.

When coming to global variable concept in swift.

Everything by default in swift is public, and thus if you declare something like this:

```<code>class FirstViewController: UIViewController {

    var someVariable: Boll = YES

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
}
</code>```

You can access it and set values as long as you have an instance of it:

```<code>var MySecondViewController: FirstViewController = FirstViewController(nibName: nil, bundle: nil)
var getThatValue = MySecondViewController.someVariable
</code>```

Title: Sending data with Segue with Swift

Body:
Since you're using same variable across the two Viewcontrollers, namely currentUser (type Bool).

So its better to make it a global variable in both classes.

When coming to global variable concept in swift.

Everything by default in swift is public, and thus if you declare something like this:

class FirstViewController: UIViewController {

    var someVariable: Boll = YES

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
}

You can access it and set values as long as you have an instance of it:

var MySecondViewController: FirstViewController = FirstViewController(nibName: nil, bundle: nil)
var getThatValue = MySecondViewController.someVariable


问:
VBA/Excel suddenly running slow with no code changes
I came to work this morning and began work on the same file I left from yesterday.  Now Excel slows way down whenever a macro is assigning values to cells or clearing them.  It was lightning quick before I left yesterday, now it takes 2-3 seconds at a time to assign a value to a cell.

Right now, other files with similar macros run fine.  This happened to another file a while back, so I reverted to a previous version of the file and it worked fine, while the slow file continued to work slow.  I guess I can do that now, but in this case that would take a whole lot of work to bring that file to where I have this version.  I was wondering if anyone knows what might be going on.  Is this one of the things Excel files just do from time to time (like a kind of file corruption), or is there a fix?

I have provided the macro below, although it happens throughout the file whenever values are assigned to cells.  I've marked the trouble areas by denoting <---SLOW HERE.

I know this all sounds very vague, and I know I am giving very little to go on.  Perhaps insufficient info, but this is all I have.  There is no reason (that I can see) that this should be happening.  I've even restarted the computer...just in case the problem was external to Excel.  No change.

If you need more info I will do my best to expound if I can.  Thanks for your help and understanding.

Example Macro:

```<code>Sub DeleteButton1_Click()
   Call UnlockSettingsWorksheet

   Sheet24.Range("C18:E18").Value = ""  <---SLOW HERE
   Dim i As Long
   For i = 18 To 21
     Sheet24.Range("C" & i & ":E" & i).Value = Sheet24.Range("C" & i + 1 & ":E" & i + 1).Value  <---SLOW HERE
   Next
   Sheet24.Range("C22:E22").Value = ""  <---SLOW HERE

   Call LockSettingsWorksheet
End Sub
</code>```

答:
As mentioned in the comments, there might be a lot of factors contributing to this change:

any actions triggered in these events:

Worksheet_Calculate()

Worksheet_Change()

Worksheet_FollowHyperlink()

Worksheet_SelectionChange()

Workbook_SheetCalculate()

Workbook_SheetChange()

Workbook_SheetFollowHyperlink()

external links, and the external file(s) moved or deleted

database connections (check Data Tab -> Connections) (doubtful)

Invalid Named Ranges (Formula Tab -> Name Manager; any Refs?)

Data validation rules (Data Tab -> Data Validation -> clear all)

Are you opening the file from a network location - this will make it much slower

Conditional Formatting rules? - remove all

Any hidden objects? (Alt + F10 - delete all)

Hidden formatting (what is the last used cell with data?); this may not be relevant for your case

Corrupt file

If the file is corrupt, and it's feasible, try re-creating it from scratch, and run this function first

If it's not corrupt, one of the first things I'd try is to disable all Excel functionality before the macro:

```<code>Sub DeleteButton1_Click()

    'UnlockSettingsWorksheet

    FastWB          '<--- Disables all Application and Worksheet level settings

    With ThisWorkbook.Worksheets("Sheet24")   'Fully qualified worksheet

        .Range("C18:E18").Value2 = vbNullString

        Dim i As Long
        For i = 18 To 21
            .Range("C" & i & ":E" & i).Value2 = .Range("C" & (i + 1) & ":E" & (i + 1) ).Value2
        Next

        .Range("C22:E22").Value2 = vbNullString

    End With

    XlResetSettings '<--- Restores all Excel settings to defaults

    'LockSettingsWorksheet

End Sub
</code>```

.

```<code>Public Sub FastWB(Optional ByVal opt As Boolean = True)
    With Application
        .Calculation = IIf(opt, xlCalculationManual, xlCalculationAutomatic)
        .DisplayAlerts = Not opt
        .DisplayStatusBar = Not opt
        .EnableAnimations = Not opt
        .EnableEvents = Not opt
        .ScreenUpdating = Not opt
    End With
    FastWS , opt
End Sub

Public Sub FastWS(Optional ByVal ws As Worksheet, Optional ByVal opt As Boolean = True)
    If ws Is Nothing Then
        For Each ws In Application.ThisWorkbook.Sheets
            OptimiseWS ws, opt
        Next
    Else
        OptimiseWS ws, opt
    End If
End Sub

Public Sub OptimiseWS(ByVal ws As Worksheet, ByVal opt As Boolean)
    With ws
        .DisplayPageBreaks = False
        .EnableCalculation = Not opt
        .EnableFormatConditionsCalculation = Not opt
        .EnablePivotTable = Not opt
    End With
End Sub
</code>```

```<code>Public Sub XlResetSettings()    'default Excel settings
    With Application
        .Calculation = xlCalculationAutomatic
        .DisplayAlerts = True
        .DisplayStatusBar = True
        .EnableAnimations = False
        .EnableEvents = True
        .ScreenUpdating = True
        Dim ws As Worksheet
        For Each ws In Application.ThisWorkbook.Sheets
            With ws
                .DisplayPageBreaks = False
                .EnableCalculation = True
                .EnableFormatConditionsCalculation = True
                .EnablePivotTable = True
            End With
        Next
    End With
End Sub
</code>```

Maybe this will eliminate some VBA causes

Body:
I came to work this morning and began work on the same file I left from yesterday.  Now Excel slows way down whenever a macro is assigning values to cells or clearing them.  It was lightning quick before I left yesterday, now it takes 2-3 seconds at a time to assign a value to a cell.

Right now, other files with similar macros run fine.  This happened to another file a while back, so I reverted to a previous version of the file and it worked fine, while the slow file continued to work slow.  I guess I can do that now, but in this case that would take a whole lot of work to bring that file to where I have this version.  I was wondering if anyone knows what might be going on.  Is this one of the things Excel files just do from time to time (like a kind of file corruption), or is there a fix?

I have provided the macro below, although it happens throughout the file whenever values are assigned to cells.  I've marked the trouble areas by denoting <---SLOW HERE.

I know this all sounds very vague, and I know I am giving very little to go on.  Perhaps insufficient info, but this is all I have.  There is no reason (that I can see) that this should be happening.  I've even restarted the computer...just in case the problem was external to Excel.  No change.

If you need more info I will do my best to expound if I can.  Thanks for your help and understanding.

Example Macro:

Sub DeleteButton1_Click()
   Call UnlockSettingsWorksheet

   Sheet24.Range("C18:E18").Value = ""  <---SLOW HERE
   Dim i As Long
   For i = 18 To 21
     Sheet24.Range("C" & i & ":E" & i).Value = Sheet24.Range("C" & i + 1 & ":E" & i + 1).Value  <---SLOW HERE
   Next
   Sheet24.Range("C22:E22").Value = ""  <---SLOW HERE

   Call LockSettingsWorksheet
End Sub

Body:
As mentioned in the comments, there might be a lot of factors contributing to this change:

any actions triggered in these events:

Worksheet_Calculate()

Worksheet_Change()

Worksheet_FollowHyperlink()

Worksheet_SelectionChange()

Workbook_SheetCalculate()

Workbook_SheetChange()

Workbook_SheetFollowHyperlink()

external links, and the external file(s) moved or deleted

database connections (check Data Tab -> Connections) (doubtful)

Invalid Named Ranges (Formula Tab -> Name Manager; any Refs?)

Data validation rules (Data Tab -> Data Validation -> clear all)

Are you opening the file from a network location - this will make it much slower

Conditional Formatting rules? - remove all

Any hidden objects? (Alt + F10 - delete all)

Hidden formatting (what is the last used cell with data?); this may not be relevant for your case

Corrupt file

If the file is corrupt, and it's feasible, try re-creating it from scratch, and run this function first

If it's not corrupt, one of the first things I'd try is to disable all Excel functionality before the macro:

Sub DeleteButton1_Click()

    'UnlockSettingsWorksheet

    FastWB          '<--- Disables all Application and Worksheet level settings

    With ThisWorkbook.Worksheets("Sheet24")   'Fully qualified worksheet

        .Range("C18:E18").Value2 = vbNullString

        Dim i As Long
        For i = 18 To 21
            .Range("C" & i & ":E" & i).Value2 = .Range("C" & (i + 1) & ":E" & (i + 1) ).Value2
        Next

        .Range("C22:E22").Value2 = vbNullString

    End With

    XlResetSettings '<--- Restores all Excel settings to defaults

    'LockSettingsWorksheet

End Sub

.

Public Sub FastWB(Optional ByVal opt As Boolean = True)
    With Application
        .Calculation = IIf(opt, xlCalculationManual, xlCalculationAutomatic)
        .DisplayAlerts = Not opt
        .DisplayStatusBar = Not opt
        .EnableAnimations = Not opt
        .EnableEvents = Not opt
        .ScreenUpdating = Not opt
    End With
    FastWS , opt
End Sub

Public Sub FastWS(Optional ByVal ws As Worksheet, Optional ByVal opt As Boolean = True)
    If ws Is Nothing Then
        For Each ws In Application.ThisWorkbook.Sheets
            OptimiseWS ws, opt
        Next
    Else
        OptimiseWS ws, opt
    End If
End Sub

Public Sub OptimiseWS(ByVal ws As Worksheet, ByVal opt As Boolean)
    With ws
        .DisplayPageBreaks = False
        .EnableCalculation = Not opt
        .EnableFormatConditionsCalculation = Not opt
        .EnablePivotTable = Not opt
    End With
End Sub

Public Sub XlResetSettings()    'default Excel settings
    With Application
        .Calculation = xlCalculationAutomatic
        .DisplayAlerts = True
        .DisplayStatusBar = True
        .EnableAnimations = False
        .EnableEvents = True
        .ScreenUpdating = True
        Dim ws As Worksheet
        For Each ws In Application.ThisWorkbook.Sheets
            With ws
                .DisplayPageBreaks = False
                .EnableCalculation = True
                .EnableFormatConditionsCalculation = True
                .EnablePivotTable = True
            End With
        Next
    End With
End Sub

Maybe this will eliminate some VBA causes


问:
How to create a FULL text index on a Computed Column
How can I create a Full Text Index on a computed column. When I bring up the wizard for full text, it doesn't show in the list of columns.</p>

答:
If you want to create an index on a computed column, then it has to be PERSISTED, deterministic, precise and cannot evaluate to the image, text or ntext data types

More details - https://www.sqlshack.com/how-to-create-indexes-on-sql-server-computed-columns/


问:
Checking input type=date in if statement (empty or !empty)
Okai, so I was running a check on my website and asked a couple of people if they could register on my page and some of the people managed to get through my registration without setting date (it turned automatically to 00-00-0000).
This is the assigning of the variables (using 1 common submit button).

```<code>$username = $_POST['username'];
        $passwordone = $_POST['passwordone'];
        $passwordtwo = $_POST['passwordtwo'];
        $name = $_POST['fullname'];
        $email = $_POST['email'];
        $age = $_POST['date'];
        $country = $_POST['country'];
</code>```

the statement to check the variables

```<code>if (!empty($username) && !empty($passwordone) && !empty($name) && !empty($email) && !empty($age) && !empty($country)
</code>```

How can I write this code so they wont be able to go through without assigning a date?

答:
I used a different method.</p>
```<code>if(strlen($_POST['date']==10){

echo $_POST['date'];

}else{

echo "Please Select Date";

}
</code>```

Body:
Okai, so I was running a check on my website and asked a couple of people if they could register on my page and some of the people managed to get through my registration without setting date (it turned automatically to 00-00-0000).
This is the assigning of the variables (using 1 common submit button).

$username = $_POST['username'];
        $passwordone = $_POST['passwordone'];
        $passwordtwo = $_POST['passwordtwo'];
        $name = $_POST['fullname'];
        $email = $_POST['email'];
        $age = $_POST['date'];
        $country = $_POST['country'];

the statement to check the variables

if (!empty($username) && !empty($passwordone) && !empty($name) && !empty($email) && !empty($age) && !empty($country)

How can I write this code so they wont be able to go through without assigning a date?

Body:
I used a different method.

if(strlen($_POST['date']==10){

echo $_POST['date'];

}else{

echo "Please Select Date";

}


问:
Assigning dynamic ids to elements using jQuery
Hi I am using jQuery and creating tags in a loop.

Ex -

```<code>for(var i=0;i<length;i++){

            jQuery("#dailydata").append("<table class='table'><tr>"+
                "<th>Min Temp : </th><td>"+ data[i]</td>" +
                "</tr></table>";

                if(data[i] <=10){
                    //add color to th
                }else{
                    //add different color to th
                }
        }
</code>```

I am creating a Table Row in every loop and appending to a HTML element. and just after that I am checking the value and according to that value I want to change the background color of the  tag.

Can somebody tell me how to achieve this?

答:
There are several methods.

The method you're using to build the tags isn't the most elegant, but you could adapt it to achieve the result you're after as follows...

```<code>jQuery("#dailydata").append("<table class='table'><tr>"+
            "<th id='"+ (data[i]<=10?'blue':'red') + "'>Min Temp : </th><td>"+ data[i]</td>" +
            "</tr></table>";
</code>```

I suggest you also read the jQuery docs on how to use 'attr' and 'prop' to add id's (and other attributes/properties) to jQuery elements without hacking the text together as in my example.

jQuery 'attr': https://api.jquery.com/attr/

jQuery 'prop': https://api.jquery.com/prop/

Body:
Hi I am using jQuery and creating tags in a loop.

Ex -

for(var i=0;i<length;i++){

            jQuery("#dailydata").append("

"+
                "Min Temp : 	"+ data[i]	" +
                "

";

                if(data[i] <=10){
                    //add color to th
                }else{
                    //add different color to th
                }
        }

I am creating a Table Row in every loop and appending to a HTML element. and just after that I am checking the value and according to that value I want to change the background color of the  tag.

Can somebody tell me how to achieve this?

Body:
There are several methods.

The method you're using to build the tags isn't the most elegant, but you could adapt it to achieve the result you're after as follows...

jQuery("#dailydata").append("<table class='table'><tr>"+
            "<th id='"+ (data[i]<=10?'blue':'red') + "'>Min Temp : </th><td>"+ data[i]</td>" +
            "</tr></table>";

I suggest you also read the jQuery docs on how to use 'attr' and 'prop' to add id's (and other attributes/properties) to jQuery elements without hacking the text together as in my example.

jQuery 'attr': https://api.jquery.com/attr/

jQuery 'prop': https://api.jquery.com/prop/


问:
build maven project with propriatery libraries included
How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ?

EDIT :

I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.

答: I think that the "right" solution here is to add your proprietary libraries to your own repository. It should be simple: create pom for your library project and publish the compiled version on your repository. Add this repository to the list of repositories for your mail project and run build. I believe it will work for you.</p>


问:
Using values from two data files for one formula for calculation in R
I'm a trying-to-be R user. I never learned to code properly and have been just doing it by finding stuff online.

I encountered a problem that I would need some of you experts' help.

I have two data files.

Particulate matter (PM) concentrations (~20000 observations)

Coefficient combinations to use with the particulate matter concentrations to calculate final concentrations.

For example..

Data set 1.

```<code>ID      PM
 1       5
 2      10
...    ...
1500    25
</code>```

Data set 2.

```<code>alpha    beta
    5       6
    1       2
  ...     ...
</code>```

I ultimately have to use all the coefficient combinations (alpha and beta) for each of the IDs from data set 1. For example, if I have 10 observations in data set 1, and 10 coefficient combinations in data set 2, my output table should have 100 different output values (10*10=100).

```<code>for (i in cmaq$FID) {
  mean=cmaq$PM*IER$alpha*IER$beta
}
</code>```

I used the above code to do what I'm trying to do, but it only gave me 10 output values rather than 100. I think using the split function first, and somehow use that with the second dataset would work, but have not figured out how...

It may be a very very simple problem, but after spending hours to figure it out, I thought it may be a better strategy to get some help from R experts.

Thank you in advance!!!

答:
Look for the term 'cross join' or 'cartesian join' (eg, How to do cross join in R?).

If that doesn't address the issue, please see https://stackoverflow.com/help/mcve.  I think there is a mistake inside the loop.  beta is free-floating, and not connected to the IER data.frame

Body:
I'm a trying-to-be R user. I never learned to code properly and have been just doing it by finding stuff online.

I encountered a problem that I would need some of you experts' help.

I have two data files.

Particulate matter (PM) concentrations (~20000 observations)

Coefficient combinations to use with the particulate matter concentrations to calculate final concentrations.

For example..

Data set 1.

ID      PM
 1       5
 2      10
...    ...
1500    25

Data set 2.

alpha    beta
    5       6
    1       2
  ...     ...

I ultimately have to use all the coefficient combinations (alpha and beta) for each of the IDs from data set 1. For example, if I have 10 observations in data set 1, and 10 coefficient combinations in data set 2, my output table should have 100 different output values (10*10=100).

for (i in cmaq$FID) {
  mean=cmaq$PM*IER$alpha*IER$beta
}

I used the above code to do what I'm trying to do, but it only gave me 10 output values rather than 100. I think using the split function first, and somehow use that with the second dataset would work, but have not figured out how...

It may be a very very simple problem, but after spending hours to figure it out, I thought it may be a better strategy to get some help from R experts.

Thank you in advance!!!


问:
Kotlin Simplify Boolean Expression
Why do I get a minor error that says "Simplify boolean expression" in my if condition line?

For instance this snippet of code:

```<code>if (isClear==true){
    displayText.setText("")
}
</code>```

答:
Try the following to simply the Boolean expression and avoid the error:</p>

```<code>if (isClear) {
    displayText.setText("")
}
</code>```

Title: Kotlin Simplify Boolean Expression

Body:
Why do I get a minor error that says "Simplify boolean expression" in my if condition line?

For instance this snippet of code:

if (isClear==true){
    displayText.setText("")
}

Body:
Try the following to simply the Boolean expression and avoid the error:

if (isClear) {
    displayText.setText("")
}


问:
sql update multiple values to one column from another table
I have two tables.

table_a      table_b

idA         idB
nameA       nameB
remarkA1    remarkB
remarkA2

Update from Comment: Code I have tired

```<code>UPDATE table_b
SET remarkB = table_a.remarkA1
FROM table_a WHERE table_b.id = table_a.id
</code>```

But this code I can only update one value to column remarkB,If i want update values in table_b from table_a by update values from
remarkA1, remarkA2 to remarkB  How should I write?

答:
You can use the following Update Statement along with you need a string CONCAT

I'm assuming the data type of table_a.remarkA1 and table_a.remarkA2 are string (i.e., VARCHAR)

```<code>UPDATE table_b
SET remarkB = CONCAT(table_a.remarkA1, ' ', table_a.remarkA2)
FROM table_a
WHERE table_b.idB = table_a.idA
</code>```

Body:
I have two tables.

table_a      table_b

idA         idB
nameA       nameB
remarkA1    remarkB
remarkA2

Update from Comment: Code I have tired

UPDATE table_b
SET remarkB = table_a.remarkA1
FROM table_a WHERE table_b.id = table_a.id

But this code I can only update one value to column remarkB,If i want update values in table_b from table_a by update values from
remarkA1, remarkA2 to remarkB  How should I write?

Body:
You can use the following Update Statement along with you need a string CONCAT

I'm assuming the data type of table_a.remarkA1 and table_a.remarkA2 are string (i.e., VARCHAR)

UPDATE table_b
SET remarkB = CONCAT(table_a.remarkA1, ' ', table_a.remarkA2)
FROM table_a
WHERE table_b.idB = table_a.idA


问:
Min / Max of 3d Matrix using different intervals Matlab
I have a 3d matrix A of size MxNxZ. I am searching the minimum for each vector in the Z direction like this.

```<code>I = min(A(:, :, minInterval : maxInterval), [], 3);
</code>```

This is working.

Now I want to have variable intervals for each vector. I have then two 2d matrices as follow :

```<code>minIntervals of size MxN
maxIntervals of size MxN
</code>```

I am then trying this :

```<code>I = min(A(:, :, minIntervals : maxIntervals), [], 3);
</code>```

but it did not work and use only minIntervals(1,1) and maxIntervals(1,1).

Do you have an idea, I don't want to use loop because of the size of the data.

Thank you very much.

答:
You can set matrix values that are outside the interval to Inf and take the min :

In MATLAB r2016b and later:

```<code>z=reshape(1:size(A,3),1,1,[]);
A(z<minInterval | z>maxInterval)=Inf;
I=min(A,[],3);
</code>```

In pre r2016b:

```<code>z=reshape(1:size(A,3),1,1,[]);
A(bsxfun(@lt, z, minInterval) | bsxfun(@gt, z,maxInterval))=Inf;
I=min(A,[],3);
</code>```

Body:
I have a 3d matrix A of size MxNxZ. I am searching the minimum for each vector in the Z direction like this.

I = min(A(:, :, minInterval : maxInterval), [], 3);

This is working.

Now I want to have variable intervals for each vector. I have then two 2d matrices as follow :

minIntervals of size MxN
maxIntervals of size MxN

I am then trying this :

I = min(A(:, :, minIntervals : maxIntervals), [], 3);

but it did not work and use only minIntervals(1,1) and maxIntervals(1,1).

Do you have an idea, I don't want to use loop because of the size of the data.

Thank you very much.

Body:
You can set matrix values that are outside the interval to Inf and take the min :

In MATLAB r2016b and later:

z=reshape(1:size(A,3),1,1,[]);
A(z<minInterval | z>maxInterval)=Inf;
I=min(A,[],3);

In pre r2016b:

z=reshape(1:size(A,3),1,1,[]);
A(bsxfun(@lt, z, minInterval) | bsxfun(@gt, z,maxInterval))=Inf;
I=min(A,[],3);


问:
QMutexLocker, QMutex C2530 references must be initialized
I have QMutex m_mutex; as a private field in my class and I try to lock it using QMutexLocker from one of the methods but when I try to build it I get C2530 error.(My compiler is MSVC 2015).

```<code>#include <QObject>
#include <QMutex>
#include <QMutexLocker>

class MyClass : public QObject
    Q_OBJECT
public:
    MyClass(QObject *parent = 0) : QObject(parent) {}

    void setValue(const SomeEnum& val)
    {
        QMutexLocker(&m_mutex) // C2530
        m_enum = val;
    }
private:
    QMutex m_mutex;
    SomeEnum m_enum;
};
</code>```

EDIT: it works when I use &this->m_mutex

答:
The code should be:

```<code>QMutexLocker something(&m_mutex);
</code>```

which declares a variable called something which is a QMutexLocker, and persists until the end of the block (which is the end of the function in this case).

The code QMutexLocker(&m_mutex); is a slightly vexing parse - it fits the syntax for a reference declaration, i.e. it's the same as QMutexLocker& m_mutex; , which produces the error because references must be initialized.

The code QMutexLocker(&this->m_mutex); does not fit the syntax for a reference declaration, so you don't get that error.  However it creates a temporary QMutexLocker object which is then immediately destroyed. So , even though it does not give a compilation error, it probably doesn't do what you intended: the mutex will be locked and then unlocked before the next statement is executed.

Body:
I have QMutex m_mutex; as a private field in my class and I try to lock it using QMutexLocker from one of the methods but when I try to build it I get C2530 error.(My compiler is MSVC 2015).

#include <QObject>
#include <QMutex>
#include <QMutexLocker>

class MyClass : public QObject
    Q_OBJECT
public:
    MyClass(QObject *parent = 0) : QObject(parent) {}

    void setValue(const SomeEnum& val)
    {
        QMutexLocker(&m_mutex) // C2530
        m_enum = val;
    }
private:
    QMutex m_mutex;
    SomeEnum m_enum;
};

EDIT: it works when I use &this->m_mutex

Body:
The code should be:

QMutexLocker something(&m_mutex);

which declares a variable called something which is a QMutexLocker, and persists until the end of the block (which is the end of the function in this case).

The code QMutexLocker(&m_mutex); is a slightly vexing parse - it fits the syntax for a reference declaration, i.e. it's the same as QMutexLocker& m_mutex; , which produces the error because references must be initialized.

The code QMutexLocker(&this->m_mutex); does not fit the syntax for a reference declaration, so you don't get that error.  However it creates a temporary QMutexLocker object which is then immediately destroyed. So , even though it does not give a compilation error, it probably doesn't do what you intended: the mutex will be locked and then unlocked before the next statement is executed.


问:
Unable to use XPath to select input element based on content
I have a Selenium Webdriver test where I want to wait for a text input field to contain a specific value before moving to the next step. I know what the value will be ("Town of Oakura") and it is set by JavaScript. I tried using the following c# code:

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElement(DpNumber, "Town of Oakura"));
</code>```

This just timed out every time. So I thought I would try XPath to wait for the field to be updated:

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER'
                                                        and text()='Town of Oakura']")));
</code>```

Which also didn't work. Using the console in Chrome I can use XPath to identify the element, defined as:

```<code><input id="DP_NUMBER" type="text" name="DP_NUMBER"
     data-bind="textInput:DP_NUMBER" class="js-bound">
</code>```

Expanding the element I can establish that the value is correct. But I can't find any permutation of XPath that locates the element based on its contents.

答:
text()='Town of Oakura', as well as ExpectedConditions.TextToBePresentInElement, is looking for exact match. Although it might look like an exact match any space or special character will throw the results off. Try using contains

```<code>new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER' and contains(text(), 'Town of Oakura')]")));
</code>```

Body:
I have a Selenium Webdriver test where I want to wait for a text input field to contain a specific value before moving to the next step. I know what the value will be ("Town of Oakura") and it is set by JavaScript. I tried using the following c# code:

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.TextToBePresentInElement(DpNumber, "Town of Oakura"));

This just timed out every time. So I thought I would try XPath to wait for the field to be updated:

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER'
                                                        and text()='Town of Oakura']")));

Which also didn't work. Using the console in Chrome I can use XPath to identify the element, defined as:

<input id="DP_NUMBER" type="text" name="DP_NUMBER"
     data-bind="textInput:DP_NUMBER" class="js-bound">

Expanding the element I can establish that the value is correct. But I can't find any permutation of XPath that locates the element based on its contents.

Body:
text()='Town of Oakura', as well as ExpectedConditions.TextToBePresentInElement, is looking for exact match. Although it might look like an exact match any space or special character will throw the results off. Try using contains

new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout))
    .Until(ExpectedConditions.ElementExists(By.XPath("//input[@id='DP_NUMBER' and contains(text(), 'Town of Oakura')]")));


答:
Simplify your geometries!

The more complex a shape is, the longer it takes for MySQL to tell whether it contains a point or not -- and some countries have very complex shapes indeed. For example, the boundary of Indonesia (which you mentioned in a comment) contains over 18,000 points, most of which define the complex border between Sarawak and Kalimantan.

Unless your application specifically needs to know exactly where a user sits with regard to that border, you'll probably be much better off with a simpler version. There are a number of tools available for this purpose; one popular one is mapshaper.

Title: Slow ST_CONTAINS query in GEOMETRY type SPATIAL INDEX in MySQL 5.7

Body:
I have a table with spatial index. When I run this query, it takes more than 0.7 to return results. Is there a way to make this query faster??
(MySQL 5.7.17 on AWS RDS, InnoDB)

CREATE TABLE

CREATE TABLE `geofences` (
    `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `sticker_key` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_bin',
    `geofence` GEOMETRY NOT NULL,
    `location` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    `expires` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    PRIMARY KEY (`id`),
    SPATIAL INDEX `geofence` (`geofence`)
)COLLATE='utf8mb4_bin'
ENGINE=InnoDB;

QUERY

SELECT geofences.sticker_key FROM geofences WHERE ST_CONTAINS(geofences.geofence, POINT(126.924394,37.552754)) GROUP BY sticker_key;

EXPLAIN

Example Data

This is the smallest row in my geofence table.

MULTIPOLYGON(((126.982169151306 37.5796080752196,126.984980106354 37.5792084484235,126.985055208206 37.5801097313528,126.985623836517 37.5800672182523,126.985656023026 37.5802542757132,126.986804008484 37.5801947574811,126.9868683815 37.5831110948965,126.986482143402 37.5831961175971,126.986385583878 37.5830685835098,126.986138820648 37.5828475239075,126.98569893837 37.582711486903,126.985720396042 37.5819207668924,126.985355615616 37.5817762257676,126.984947919846 37.5817677233397,126.984915733337 37.5814616352904,126.9846367836 37.5814616352904,126.984508037567 37.5817082063176,126.984218358994 37.581878254826,126.983692646027 37.5820398005493,126.98362827301 37.5822608625499,126.983746290207 37.5823373838587,126.983370780945 37.5834086739237,126.983295679092 37.5834766918201,126.983370780945 37.5843269102809,126.983531713486 37.5843609188173,126.983789205551 37.5849730698168,126.982952356338 37.5850580903908,126.982877254486 37.5845139570391,126.982491016388 37.5845479654901,126.982126235962 37.5845564676004,126.982115507126 37.5846329865497,126.981954574585 37.5846329865497,126.981739997864 37.5837147539679,126.981611251831 37.5823118767645,126.981300115585 37.5819972885508,126.980999708176 37.5815041475947,126.98145031929 37.5812235659375,126.981514692307 37.581036510912,126.982115507126 37.5800162024996,126.982308626175 37.5799226735289,126.982169151306 37.5796080752196)))

Some are bigger (like entire nation and such)


问:
How to create a nested object (JSON) of a form input values based on the input name in vanilla JavaScript?
//lets say the form is like below

```<code> <form id="myform">
      <input name="foo" value="parent"/>
      <input name="foo.cat.bar" value="child1"/>
      <input name="foo.cat.biz" value="child2"/>
      <input name="foo.cat.biz.dog.bar" value="child3"/>
  </form>
</code>```

// I want the output to be like this in JSON format based on the input name attr //(this is just an example, want  generic answer and the best way to do it)

```<code>{
    "foo": "parent",
    "foo.cat": {
        "bar": "child1",
        "biz": "child2",
        "foo.cat.biz.dog": {
            "bar": "child3"
        }
    }
}
</code>```

答:
Here you go.  I've included an explanation in the comments...

```<code>function getFormData() {
    /* return nested array combined
       into groups of two. See question @
       https://stackoverflow.com/a/31352555/4746328 */
    function groupIntoPairs(arr) {
        var temp = arr.slice();
        var out = [];

        while (temp.length) {
            out.push(temp.splice(0,2));
        }

        return out;
    }

    /* create a storage object */
    var data = {},
    /* get 'input' elements as an array */
    inputs = [].slice.call(document.getElementById('myform').querySelectorAll('input')),
    /* additional variables */
    name, hold, splits, L, dKey;

    /* loop through input elements */
    inputs.forEach(function(n) {
        name = n.name;

        /* for holding key strings */
        hold = '';

        /* split the 'name' at '.'
           and group into pairs */
        splits = groupIntoPairs( name.split('.') );

        /* index of last item in 'splits' */
        L = splits.length - 1;

        /* if 'splits' has only one
           item add the name-value pair
           to 'data' straight away */
        if (L === 0) {
            data[name] = n.value;
        } else {
            /* loop 'splits' to create keys */
            splits.forEach(function(x, i) {
                /* combine key strings until
                   last item in 'splits' */
                if (i !== L) hold += '.' + x.join('.');
            });

            /* define the key */
            dKey = hold.slice(1);

            /* create 'data[dKey]' Object if
               it doesn't exist or use it
               again if it does */
            data[dKey] = data[dKey] || {};

            /* add last item in 'splits' as
               key for 'data[dKey]' and
               assign current n.value */
            data[dKey][splits[L][0]] = n.value;
        }
    });
    /* return 'data' object */
    return data;
}

console.log('data:', JSON.stringify(getFormData(), null, 4));
/* => data: {
    "foo": "parent",
    "foo.cat": {
        "bar": "child1",
        "biz": "child2"
    },
    "foo.cat.biz.dog": {
        "bar": "child3"
    }
}
*/
</code>```

Hope that helped.

Body:
//lets say the form is like below

 <form id="myform">
      <input name="foo" value="parent"/>
      <input name="foo.cat.bar" value="child1"/>
      <input name="foo.cat.biz" value="child2"/>
      <input name="foo.cat.biz.dog.bar" value="child3"/>
  </form>

// I want the output to be like this in JSON format based on the input name attr //(this is just an example, want  generic answer and the best way to do it)

{
    "foo": "parent",
    "foo.cat": {
        "bar": "child1",
        "biz": "child2",
        "foo.cat.biz.dog": {
            "bar": "child3"
        }
    }
}

Body:
Here you go.  I've included an explanation in the comments...

function getFormData() {
    /* return nested array combined
       into groups of two. See question @
       https://stackoverflow.com/a/31352555/4746328 */
    function groupIntoPairs(arr) {
        var temp = arr.slice();
        var out = [];

        while (temp.length) {
            out.push(temp.splice(0,2));
        }

        return out;
    }

    /* create a storage object */
    var data = {},
    /* get 'input' elements as an array */
    inputs = [].slice.call(document.getElementById('myform').querySelectorAll('input')),
    /* additional variables */
    name, hold, splits, L, dKey;

    /* loop through input elements */
    inputs.forEach(function(n) {
        name = n.name;

        /* for holding key strings */
        hold = '';

        /* split the 'name' at '.'
           and group into pairs */
        splits = groupIntoPairs( name.split('.') );

        /* index of last item in 'splits' */
        L = splits.length - 1;

        /* if 'splits' has only one
           item add the name-value pair
           to 'data' straight away */
        if (L === 0) {
            data[name] = n.value;
        } else {
            /* loop 'splits' to create keys */
            splits.forEach(function(x, i) {
                /* combine key strings until
                   last item in 'splits' */
                if (i !== L) hold += '.' + x.join('.');
            });

            /* define the key */
            dKey = hold.slice(1);

            /* create 'data[dKey]' Object if
               it doesn't exist or use it
               again if it does */
            data[dKey] = data[dKey] || {};

            /* add last item in 'splits' as
               key for 'data[dKey]' and
               assign current n.value */
            data[dKey][splits[L][0]] = n.value;
        }
    });
    /* return 'data' object */
    return data;
}

console.log('data:', JSON.stringify(getFormData(), null, 4));
/* => data: {
    "foo": "parent",
    "foo.cat": {
        "bar": "child1",
        "biz": "child2"
    },
    "foo.cat.biz.dog": {
        "bar": "child3"
    }
}
*/

Hope that helped.


答:
The simplest way basing on your code:</p>

```<code>for (var i = 0; i < length; i++) {
  var color;
  if(data[i] <=10) {
    color = "ff0000";
  } else{
    color = "0000ff";
  }

  jQuery("#dailydata").append(
    "<table class='table'><tr>" +
    "<th style="background-color:#" + color +
    ">Min Temp : </th><td>" + data[i]</td>" +
    "</tr></table>");
}
</code>```

Title: Assigning dynamic ids to elements using jQuery

Body:
The simplest way basing on your code:

for (var i = 0; i < length; i++) {
  var color;
  if(data[i] <=10) {
    color = "ff0000";
  } else{
    color = "0000ff";
  }

  jQuery("#dailydata").append(
    "<table class='table'><tr>" +
    "<th style="background-color:#" + color +
    ">Min Temp : </th><td>" + data[i]</td>" +
    "</tr></table>");
}


问:
How to remove an element found in an array and shift the array elements to the left?
```<code>int search(int a[]) {

   int i,V,index;
   printf("Enter the element (V),That you want to find:>");
   scanf("%d",&V);

   for (i=0;i<N;i++) {
       if(a[i]==V) {
           V=a[i];
           index=i;
       }
   }
   printf("%d is located in a[%d].",V,index
)
</code>```

答:
C arrays cannot be resized, so you cannot do this without creating a new array. Some suggestions you could implement:

Mark the item as deleted (lazy deletion) by either having a second deleted bool array or setting the item to some unused value such as -1.

Use vectors, but then this is not C anymore. STL vectors have an erase() method.

Vectors will be inefficient to delete from, so depending on the other operations you perform you could use a deque. Again, this then becomes C++, but you can also use erase() on a deque.


问:
Adding Text under each image in image gallery
I tried using p tag with max-width attribute but in doesn't worked for me:

```<code>.a {
     max-width:100px;
}
</code>```

With HTML:

```<code><p class="a">Hello Welcome to Stackoverflow.</p>
</code>```

I want this text to be fit under image of resolution 500*500. If the text goes more than image width it should be automatically wrapped in next line.

答:
Use This Code

div {
  height: auto;
  width: 500px;
}

img {
  height: 100%;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>

</head>

<body>

  <div>
  <img src="img.jpg" />
  <p>Hello Welcome to Stackoverflow</p>
  </div>
</body>

</html></code>```

Body:
I tried using p tag with max-width attribute but in doesn't worked for me:

.a {
     max-width:100px;
}

With HTML:

Hello Welcome to Stackoverflow.

I want this text to be fit under image of resolution 500*500. If the text goes more than image width it should be automatically wrapped in next line.

Body:
Use This Code

div {
  height: auto;
  width: 500px;
}

img {
  height: 100%;
  width: 100%;
}

<html>

<head>

</head>

<body>

  <div>
  <img src="img.jpg" />
  <p>Hello Welcome to Stackoverflow</p>
  </div>
</body>

</html>


答:
I don't know is this what you need, just check this snippet

.image_wrap {
  width: 300px;
}
.image_wrap img {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image_wrap">
 <img src="http://dreamicus.com/data/garden/garden-06.jpg" alt="garden" />
 <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has</p>
</div></code>```

Title: Adding Text under each image in image gallery

Body:
I don't know is this what you need, just check this snippet

.image_wrap {
  width: 300px;
}
.image_wrap img {
  width: 100%;
}

<div class="image_wrap">
 <img src="http://dreamicus.com/data/garden/garden-06.jpg" alt="garden" />
 <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has</p>
</div>


问:
Make a specific screen transparent react navigation
I am trying to make a specific screen have a transparent background using react navigation but I only want this behaviour on this specific screen. I am stuck because I have tried the following approach:

```<code>export const MainNavigator = StackNavigator({
  ScreenOne: {
    screen: ScreenOne
  },
  ScreenTwo: {
    screen: ScreenTwoNavigator
  },
  ScreenThree: {
    screen: ScreenThreeNavigator,
  },
}, {
  headerMode: 'none',
  mode: 'modal',
    cardStyle: {
      opacity: 0.1,
   },
})
</code>```

However, this results in the opacity being applied to all the screens. I have also tried removing the opacity from this and instead setting it within the ScreenThreeNavigator, which contains only the single screen that i wish to have as transparent. This had no impact whatsoever. I have also tried setting the background color of the View for this screen as transparent but this also did not work.

答:
I was able to resolve the problem by instead taking this approach and not using a separate screen:

Add an overlay to a react-navigation navigator

Body:
I am trying to make a specific screen have a transparent background using react navigation but I only want this behaviour on this specific screen. I am stuck because I have tried the following approach:

export const MainNavigator = StackNavigator({
  ScreenOne: {
    screen: ScreenOne
  },
  ScreenTwo: {
    screen: ScreenTwoNavigator
  },
  ScreenThree: {
    screen: ScreenThreeNavigator,
  },
}, {
  headerMode: 'none',
  mode: 'modal',
    cardStyle: {
      opacity: 0.1,
   },
})

However, this results in the opacity being applied to all the screens. I have also tried removing the opacity from this and instead setting it within the ScreenThreeNavigator, which contains only the single screen that i wish to have as transparent. This had no impact whatsoever. I have also tried setting the background color of the View for this screen as transparent but this also did not work.


问:
Windows Task Scheduler wont run ren command, but cmd.exe will
I am creating a task that executes a batch file for ftp uploads.

The batch script just renames any file in a certain folder to an appropriate name, then uploads that folder.

I have set the task to run under a service account, when I log in with the service account and run the .bat file it works perfectly. When I run the task scheduler it runs the .bat file but the log shows that the ren command doesn't work.

Here is the output from the log after being invoked via task scheduler:

```<code>c:\TEMP\Bulletin>rename "R:\x\x\x\*.pdf" Bulletin.pdf

c:\TEMP\Bulletin>chdir c:\Program Files (x86)\WinSCP

c:\Program Files (x86)\WinSCP>WinSCP.com /ini=nul /script=c:\TEMP\Bulletin\bulletin.tmp
Searching for host...
Connecting to host...
Authenticating...
Using username "svc-bulletin".
Authenticating with pre-entered password.
Authenticated.
Starting the session...
Session started.
Active session: [1] svc-bulletin@x.x.x
File or folder 'C:\FileShares\Drive-R\x\x\x\Bulletin.pdf' does not exist.
System Error.  Code: 2.

The system cannot find the file specified
(A)bort, (R)etry, (S)kip, Ski(p) all: Abort

c:\Program Files (x86)\WinSCP>exit
</code>```

Here is the output from just manually invoking the .bat file:

```<code>C:\TEMP\Bulletin>rename "R:\x\x\x\*.pdf" Bulletin.pdf

C:\TEMP\Bulletin>chdir c:\Program Files (x86)\WinSCP

c:\Program Files (x86)\WinSCP>WinSCP.com /ini=nul /script=c:\TEMP\Bulletin\bulletin.tmp
Searching for host...
Connecting to host...
Authenticating...
Using username "svc-bulletin".
Authenticating with pre-entered password.
Authenticated.
Starting the session...
Session started.
Active session: [1] svc-bulletin@x.x.x
C:\FileShares\Drive-R\x\x\x\Bulletin.pdf |         957 KB | 1390.5 KB/s | binary | 100%

c:\Program Files (x86)\WinSCP>exit
</code>```

I am running the task with full permissions and have also tried starting it in the same directory as the .bat and without, neither works. Appreciate any pointers/ideas.

答: I'm, assuming R: is a mapped drive. Mapped drives are established when a user logs on as they are only mapped for the user that did the mapping. The service account doesn't know anything about mapped drives that are mapped under your account. To complicate the issue the task may be running under S4U authentication depending on your task settings so you won't have access to network resources. That also eliminates using a UNC rather than a mapped drive. See technet.microsoft.com/en-us/library/cc722152(v=ws.11).aspx</p>

Body:
I am creating a task that executes a batch file for ftp uploads.

The batch script just renames any file in a certain folder to an appropriate name, then uploads that folder.

I have set the task to run under a service account, when I log in with the service account and run the .bat file it works perfectly. When I run the task scheduler it runs the .bat file but the log shows that the ren command doesn't work.

Here is the output from the log after being invoked via task scheduler:

c:\TEMP\Bulletin>rename "R:\x\x\x\*.pdf" Bulletin.pdf

c:\TEMP\Bulletin>chdir c:\Program Files (x86)\WinSCP

c:\Program Files (x86)\WinSCP>WinSCP.com /ini=nul /script=c:\TEMP\Bulletin\bulletin.tmp
Searching for host...
Connecting to host...
Authenticating...
Using username "svc-bulletin".
Authenticating with pre-entered password.
Authenticated.
Starting the session...
Session started.
Active session: [1] svc-bulletin@x.x.x
File or folder 'C:\FileShares\Drive-R\x\x\x\Bulletin.pdf' does not exist.
System Error.  Code: 2.

The system cannot find the file specified
(A)bort, (R)etry, (S)kip, Ski(p) all: Abort

c:\Program Files (x86)\WinSCP>exit

Here is the output from just manually invoking the .bat file:

C:\TEMP\Bulletin>rename "R:\x\x\x\*.pdf" Bulletin.pdf

C:\TEMP\Bulletin>chdir c:\Program Files (x86)\WinSCP

c:\Program Files (x86)\WinSCP>WinSCP.com /ini=nul /script=c:\TEMP\Bulletin\bulletin.tmp
Searching for host...
Connecting to host...
Authenticating...
Using username "svc-bulletin".
Authenticating with pre-entered password.
Authenticated.
Starting the session...
Session started.
Active session: [1] svc-bulletin@x.x.x
C:\FileShares\Drive-R\x\x\x\Bulletin.pdf |         957 KB | 1390.5 KB/s | binary | 100%

c:\Program Files (x86)\WinSCP>exit

I am running the task with full permissions and have also tried starting it in the same directory as the .bat and without, neither works. Appreciate any pointers/ideas.


问:
Two inputs, generate link
Trying to generate link from two input fields, title and link text. It should be generated as you type. Here is what I got so far:</p>

```<code><input type="text" id="title" value="" placeholder="Paste title"/><br>
<input type="text" id="link" value="" placeholder="Paste link"/>
<br>
<br>

Title: <span id="text_1"></span>
<script type="text/javascript">
$("#title").keyup(function() {
  $("#text_1").text($("#title").val());
})
</script>
<br>
<br>

Link <span id="text_1_link"></span>
<script type="text/javascript">
$("#link").keyup(function() {
  $("#text_1_link").text($("#link").val());
})
</script>
<br>
<br>

Combined here:
</code>```

答:
I think you're lloking somthing like following:

$("#link").keyup(function() {
  $("#text_1_link").text($("#link").val());
  $(".link").attr('href',$("#link").val());

})
$("#title").keyup(function() {
  $("#text_1").text($("#title").val());
  $(".link").text($("#title").val());
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="title" value="" placeholder="Paste title"/><br>
<input type="text" id="link" value="" placeholder="Paste link"/>
<br>
<br>

Title: <span id="text_1"></span>
<br>
<br>

Link <span id="text_1_link"></span>
<br>
<br>

Combined here: </code>```

Title: Two inputs, generate link

Body:
Trying to generate link from two input fields, title and link text. It should be generated as you type. Here is what I got so far:

<input type="text" id="title" value="" placeholder="Paste title"/>

<input type="text" id="link" value="" placeholder="Paste link"/>

Title:

Link

Combined here:

Body:
I think you're lloking somthing like following:

$("#link").keyup(function() {
  $("#text_1_link").text($("#link").val());
  $(".link").attr('href',$("#link").val());

})
$("#title").keyup(function() {
  $("#text_1").text($("#title").val());
  $(".link").text($("#title").val());
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="title" value="" placeholder="Paste title"/><br>
<input type="text" id="link" value="" placeholder="Paste link"/>
<br>
<br>

Title: <span id="text_1"></span>
<br>
<br>

Link <span id="text_1_link"></span>
<br>
<br>

Combined here: <a href="#" class="link"></a>


问:
Where best to throw exception in this example?
In a library I am writing, I have some methods which would only be executed very rarely and on the fly. As I am modelling a vehicle, one of the (Exceptional) methods is a cracked engine, which would be very rare. Should  I throw an exception in this method? This will stop a vehicle from being usable.

I read the .NET Design Framework Guidelines book and it states that an exception should only occur when a method cannot complete execution. The actual engine cracked method will always complete, but if one of my methods, such as start engine (this method will store the amount of engine starts as a means of accruing stress to the engine), is called and results in a call to cracked engine, where (if anywhere) should I throw an exception?

答:
I believe your Car model needs to have a variable declared like so:

```<code>bool isEngineCracked;
</code>```

Then when you make a call to the crackedEngine(Car car) method it will return a bool

This in turn will allow you to do state checking of the engine to see if it's engine is functioning or not.

Body:
I believe your Car model needs to have a variable declared like so:

bool isEngineCracked;

Then when you make a call to the crackedEngine(Car car) method it will return a bool

This in turn will allow you to do state checking of the engine to see if it's engine is functioning or not.