问:
Related to card view patterns

I know that they are not Card View in the picture(i am using this picture just for reference to make you guys understand what I'm saying). But, I want to create a card view making some angle.

答:
Didn't you try android:rotation ?

It's available since api level 11.

```<code>  <android.support.v7.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_view"
            android:layout_gravity="center"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:rotation="90"
       card_view:cardCornerRadius="4dp">

            <TextView
                android:id="@+id/info_text"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </android.support.v7.widget.CardView>
</code>```

Title: Related to card view patterns

Body:
Didn't you try android:rotation ?

It's available since api level 11.

  <android.support.v7.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_view"
            android:layout_gravity="center"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:rotation="90"
       card_view:cardCornerRadius="4dp">

            <TextView
                android:id="@+id/info_text"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </android.support.v7.widget.CardView>


来源: stackexchange

问:
Is a For Loop always executed at least once?
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

```<code>for (int i=6; i <=5; i++) {
    //irrelevant for this question
}
</code>```

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.

答:
A loop will only execute while its condition is true.  Since a for loop and a while loop both check the condition before the body is executed they will never execute if the condition is false.

The only loop that will is a do while loop.  With a do while loop the condition is not evaluated until the end of the loop.  Because of that a do while loop will always execute at least once.

ContentLicense: CC BY-SA 3.0

Body:
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

for (int i=6; i <=5; i++) {
    //irrelevant for this question
}

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.

ContentLicense: CC BY-SA 4.0


问:
can i create ImageView programmatically before setcontentview android
can i initialize ImageView or any other view programmatically before setContentView(R.layout.activity_main); in android??

actually i am getting an instance of a custom class (not activity)
before onCreate method globally
like this

```<code>MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);
</code>```

and in that class constructor i have to use that context to initialize my preference class

```<code>public MyInAppPurchaseBilling(Activity launcher) {
        this.activity = launcher;
        tinyDB= new TinyDB(launcher);
    }
</code>```

Here is my logcat of error that i am facing

```<code>07-05 17:22:01.852 9660-9660/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.write.urdu.poetry.urdutexteditor, PID: 9660
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.write.urdu.poetry.urdutexteditor/com.write.urdu.poetry.urdutexteditor.MenuClass}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
    at com.write.urdu.poetry.urdutexteditor.TinyDB.<init>(TinyDB.java:55)
    at com.write.urdu.poetry.urdutexteditor.inapppurchase.MyInAppPurchaseBilling.<init>(MyInAppPurchaseBilling.java:48)
    at com.write.urdu.poetry.urdutexteditor.MenuClass.<init>(MenuClass.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
</code>```

答:
here is my MenuClass Activity code i initialize TinyDB in MenuClass onCreate() method before setContentView() and did my work after getting saved boolean value from preference class

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

TinyDB tinyDB;
    MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myInAppPurchaseBilling.onCreate();

    tinyDB= new TinyDB(MenuClass.this);
        if (!tinyDB.getBoolean(Constant.isAdsDisabled)) {
//do your work
        }
        setContentView(R.layout.activity_menu_class);
   }
}
</code>```

and this is the code of my MyInAppPurchaseBilling class i did nothing in its constructor but created separate method of onCreate just like activity's onCreate and initialize TinyDB in it and Called that onCreate method of this class in MenuClass onCreate after super.*** line...in this way i initialize TinyDB in MyInAppPurchaseBilling class successfully to put boolean value at start of app and get that boolean value in Menuclass afterward to further processing

```<code>      public class MyInAppPurchaseBilling {

            private TinyDB tinyDB;
            Activity activity;

            public MyInAppPurchaseBilling(Activity launcher) {
                this.activity = launcher;
            }

            public void onCreate() {
                tinyDB= new TinyDB(activity);
    }
}
</code>```

Body:
can i initialize ImageView or any other view programmatically before setContentView(R.layout.activity_main); in android??

actually i am getting an instance of a custom class (not activity)
before onCreate method globally
like this

MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);

and in that class constructor i have to use that context to initialize my preference class

public MyInAppPurchaseBilling(Activity launcher) {
        this.activity = launcher;
        tinyDB= new TinyDB(launcher);
    }

Here is my logcat of error that i am facing

07-05 17:22:01.852 9660-9660/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.write.urdu.poetry.urdutexteditor, PID: 9660
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.write.urdu.poetry.urdutexteditor/com.write.urdu.poetry.urdutexteditor.MenuClass}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
    at com.write.urdu.poetry.urdutexteditor.TinyDB.<init>(TinyDB.java:55)
    at com.write.urdu.poetry.urdutexteditor.inapppurchase.MyInAppPurchaseBilling.<init>(MyInAppPurchaseBilling.java:48)
    at com.write.urdu.poetry.urdutexteditor.MenuClass.<init>(MenuClass.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

Body:
here is my MenuClass Activity code i initialize TinyDB in MenuClass onCreate() method before setContentView() and did my work after getting saved boolean value from preference class

public class MenuClass extends Activity {

TinyDB tinyDB;
    MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myInAppPurchaseBilling.onCreate();

    tinyDB= new TinyDB(MenuClass.this);
        if (!tinyDB.getBoolean(Constant.isAdsDisabled)) {
//do your work
        }
        setContentView(R.layout.activity_menu_class);
   }
}

and this is the code of my MyInAppPurchaseBilling class i did nothing in its constructor but created separate method of onCreate just like activity's onCreate and initialize TinyDB in it and Called that onCreate method of this class in MenuClass onCreate after super.*** line...in this way i initialize TinyDB in MyInAppPurchaseBilling class successfully to put boolean value at start of app and get that boolean value in Menuclass afterward to further processing

      public class MyInAppPurchaseBilling {

            private TinyDB tinyDB;
            Activity activity;

            public MyInAppPurchaseBilling(Activity launcher) {
                this.activity = launcher;
            }

            public void onCreate() {
                tinyDB= new TinyDB(activity);
    }
}


问:
Spring boot java.util.MissingResourceException while accessing properties file
In spring boot application i have the below code for accessing the properties file(errors.properties), when I access the code it gives the below exception:

```<code>exception":"java.util.MissingResourceException","message":"Can't find bundle for base name errors.properties
</code>```

the errors.properties file is under src/main/resources/

Below is the code

```<code>@Configuration
@PropertySource("classpath:errors.properties") // tried with both the annotations
@ConfigurationProperties("classpath:errors.properties") //  tried with both the annotations
public class ApplicationProperties {

    public static String getProperty(final String key) {
        ResourceBundle bundle = ResourceBundle.getBundle("errors.properties");
        return bundle.getString(key);
    }
}
</code>```

I am not able to understand why its not picking up the errors.properties file under resources folder, could somebody please help me?

答:
This might be useful to get the value from properties file. But may not be useful to support i18n.</p>

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * This class loads the property file and returns the property file values.
 *
 */
@Component
@Configuration
@PropertySource("classpath:errors.properties")
public class ApplicationProperties {

    @Autowired
    private Environment env;

    public static String getProperty(final String key) {
        return env.getProperty(key, "");
    }
}
</code>```

Body:
In spring boot application i have the below code for accessing the properties file(errors.properties), when I access the code it gives the below exception:

exception":"java.util.MissingResourceException","message":"Can't find bundle for base name errors.properties

the errors.properties file is under src/main/resources/

Below is the code

@Configuration
@PropertySource("classpath:errors.properties") // tried with both the annotations
@ConfigurationProperties("classpath:errors.properties") //  tried with both the annotations
public class ApplicationProperties {

    public static String getProperty(final String key) {
        ResourceBundle bundle = ResourceBundle.getBundle("errors.properties");
        return bundle.getString(key);
    }
}

I am not able to understand why its not picking up the errors.properties file under resources folder, could somebody please help me?

Body:
This might be useful to get the value from properties file. But may not be useful to support i18n.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * This class loads the property file and returns the property file values.
 *
 */
@Component
@Configuration
@PropertySource("classpath:errors.properties")
public class ApplicationProperties {

    @Autowired
    private Environment env;

    public static String getProperty(final String key) {
        return env.getProperty(key, "");
    }
}


问:
NodeJS & Express authentication middleware not functioning correctly
I am attempting to run the function isUserAuthenticated on every request to the server by requiring it in app.js and 'using' it as so: app.use(authenticate.isUserAuthenticated).

I have an /authenticate callback route that is being POSTED to by our SAML Identity Provider which contains the information required to validate the user and the session.  This is what is inside my authenticate.js file:

```<code>module.exports = router;
module.exports.isUserAuthenticated = function(req, res, next) {
    console.log(req.cookies.subject);
  if (req.cookies.subject) {
      console.log(req.cookies.subject)
    return next();
    } res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");
}
</code>```

As referenced, this authentication function is being required and used in app.js: authenticate = require('./routes/authenticate'), and app.use(authenticate.isUserAuthenticated).

The problem: No matter what variation of the if statement to verify if the subject cookie is present in the request, the authentication check is not being fired and the redirect to the IDP authentication route is not being redirected too.  The console.log checks in the code above are returning:

undefined, and
{}.

Authentication was working on a single route when I was using the isUserAuthenticated function manually like this: router.use('/', isUserAuthenticated, function(req, res, next) {..., but I am trying to use this function globally so I don't have to manually incorporate this middleware on each route.

Any advice/suggestions would be greatly appreciated.  Thank you.

答:
A middleware needs to be set on router object if you are using express js

```<code>router.use(isUserAuthenticated)
</code>```

Don't forget to put this on the top of your routes file.

See the difference between app level and router level middleware here

Body:
I am attempting to run the function isUserAuthenticated on every request to the server by requiring it in app.js and 'using' it as so: app.use(authenticate.isUserAuthenticated).

I have an /authenticate callback route that is being POSTED to by our SAML Identity Provider which contains the information required to validate the user and the session.  This is what is inside my authenticate.js file:

module.exports = router;
module.exports.isUserAuthenticated = function(req, res, next) {
    console.log(req.cookies.subject);
  if (req.cookies.subject) {
      console.log(req.cookies.subject)
    return next();
    } res.redirect("LINK TO IDP FOR VERIFICATION, callback func. is then ran to get value of user and session");
}

As referenced, this authentication function is being required and used in app.js: authenticate = require('./routes/authenticate'), and app.use(authenticate.isUserAuthenticated).

The problem: No matter what variation of the if statement to verify if the subject cookie is present in the request, the authentication check is not being fired and the redirect to the IDP authentication route is not being redirected too.  The console.log checks in the code above are returning:

undefined, and
{}.

Authentication was working on a single route when I was using the isUserAuthenticated function manually like this: router.use('/', isUserAuthenticated, function(req, res, next) {..., but I am trying to use this function globally so I don't have to manually incorporate this middleware on each route.

Any advice/suggestions would be greatly appreciated.  Thank you.

Body:
A middleware needs to be set on router object if you are using express js

router.use(isUserAuthenticated)

Don't forget to put this on the top of your routes file.

See the difference between app level and router level middleware here


问:
Incompatible types in assignments of 'float*' to 'float* [1000]'
```<code>float a[1000];
float b[1000];
float c[1000];

int main()
{
    float *w1;
    w1 = &a;
    float *w2[1000];
    w2 = &b;
    ...
}
</code>```

so error: cannot convert float (*)[1000] to float* in assignments - to w1
and compiler throws error: incompatible types in assignments of float* to float * [1000] to w2

答:
```<code>float *w2[1000];
</code>```

is erroneous, and should be float *w2;

```<code>float a[1000];
float b[1000];
float c[1000];

int main()
{
float *w1;
w1 = a;
float *w2;
w2 = b;
}
</code>```

compiles with no error.

The '&' is intended for single variables, not arrays of single variables. When you instantiate an array with [] your variable actually transforms into a pointer.

Body:
float a[1000];
float b[1000];
float c[1000];

int main()
{
    float *w1;
    w1 = &a;
    float *w2[1000];
    w2 = &b;
    ...
}

so error: cannot convert float (*)[1000] to float* in assignments - to w1
and compiler throws error: incompatible types in assignments of float* to float * [1000] to w2

Body:
float *w2[1000];

is erroneous, and should be float *w2;

float a[1000];
float b[1000];
float c[1000];

int main()
{
float *w1;
w1 = a;
float *w2;
w2 = b;
}

compiles with no error.

The '&' is intended for single variables, not arrays of single variables. When you instantiate an array with [] your variable actually transforms into a pointer.


问:
Office Add-in JavaScript FileDownload not working with MAC
We are having an issue in office add-in with Mac. We can't download file from office-add-in on mac. Same add-in working fine with windows platform.

We have constructed as blob type data from our API Response. Same blob type passing into FileSaver.js of SaveAs method. We are using FileSaver.js to saving files on the word office add-ins.

Note : Everything work fine on windows platform. We already have implementation of html download link attribute same as in following link sample but that won't be use due to security concern.

https://github.com/OfficeDev/Office-Add-in-JavaScript-FileDownload

Force download a pdf link using javascript/ajax/jquery

Here are the our sample code.

var getMessageUrl = "https://test.xxx.xxx/api/xxx/testcontroller/GetTest?id=121212121212";

   var oReq = new XMLHttpRequest();

   oReq.open("GET", getMessageUrl, true);
   oReq.responseType = "arraybuffer";
   oReq.setRequestHeader('X_ConnectTo', 'X-Author-CRM');
   oReq.setRequestHeader('Access-Control-Allow-Origin', '*');
   oReq.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
   oReq.setRequestHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type,Accept, Origin');
   oReq.setRequestHeader('Authorization', 'Bearer XXXXXXXXX-Token-XXXXXXX');
   oReq.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
   oReq.onload = function (oEvent) {
    var blob = new Blob([oReq.response], { type: "application/octet-binary" });
    saveAs(blob, 'Test1234.docx');
   };

   oReq.send();```

here

we are getting following issue on mac

答: I wonder if the issue is similar to what we found with Script Lab, https://github.com/OfficeDev/script-lab/issues/458?  If so, it may be a platform bug/limitation, though it would be good to investigate it further.  See more in that issue.  If you can confirm whether it's the same issue or not, it would be a good first step.  Thanks!</p>

Body:
We are having an issue in office add-in with Mac. We can't download file from office-add-in on mac. Same add-in working fine with windows platform.

We have constructed as blob type data from our API Response. Same blob type passing into FileSaver.js of SaveAs method. We are using FileSaver.js to saving files on the word office add-ins.

Note : Everything work fine on windows platform. We already have implementation of html download link attribute same as in following link sample but that won't be use due to security concern.

https://github.com/OfficeDev/Office-Add-in-JavaScript-FileDownload

Force download a pdf link using javascript/ajax/jquery

Here are the our sample code.

var getMessageUrl = "https://test.xxx.xxx/api/xxx/testcontroller/GetTest?id=121212121212";

   var oReq = new XMLHttpRequest();

   oReq.open("GET", getMessageUrl, true);
   oReq.responseType = "arraybuffer";
   oReq.setRequestHeader('X_ConnectTo', 'X-Author-CRM');
   oReq.setRequestHeader('Access-Control-Allow-Origin', '*');
   oReq.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
   oReq.setRequestHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type,Accept, Origin');
   oReq.setRequestHeader('Authorization', 'Bearer XXXXXXXXX-Token-XXXXXXX');
   oReq.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
   oReq.onload = function (oEvent) {
    var blob = new Blob([oReq.response], { type: "application/octet-binary" });
    saveAs(blob, 'Test1234.docx');
   };

   oReq.send();

here

we are getting following issue on mac


问:
Excel Macro: Copy Sheets from Multiple Workbooks WITH Added Refresh Capability
I am looking to merge sheets in multiple Excel files into one master file with refresh/update functionality.

To be more specific, I have ~25 workbooks in one folder which are identical in structure and vary based on entity.  Each file has one sheet, which is identical to the name of the file.  Each entity will update their specific file each week with up-to-date number values.  I want to create a macro which will:

Copy the one worksheet from each file and paste them in one "Master" workbook.

Have the added functionality which allows me to "refresh" these copy/pasted tabs each week.

I have this code thus far:

```<code>Sub ConslidateWorkbooks()
'Code to pull sheets from multiple Excel files in one file directory
'into master "Consolidation" sheet.

Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet

Application.ScreenUpdating = False
FolderPath = "....."       'I have this filled in my code
Filename = Dir(FolderPath & "*.xls*")

Do While Filename <> ""
 Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
 For Each Sheet In ActiveWorkbook.Sheets
 Sheet.Copy After:=ThisWorkbook.Sheets(1)
 Next Sheet
 Workbooks(Filename).Close
 Filename = Dir()
Loop

Application.ScreenUpdating = True

End Sub
</code>```

This code works fine to pull the data from multiple workbooks into a master workbook, but I need to add some sort of refresh capability WITHOUT deleting and re-copying the tabs (because I have links in other tabs in the Master sheet which will become #REF if sheets are deleted and re-copied).

Thank you for your help in advance.

答:
Basically you want to refresh the worksheet's data if it already exists in ThisWorkbook, otherwise copy/add it. You can use this subroutine to accomplish this:

```<code>Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet)
  Dim ws As Worksheet
  On Error Resume Next
  Set ws = destWb.Worksheets(sourceWs.Name)
  On Error GoTo 0
  If ws Is Nothing Then
    sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.count)
  Else
    ws.Cells.ClearContents
    ws.Range(sourceWs.UsedRange.Address).value = sourceWs.UsedRange.Value2
  End If
End Sub
</code>```

Now to use this, change this line from your routine's code:

```<code>Sheet.Copy After:=ThisWorkbook.Sheets(1)
</code>```

into:

```<code>copyOrRefreshSheet ThisWorkbook, sheet
</code>```

Body:
I am looking to merge sheets in multiple Excel files into one master file with refresh/update functionality.

To be more specific, I have ~25 workbooks in one folder which are identical in structure and vary based on entity.  Each file has one sheet, which is identical to the name of the file.  Each entity will update their specific file each week with up-to-date number values.  I want to create a macro which will:

Copy the one worksheet from each file and paste them in one "Master" workbook.

Have the added functionality which allows me to "refresh" these copy/pasted tabs each week.

I have this code thus far:

Sub ConslidateWorkbooks()
'Code to pull sheets from multiple Excel files in one file directory
'into master "Consolidation" sheet.

Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet

Application.ScreenUpdating = False
FolderPath = "....."       'I have this filled in my code
Filename = Dir(FolderPath & "*.xls*")

Do While Filename <> ""
 Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
 For Each Sheet In ActiveWorkbook.Sheets
 Sheet.Copy After:=ThisWorkbook.Sheets(1)
 Next Sheet
 Workbooks(Filename).Close
 Filename = Dir()
Loop

Application.ScreenUpdating = True

End Sub

This code works fine to pull the data from multiple workbooks into a master workbook, but I need to add some sort of refresh capability WITHOUT deleting and re-copying the tabs (because I have links in other tabs in the Master sheet which will become #REF if sheets are deleted and re-copied).

Thank you for your help in advance.

Body:
Basically you want to refresh the worksheet's data if it already exists in ThisWorkbook, otherwise copy/add it. You can use this subroutine to accomplish this:

Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet)
  Dim ws As Worksheet
  On Error Resume Next
  Set ws = destWb.Worksheets(sourceWs.Name)
  On Error GoTo 0
  If ws Is Nothing Then
    sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.count)
  Else
    ws.Cells.ClearContents
    ws.Range(sourceWs.UsedRange.Address).value = sourceWs.UsedRange.Value2
  End If
End Sub

Now to use this, change this line from your routine's code:

Sheet.Copy After:=ThisWorkbook.Sheets(1)

into:

copyOrRefreshSheet ThisWorkbook, sheet


问:
Change Background Color with jQuery
I have a form with multiple drop downs... I would like to set the background color of the visible dropdowns to gray when they are disabled. All of these dropdown's id's begin with usrControl. Here is what I have this far..

```<code>    $('select[id ^= "usrControl"]:visible').each(function(){
this.css("background-color")
});
</code>```

Not sure how to get the disabled/enabled selectors.

Thanks in advance

```<code>Protected _picklistColorScriptText As String = "$(document).ready(function(){ " + _
                                                "$('[id ^= ""usrControl""]:visible:disabled').css(""background-color"", '#DCDCDC'); " + _
                                                "$('[id ^= ""usrControl""]:visible:enabled').css(""background-color"", '#FFFFFF');" + _
                                                "});"
</code>```

This works. However, this sets the background for the entire control to gray, how can I change the color of the selected item to gray?

答:
I believe you are looking for</p>

```<code>$('select[id ^="usrControl":visible:disabled].each(...
</code>```

ContentLicense: CC BY-SA 2.5

Title: Change Background Color with jQuery

Body:
I have a form with multiple drop downs... I would like to set the background color of the visible dropdowns to gray when they are disabled. All of these dropdown's id's begin with usrControl. Here is what I have this far..

    $('select[id ^= "usrControl"]:visible').each(function(){
this.css("background-color")
});

Not sure how to get the disabled/enabled selectors.

Thanks in advance

Protected _picklistColorScriptText As String = "$(document).ready(function(){ " + _
                                                "$('[id ^= ""usrControl""]:visible:disabled').css(""background-color"", '#DCDCDC'); " + _
                                                "$('[id ^= ""usrControl""]:visible:enabled').css(""background-color"", '#FFFFFF');" + _
                                                "});"

This works. However, this sets the background for the entire control to gray, how can I change the color of the selected item to gray?

Body:
I believe you are looking for

$('select[id ^="usrControl":visible:disabled].each(...


问:
Addition of integers from two different list of lists of unicode object and integer
I have a list of lists of unicode object and integer as follows. There are two such lists and I want to add the integer values of both these lists if the unicode objects(date&time) match

```<code>list1 = [ [u'2015-01-01T05:00:00.000Z', 58],[u'2015-01-01T05:15:00.000Z', 57],[u'2015-01-01T05:30:00.000Z', 55],
[u'2015-01-01T05:45:00.000Z', 54] ]

list2 = [ [u'2015-01-01T05:00:00.000Z', 65],[u'2015-01-01T05:15:00.000Z', 67],[u'2015-01-01T05:30:00.000Z', 61],
[u'2015-01-01T05:45:00.000Z', 74] ]
</code>```

I created a dictionary object with date&time as a key and integer as a value. I tried to add the integers if the key matches. However, a dictionary does not give me date&time in order when I try to save the output in a CSV. I am fairly new to python and I am sure there are more sophisticated ways to do this.

答:
you can sort the keys like so:

```<code>for key in sorted(dict.keys()):
   #keys will now appear in a sorted way
</code>```

Body:
I have a list of lists of unicode object and integer as follows. There are two such lists and I want to add the integer values of both these lists if the unicode objects(date&time) match

list1 = [ [u'2015-01-01T05:00:00.000Z', 58],[u'2015-01-01T05:15:00.000Z', 57],[u'2015-01-01T05:30:00.000Z', 55],
[u'2015-01-01T05:45:00.000Z', 54] ]

list2 = [ [u'2015-01-01T05:00:00.000Z', 65],[u'2015-01-01T05:15:00.000Z', 67],[u'2015-01-01T05:30:00.000Z', 61],
[u'2015-01-01T05:45:00.000Z', 74] ]

I created a dictionary object with date&time as a key and integer as a value. I tried to add the integers if the key matches. However, a dictionary does not give me date&time in order when I try to save the output in a CSV. I am fairly new to python and I am sure there are more sophisticated ways to do this.

Body:
you can sort the keys like so:

for key in sorted(dict.keys()):
   #keys will now appear in a sorted way


问:
Children :before content inheritance
The title might be a little bit confusing but I wonder why is it impossible for a child element to inherit it's parent ::before content. for example:

HTML:

```<code><div class="foo">
    <div class="baz"></div>
</div>
</code>```

CSS:

```<code>.foo::before {
    content: 'bar';
}

.foo .baz::before {
    content: inherit;
}
</code>```

I have tried it that way, and even this way:

```<code>.foo > .baz::before {
    content: inherit;
}
</code>```

and this one:

```<code>.foo::before ~ .baz::before {
    content: inherit;
}
</code>```

...and none of the above worked... Is it possible at all? if not, which options do I have in order to achieve this?

UPDATE

I think I might found a way to do such thing:

```<code>.foo {
    content: 'bar';
}

.foo > .baz,
.foo > .baz::before {
    content: inherit;
}
</code>```

答:
A ::before/::after pseudo-element cannot inherit from another ::before/::after pseudo-element. A pseudo-element can only inherit from its originating element — this is the element that the pseudo-element is attached to. A pseudo-element cannot even inherit from the parent of its originating element, unless the originating element itself is also inheriting from its parent and the property involved is not content.

In your example, .foo::before can only inherit from the .foo it's attached to, and likewise for .baz::before and .baz. .baz::before cannot inherit from .foo::before, so what you're trying to do is not possible. There does not appear to be a reliable way to ensure that one pseudo-element always inherits from another pseudo-element through CSS alone without enforcing this within the markup itself.

Title: Children :before content inheritance

Body:
The title might be a little bit confusing but I wonder why is it impossible for a child element to inherit it's parent ::before content. for example:

HTML:

CSS:

.foo::before {
    content: 'bar';
}

.foo .baz::before {
    content: inherit;
}

I have tried it that way, and even this way:

.foo > .baz::before {
    content: inherit;
}

and this one:

.foo::before ~ .baz::before {
    content: inherit;
}

...and none of the above worked... Is it possible at all? if not, which options do I have in order to achieve this?

UPDATE

I think I might found a way to do such thing:

.foo {
    content: 'bar';
}

.foo > .baz,
.foo > .baz::before {
    content: inherit;
}


问:
Writing from JS to JSON
I have a JavaScript file:

```<code>export default {
  'test/index.yaml': {
    name: 'Test Index',
    product: 'test'
  },
  'test/hello.yaml': {
    name: 'Test Greeting',
    product: 'test'
  }
}
</code>```

I am looking to convert this into a JSON file with the desired output being:

```<code>{
  "test/index.yaml": {
    "name": "Test Index",
    "product": "test"
  },
  "test/hello.yaml": {
    "name": "Test Greeting",
    "product": "test"
  }
}
</code>```

--

I am trying to use something like this:

```<code>fs.readFileSync('test/configuration.js').toString().split('\n').forEach(function(line) {
    fs.appendFileSync('newTest/configuration.json', JSON.stringify(line) + '\n');
});
</code>```

But it doesn't break into the correct JSON syntax with the output of:

```<code>"export default {"
"  'test/index.yaml': {"
"    name: 'Test Index',"
"    product: 'test'"
"  },"
"  'test/hello.yaml': {"
"    name: 'Test Greeting',"
"    product: 'test'"
"  }"
"}"
</code>```

Thanks for the assistance!

答:
There is a library called json5 which does exactly this, converting things that are valid JavaScript into valid JSON.  From their documentation:

Object keys can be unquoted if they’re valid identifiers.

Strings can be single-quoted.

Title: Writing from JS to JSON

Body:
I have a JavaScript file:

export default {
  'test/index.yaml': {
    name: 'Test Index',
    product: 'test'
  },
  'test/hello.yaml': {
    name: 'Test Greeting',
    product: 'test'
  }
}

I am looking to convert this into a JSON file with the desired output being:

{
  "test/index.yaml": {
    "name": "Test Index",
    "product": "test"
  },
  "test/hello.yaml": {
    "name": "Test Greeting",
    "product": "test"
  }
}

--

I am trying to use something like this:

fs.readFileSync('test/configuration.js').toString().split('\n').forEach(function(line) {
    fs.appendFileSync('newTest/configuration.json', JSON.stringify(line) + '\n');
});

But it doesn't break into the correct JSON syntax with the output of:

"export default {"
"  'test/index.yaml': {"
"    name: 'Test Index',"
"    product: 'test'"
"  },"
"  'test/hello.yaml': {"
"    name: 'Test Greeting',"
"    product: 'test'"
"  }"
"}"

Thanks for the assistance!


问:
IfNull with Zero value is Boolean False. How to count?
EDIT : more explicit exemple

I would like to count the number of values of one specific field in a collection.

```<code>chosenSensors = ["CO2_BUR_NE_I_001", "CO2_CEL_SE_I_001"]

match = {'$match':{'$or':list(map(lambda x:{x:{'$exists': True}}, chosenSensors))}}

group = {'$group':{'_id':{'year':{'$year':'$timestamp'}}}}

project = {'$project':{}}

for chosenSensor in chosenSensors:
    group['$group'][chosenSensor+'-Count'] = {'$sum':{'$cond':[{'$ifNull':['$'+chosenSensor, False]}, 1, 0]}}
project['$project'][chosenSensor+'-Count'] = True

sort = {'$sort': {"_id":1}}

pipeline = [match, group, project, sort]

for doc in client["cleanData"]["test"].aggregate(pipeline):
    print(doc)
</code>```

Just below is one sample of my collection. I would like to count the number of values in CO2_BUR_NE_I_001.

I expect to have a count of 4.

```<code>{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fe"),
    "timestamp" : ISODate("2016-11-17T12:37:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 0
}

{
    "_id" : ObjectId("593ab63a1ccb9b0c0fb3d3e5"),
    "timestamp" : ISODate("2016-02-01T19:26:00.000Z"),
    "CO2_CEL_SE_I_001" : 1080
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb22700"),
    "timestamp" : ISODate("2016-11-17T12:39:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6025ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "TEM_ETG_001" : 1210
}
</code>```

But I have 3. The value 0 of CO2_CEL_SE_I_001 is not counted as an existing value.

```<code>{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 3, 'CO2_CEL_SE_I_001-Count': 5}
</code>```

If I replace 0 by 880 in the involved document...

```<code>{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}
</code>```

... I find the expected result

```<code>{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 4, 'CO2_CEL_SE_I_001-Count': 5}
</code>```

EDIT : Beggining of an answer...

When I use $ifNull on a value which exists, it returns the value. However, when this value is 0, it returns 0. But this return is given to $cond, and when it's 0, the $cond is considered as False and it returns 0 instead of 1 to my $sum. How can i handle that?

答:
Counting the number of values of one specific field in a collection.

You can use db.collection.distinct() to get distinct values from mongodb and then find length of list no need of aggregation.

```<code>values = db.collection.distinct('field',{Conditions})
print(len(values))
</code>```

Body:
EDIT : more explicit exemple

I would like to count the number of values of one specific field in a collection.

chosenSensors = ["CO2_BUR_NE_I_001", "CO2_CEL_SE_I_001"]

match = {'$match':{'$or':list(map(lambda x:{x:{'$exists': True}}, chosenSensors))}}

group = {'$group':{'_id':{'year':{'$year':'$timestamp'}}}}

project = {'$project':{}}

for chosenSensor in chosenSensors:
    group['$group'][chosenSensor+'-Count'] = {'$sum':{'$cond':[{'$ifNull':['$'+chosenSensor, False]}, 1, 0]}}
project['$project'][chosenSensor+'-Count'] = True

sort = {'$sort': {"_id":1}}

pipeline = [match, group, project, sort]

for doc in client["cleanData"]["test"].aggregate(pipeline):
    print(doc)

Just below is one sample of my collection. I would like to count the number of values in CO2_BUR_NE_I_001.

I expect to have a count of 4.

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fe"),
    "timestamp" : ISODate("2016-11-17T12:37:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 0
}

{
    "_id" : ObjectId("593ab63a1ccb9b0c0fb3d3e5"),
    "timestamp" : ISODate("2016-02-01T19:26:00.000Z"),
    "CO2_CEL_SE_I_001" : 1080
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb22700"),
    "timestamp" : ISODate("2016-11-17T12:39:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6025ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "TEM_ETG_001" : 1210
}

But I have 3. The value 0 of CO2_CEL_SE_I_001 is not counted as an existing value.

{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 3, 'CO2_CEL_SE_I_001-Count': 5}

If I replace 0 by 880 in the involved document...

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

... I find the expected result

{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 4, 'CO2_CEL_SE_I_001-Count': 5}

EDIT : Beggining of an answer...

When I use $ifNull on a value which exists, it returns the value. However, when this value is 0, it returns 0. But this return is given to $cond, and when it's 0, the $cond is considered as False and it returns 0 instead of 1 to my $sum. How can i handle that?

Body:
Counting the number of values of one specific field in a collection.

You can use db.collection.distinct() to get distinct values from mongodb and then find length of list no need of aggregation.

values = db.collection.distinct('field',{Conditions})
print(len(values))


问:
How i make this code shorter?
I have a startup value with letters in the beginning and number at the end I need to add the numbers 82 times. if you could tell me a possible way to shorten this I would be grateful.

```<code>'With Sheets("License Plate Number")
.Range("A3") = mp_start
.Range("A4") = Left(mp_start, 2) & Right(mp_start, 12) + 1
.Range("A5") = Left(mp_start, 2) & Right(mp_start, 12) + 2
.Range("A6") = Left(mp_start, 2) & Right(mp_start, 12) + 3
.Range("A7") = Left(mp_start, 2) & Right(mp_start, 12) + 4
.Range("A8") = Left(mp_start, 2) & Right(mp_start, 12) + 5
.Range("A9") = Left(mp_start, 2) & Right(mp_start, 12) + 6
.Range("A10") = Left(mp_start, 2) & Right(mp_start, 12) + 7
.Range("A11") = Left(mp_start, 2) & Right(mp_start, 12) + 8
.Range("A12") = Left(mp_start, 2) & Right(mp_start, 12) + 9
.Range("A13") = Left(mp_start, 2) & Right(mp_start, 12) + 10
.Range("A14") = Left(mp_start, 2) & Right(mp_start, 12) + 11
.Range("A15") = Left(mp_start, 2) & Right(mp_start, 12) + 12
.Range("A16") = Left(mp_start, 2) & Right(mp_start, 12) + 13
.Range("A17") = Left(mp_start, 2) & Right(mp_start, 12) + 14
.Range("A18") = Left(mp_start, 2) & Right(mp_start, 12) + 15
.Range("A19") = Left(mp_start, 2) & Right(mp_start, 12) + 16
.Range("A20") = Left(mp_start, 2) & Right(mp_start, 12) + 17
.Range("A21") = Left(mp_start, 2) & Right(mp_start, 12) + 18
.Range("A22") = Left(mp_start, 2) & Right(mp_start, 12) + 19
.Range("A23") = Left(mp_start, 2) & Right(mp_start, 12) + 20
.Range("A24") = Left(mp_start, 2) & Right(mp_start, 12) + 21
.Range("A25") = Left(mp_start, 2) & Right(mp_start, 12) + 22
.Range("A26") = Left(mp_start, 2) & Right(mp_start, 12) + 23
.Range("A27") = Left(mp_start, 2) & Right(mp_start, 12) + 24
.Range("A28") = Left(mp_start, 2) & Right(mp_start, 12) + 25
.Range("A29") = Left(mp_start, 2) & Right(mp_start, 12) + 26
.Range("A30") = Left(mp_start, 2) & Right(mp_start, 12) + 27
.Range("A31") = Left(mp_start, 2) & Right(mp_start, 12) + 28
.Range("A32") = Left(mp_start, 2) & Right(mp_start, 12) + 29
.Range("A33") = Left(mp_start, 2) & Right(mp_start, 12) + 30
.Range("A34") = Left(mp_start, 2) & Right(mp_start, 12) + 31
.Range("A35") = Left(mp_start, 2) & Right(mp_start, 12) + 32
.Range("A36") = Left(mp_start, 2) & Right(mp_start, 12) + 33
.Range("A37") = Left(mp_start, 2) & Right(mp_start, 12) + 34
.Range("A38") = Left(mp_start, 2) & Right(mp_start, 12) + 35
.Range("A39") = Left(mp_start, 2) & Right(mp_start, 12) + 36
.Range("A40") = Left(mp_start, 2) & Right(mp_start, 12) + 37
.Range("A41") = Left(mp_start, 2) & Right(mp_start, 12) + 38
.Range("A42") = Left(mp_start, 2) & Right(mp_start, 12) + 39
.Range("A43") = Left(mp_start, 2) & Right(mp_start, 12) + 40
.Range("A44") = Left(mp_start, 2) & Right(mp_start, 12) + 41
.Range("A45") = Left(mp_start, 2) & Right(mp_start, 12) + 42
.Range("A46") = Left(mp_start, 2) & Right(mp_start, 12) + 43
.Range("A47") = Left(mp_start, 2) & Right(mp_start, 12) + 44
.Range("A48") = Left(mp_start, 2) & Right(mp_start, 12) + 45
.Range("A49") = Left(mp_start, 2) & Right(mp_start, 12) + 46
.Range("A50") = Left(mp_start, 2) & Right(mp_start, 12) + 47
.Range("A51") = Left(mp_start, 2) & Right(mp_start, 12) + 48
.Range("A52") = Left(mp_start, 2) & Right(mp_start, 12) + 49
.Range("A53") = Left(mp_start, 2) & Right(mp_start, 12) + 50
.Range("A54") = Left(mp_start, 2) & Right(mp_start, 12) + 51
.Range("A55") = Left(mp_start, 2) & Right(mp_start, 12) + 52
.Range("A56") = Left(mp_start, 2) & Right(mp_start, 12) + 53
.Range("A57") = Left(mp_start, 2) & Right(mp_start, 12) + 54
.Range("A58") = Left(mp_start, 2) & Right(mp_start, 12) + 55
.Range("A59") = Left(mp_start, 2) & Right(mp_start, 12) + 56
.Range("A60") = Left(mp_start, 2) & Right(mp_start, 12) + 57
.Range("A61") = Left(mp_start, 2) & Right(mp_start, 12) + 58
.Range("A62") = Left(mp_start, 2) & Right(mp_start, 12) + 59
.Range("A63") = Left(mp_start, 2) & Right(mp_start, 12) + 60
.Range("A64") = Left(mp_start, 2) & Right(mp_start, 12) + 61
.Range("A65") = Left(mp_start, 2) & Right(mp_start, 12) + 62
.Range("A66") = Left(mp_start, 2) & Right(mp_start, 12) + 63
.Range("A67") = Left(mp_start, 2) & Right(mp_start, 12) + 64
.Range("A68") = Left(mp_start, 2) & Right(mp_start, 12) + 65
.Range("A69") = Left(mp_start, 2) & Right(mp_start, 12) + 66
.Range("A70") = Left(mp_start, 2) & Right(mp_start, 12) + 67
.Range("A71") = Left(mp_start, 2) & Right(mp_start, 12) + 68
.Range("A72") = Left(mp_start, 2) & Right(mp_start, 12) + 69
.Range("A73") = Left(mp_start, 2) & Right(mp_start, 12) + 70
.Range("A74") = Left(mp_start, 2) & Right(mp_start, 12) + 71
.Range("A75") = Left(mp_start, 2) & Right(mp_start, 12) + 72
.Range("A76") = Left(mp_start, 2) & Right(mp_start, 12) + 73
.Range("A77") = Left(mp_start, 2) & Right(mp_start, 12) + 74
.Range("A78") = Left(mp_start, 2) & Right(mp_start, 12) + 75
.Range("A79") = Left(mp_start, 2) & Right(mp_start, 12) + 76
.Range("A80") = Left(mp_start, 2) & Right(mp_start, 12) + 77
.Range("A81") = Left(mp_start, 2) & Right(mp_start, 12) + 78
.Range("A82") = Left(mp_start, 2) & Right(mp_start, 12) + 79
.Range("A83") = Left(mp_start, 2) & Right(mp_start, 12) + 80
.Range("A84") = Left(mp_start, 2) & Right(mp_start, 12) + 81
End With'
</code>```

if you could tell me a possible way to shorten this I would be grateful.

答:
Use a Forloop:

```<code>.Range("A3") = mp_start
For i = 4 To 84
    .Range("A" & i) = Left(mp_start, 2) & Right(mp_start, 12) + i - 3
Next i
</code>```

Title: How i make this code shorter?

Body:
I have a startup value with letters in the beginning and number at the end I need to add the numbers 82 times. if you could tell me a possible way to shorten this I would be grateful.

'With Sheets("License Plate Number")
.Range("A3") = mp_start
.Range("A4") = Left(mp_start, 2) & Right(mp_start, 12) + 1
.Range("A5") = Left(mp_start, 2) & Right(mp_start, 12) + 2
.Range("A6") = Left(mp_start, 2) & Right(mp_start, 12) + 3
.Range("A7") = Left(mp_start, 2) & Right(mp_start, 12) + 4
.Range("A8") = Left(mp_start, 2) & Right(mp_start, 12) + 5
.Range("A9") = Left(mp_start, 2) & Right(mp_start, 12) + 6
.Range("A10") = Left(mp_start, 2) & Right(mp_start, 12) + 7
.Range("A11") = Left(mp_start, 2) & Right(mp_start, 12) + 8
.Range("A12") = Left(mp_start, 2) & Right(mp_start, 12) + 9
.Range("A13") = Left(mp_start, 2) & Right(mp_start, 12) + 10
.Range("A14") = Left(mp_start, 2) & Right(mp_start, 12) + 11
.Range("A15") = Left(mp_start, 2) & Right(mp_start, 12) + 12
.Range("A16") = Left(mp_start, 2) & Right(mp_start, 12) + 13
.Range("A17") = Left(mp_start, 2) & Right(mp_start, 12) + 14
.Range("A18") = Left(mp_start, 2) & Right(mp_start, 12) + 15
.Range("A19") = Left(mp_start, 2) & Right(mp_start, 12) + 16
.Range("A20") = Left(mp_start, 2) & Right(mp_start, 12) + 17
.Range("A21") = Left(mp_start, 2) & Right(mp_start, 12) + 18
.Range("A22") = Left(mp_start, 2) & Right(mp_start, 12) + 19
.Range("A23") = Left(mp_start, 2) & Right(mp_start, 12) + 20
.Range("A24") = Left(mp_start, 2) & Right(mp_start, 12) + 21
.Range("A25") = Left(mp_start, 2) & Right(mp_start, 12) + 22
.Range("A26") = Left(mp_start, 2) & Right(mp_start, 12) + 23
.Range("A27") = Left(mp_start, 2) & Right(mp_start, 12) + 24
.Range("A28") = Left(mp_start, 2) & Right(mp_start, 12) + 25
.Range("A29") = Left(mp_start, 2) & Right(mp_start, 12) + 26
.Range("A30") = Left(mp_start, 2) & Right(mp_start, 12) + 27
.Range("A31") = Left(mp_start, 2) & Right(mp_start, 12) + 28
.Range("A32") = Left(mp_start, 2) & Right(mp_start, 12) + 29
.Range("A33") = Left(mp_start, 2) & Right(mp_start, 12) + 30
.Range("A34") = Left(mp_start, 2) & Right(mp_start, 12) + 31
.Range("A35") = Left(mp_start, 2) & Right(mp_start, 12) + 32
.Range("A36") = Left(mp_start, 2) & Right(mp_start, 12) + 33
.Range("A37") = Left(mp_start, 2) & Right(mp_start, 12) + 34
.Range("A38") = Left(mp_start, 2) & Right(mp_start, 12) + 35
.Range("A39") = Left(mp_start, 2) & Right(mp_start, 12) + 36
.Range("A40") = Left(mp_start, 2) & Right(mp_start, 12) + 37
.Range("A41") = Left(mp_start, 2) & Right(mp_start, 12) + 38
.Range("A42") = Left(mp_start, 2) & Right(mp_start, 12) + 39
.Range("A43") = Left(mp_start, 2) & Right(mp_start, 12) + 40
.Range("A44") = Left(mp_start, 2) & Right(mp_start, 12) + 41
.Range("A45") = Left(mp_start, 2) & Right(mp_start, 12) + 42
.Range("A46") = Left(mp_start, 2) & Right(mp_start, 12) + 43
.Range("A47") = Left(mp_start, 2) & Right(mp_start, 12) + 44
.Range("A48") = Left(mp_start, 2) & Right(mp_start, 12) + 45
.Range("A49") = Left(mp_start, 2) & Right(mp_start, 12) + 46
.Range("A50") = Left(mp_start, 2) & Right(mp_start, 12) + 47
.Range("A51") = Left(mp_start, 2) & Right(mp_start, 12) + 48
.Range("A52") = Left(mp_start, 2) & Right(mp_start, 12) + 49
.Range("A53") = Left(mp_start, 2) & Right(mp_start, 12) + 50
.Range("A54") = Left(mp_start, 2) & Right(mp_start, 12) + 51
.Range("A55") = Left(mp_start, 2) & Right(mp_start, 12) + 52
.Range("A56") = Left(mp_start, 2) & Right(mp_start, 12) + 53
.Range("A57") = Left(mp_start, 2) & Right(mp_start, 12) + 54
.Range("A58") = Left(mp_start, 2) & Right(mp_start, 12) + 55
.Range("A59") = Left(mp_start, 2) & Right(mp_start, 12) + 56
.Range("A60") = Left(mp_start, 2) & Right(mp_start, 12) + 57
.Range("A61") = Left(mp_start, 2) & Right(mp_start, 12) + 58
.Range("A62") = Left(mp_start, 2) & Right(mp_start, 12) + 59
.Range("A63") = Left(mp_start, 2) & Right(mp_start, 12) + 60
.Range("A64") = Left(mp_start, 2) & Right(mp_start, 12) + 61
.Range("A65") = Left(mp_start, 2) & Right(mp_start, 12) + 62
.Range("A66") = Left(mp_start, 2) & Right(mp_start, 12) + 63
.Range("A67") = Left(mp_start, 2) & Right(mp_start, 12) + 64
.Range("A68") = Left(mp_start, 2) & Right(mp_start, 12) + 65
.Range("A69") = Left(mp_start, 2) & Right(mp_start, 12) + 66
.Range("A70") = Left(mp_start, 2) & Right(mp_start, 12) + 67
.Range("A71") = Left(mp_start, 2) & Right(mp_start, 12) + 68
.Range("A72") = Left(mp_start, 2) & Right(mp_start, 12) + 69
.Range("A73") = Left(mp_start, 2) & Right(mp_start, 12) + 70
.Range("A74") = Left(mp_start, 2) & Right(mp_start, 12) + 71
.Range("A75") = Left(mp_start, 2) & Right(mp_start, 12) + 72
.Range("A76") = Left(mp_start, 2) & Right(mp_start, 12) + 73
.Range("A77") = Left(mp_start, 2) & Right(mp_start, 12) + 74
.Range("A78") = Left(mp_start, 2) & Right(mp_start, 12) + 75
.Range("A79") = Left(mp_start, 2) & Right(mp_start, 12) + 76
.Range("A80") = Left(mp_start, 2) & Right(mp_start, 12) + 77
.Range("A81") = Left(mp_start, 2) & Right(mp_start, 12) + 78
.Range("A82") = Left(mp_start, 2) & Right(mp_start, 12) + 79
.Range("A83") = Left(mp_start, 2) & Right(mp_start, 12) + 80
.Range("A84") = Left(mp_start, 2) & Right(mp_start, 12) + 81
End With'

if you could tell me a possible way to shorten this I would be grateful.

Body:
Use a Forloop:

.Range("A3") = mp_start
For i = 4 To 84
    .Range("A" & i) = Left(mp_start, 2) & Right(mp_start, 12) + i - 3
Next i


问:
htaccess - RewriteRule for static files
how to rewrite urls for images and other static files to specific folder, i.e. I am using this so far:

```<code>RewriteRule \.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /MyFolder/$1
</code>```

but its not working,

please help.

------------------- update ---------------------

ok so now I have:

```<code>RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteCond %{REQUEST_URI} !^/exmpale.com/
RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /exmpale.com/$1

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteRule !\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /exmpale.com/index.php
</code>```

so images redirected to exmpale folders work but now I would like to rewrite everything else to index.php, above solution is not working so far.

cheers,
/Marcin

答:
Maybe this is what you want:

```<code>RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /MyFolder/$1
</code>```

or perhaps this:

```<code>RewriteRule ([^/]*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /MyFolder/$1
</code>```

If neither of those is what you're looking for please add details with some examples of your desired inputs/outputs.

As for your update, you probably want to use the L flag to stop rule processing when this rule matches. eg:

```<code>RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteCond %{REQUEST_URI} !^/exmpale.com/

# The next line is long. Scroll to the end!
RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /exmpale.com/$1 [L]

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteRule .* /exmpale.com/index.php
</code>```

Title: htaccess - RewriteRule for static files

Body:
how to rewrite urls for images and other static files to specific folder, i.e. I am using this so far:

RewriteRule \.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /MyFolder/$1

but its not working,

please help.

------------------- update ---------------------

ok so now I have:

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteCond %{REQUEST_URI} !^/exmpale.com/
RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /exmpale.com/$1

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteRule !\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /exmpale.com/index.php

so images redirected to exmpale folders work but now I would like to rewrite everything else to index.php, above solution is not working so far.

cheers,
/Marcin

Body:
Maybe this is what you want:

RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /MyFolder/$1

or perhaps this:

RewriteRule ([^/]*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /MyFolder/$1

If neither of those is what you're looking for please add details with some examples of your desired inputs/outputs.

As for your update, you probably want to use the L flag to stop rule processing when this rule matches. eg:

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteCond %{REQUEST_URI} !^/exmpale.com/

# The next line is long. Scroll to the end!
RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /exmpale.com/$1 [L]

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteRule .* /exmpale.com/index.php


答:
Probably you aim to do something like this?</p>

```<code>float a[1000];
float b[1000];
float c[1000];

int main()
{
    float *w1;
    w1 = a;    // no need of &
    float *w2; // no need of [1000]
    w2 = b;    // no need of &

    return 0;
}
</code>```

Title: Incompatible types in assignments of 'float*' to 'float* [1000]'

Body:
float a[1000];
float b[1000];
float c[1000];

int main()
{
    float *w1;
    w1 = &a;
    float *w2[1000];
    w2 = &b;
    ...
}

so error: cannot convert float (*)[1000] to float* in assignments - to w1
and compiler throws error: incompatible types in assignments of float* to float * [1000] to w2

Body:
Probably you aim to do something like this?

float a[1000];
float b[1000];
float c[1000];

int main()
{
    float *w1;
    w1 = a;    // no need of &
    float *w2; // no need of [1000]
    w2 = b;    // no need of &

    return 0;
}


问:
Bazel quits before building new op without error?
I was building a new Tensorflow op with external libraries yesterday and getting errors. Today when I ran the same code for some reason I ended up with this output instead:

```<code>    (vent)user@server:/dir/tensorflow/tensorflow/core/user_ops$ bazel build --config opt //tensorflow/core/user_ops:my_op.cc
    INFO: Found 1 target...
    INFO: Elapsed time: 1.493s, Critical Path: 0.01s
    (vent)user@server:/dir/tensorflow/tensorflow/core/user_ops$
</code>```

I thought it was something wrong with my cache so I did a 'bazel clean' and then tried to rebuild the example op zero_out.so, but I got the same problem even though yesterday I was able to successfully run zero_out.so from //bazel-bin/tensorflow/core/user_ops. There's nothing wrong with bazel since I was able to start building tensorflow from source without it quitting on me. My build file in //tensorflow/core/user_ops looks like this:

```<code>    load("//tensorflow:tensorflow.bzl", "tf_custom_op_library")

    tf_custom_op_library(
        name = "zero_out.so",
        srcs = ["zero_out.cc"],
    )

    tf_custom_op_library(
        name = "my_op.so",
        srcs = ["my_op.cc"],
        deps = ["@t//:libt"]
     )
</code>```

I've been looking around for a couple hours, but I can't find any help and I don't think I'm looking in the right places. Does this have something to do with the bazel clean deleting some important files? None of my BUILD or WORKSPACE files were changed and nothing on my server has changed.

I'm using Bazel v0.5.1 on Linux with TF v1.2.

答: Solution to the problem was simply because I had accidentally changed my_op.so to my_op.cc in the build command. </p>

Body:
I was building a new Tensorflow op with external libraries yesterday and getting errors. Today when I ran the same code for some reason I ended up with this output instead:

    (vent)user@server:/dir/tensorflow/tensorflow/core/user_ops$ bazel build --config opt //tensorflow/core/user_ops:my_op.cc
    INFO: Found 1 target...
    INFO: Elapsed time: 1.493s, Critical Path: 0.01s
    (vent)user@server:/dir/tensorflow/tensorflow/core/user_ops$

I thought it was something wrong with my cache so I did a 'bazel clean' and then tried to rebuild the example op zero_out.so, but I got the same problem even though yesterday I was able to successfully run zero_out.so from //bazel-bin/tensorflow/core/user_ops. There's nothing wrong with bazel since I was able to start building tensorflow from source without it quitting on me. My build file in //tensorflow/core/user_ops looks like this:

    load("//tensorflow:tensorflow.bzl", "tf_custom_op_library")

    tf_custom_op_library(
        name = "zero_out.so",
        srcs = ["zero_out.cc"],
    )

    tf_custom_op_library(
        name = "my_op.so",
        srcs = ["my_op.cc"],
        deps = ["@t//:libt"]
     )

I've been looking around for a couple hours, but I can't find any help and I don't think I'm looking in the right places. Does this have something to do with the bazel clean deleting some important files? None of my BUILD or WORKSPACE files were changed and nothing on my server has changed.

I'm using Bazel v0.5.1 on Linux with TF v1.2.


问:
How does this JS code look like in if...else format?
How would the following be written in an if/else format?

```<code>hours == 0 ? 12 : (hours > 12) ? hours - 12 : hours
</code>```

答:
I believe this is the appropriate way to the finale else inside of the firs else statement.</p>

```<code>if(hours == 0) {
   return 12
 } else {
   if(hours > 12){
     return hours - 12
   } else {
    return hours
   }
 }
</code>```

Body:
How would the following be written in an if/else format?

hours == 0 ? 12 : (hours > 12) ? hours - 12 : hours

Body:
I believe this is the appropriate way to the finale else inside of the firs else statement.

if(hours == 0) {
   return 12
 } else {
   if(hours > 12){
     return hours - 12
   } else {
    return hours
   }
 }


问:
IdentityServer4 - Call an API as a User from MVC
I'm getting my knickers in a twist trying to understand how to call an API protected via IdentityServer4.

Basically, I have the following sites:
- an IdentityServer application,
- a web API and
- a client web application.

My setup is just like the IdentityServer samples here.

I define a Client which represents my client web application, and an APIResource which represents my Web Api.

From within my client web application I want to make an HTTP call to the WebAPI, but I want to appear as if I am the logged in user, so I want to make the 'email' scope available to the Web Api.

The way I'm doing from within the Web Application is to grab the 'access_token', and to pass it to the Web API:

```<code>var accessToken = await httpContextAccessor.HttpContext.Authentication.GetTokenAsync($"access_token");
            var client = new HttpClient();
            client.SetBearerToken(accessToken);
</code>```

This allows me to call the Client, so the authorization step is working, but the User Claims on the Web Api do not have the appropriate scopes.

Am I doing something wrong?

答:
The access_token can contain claim information in IdentityServer4. The required claims must be specified in the ApiResource definition.

Otherwise, you have to send a JWT id_token along with the request.

```<code>  new ApiResource(ApiResourceNames.SomeApiAccess, "Access to some api.", new List<string>(){
                    new IdentityResources.OpenId().Name,
                    new IdentityResources.Profile().Name,
                    new IdentityResources.Email().Name
                }),
</code>```

Body:
I'm getting my knickers in a twist trying to understand how to call an API protected via IdentityServer4.

Basically, I have the following sites:
- an IdentityServer application,
- a web API and
- a client web application.

My setup is just like the IdentityServer samples here.

I define a Client which represents my client web application, and an APIResource which represents my Web Api.

From within my client web application I want to make an HTTP call to the WebAPI, but I want to appear as if I am the logged in user, so I want to make the 'email' scope available to the Web Api.

The way I'm doing from within the Web Application is to grab the 'access_token', and to pass it to the Web API:

var accessToken = await httpContextAccessor.HttpContext.Authentication.GetTokenAsync($"access_token");
            var client = new HttpClient();
            client.SetBearerToken(accessToken);

This allows me to call the Client, so the authorization step is working, but the User Claims on the Web Api do not have the appropriate scopes.

Am I doing something wrong?

Body:
The access_token can contain claim information in IdentityServer4. The required claims must be specified in the ApiResource definition.

Otherwise, you have to send a JWT id_token along with the request.

  new ApiResource(ApiResourceNames.SomeApiAccess, "Access to some api.", new List<string>(){
                    new IdentityResources.OpenId().Name,
                    new IdentityResources.Profile().Name,
                    new IdentityResources.Email().Name
                }),


问:
SQL query returns 0 for datagridview
I have a select statement that populates a datagridview:

```<code>da = New SqlDataAdapter("SELECT Month, (Sum(IncCnt)) as IncCnt, (Sum(AllFCR)) as AllFCR, (Sum(Prv)) as Prv, ((SUM(IncCnt)-SUM(AllFCR))/(SUM(IncCnt)-SUM(Prv))) as FCR, ((SUM(ASAT)+SUM(CSAT))/(SUM(SurveyTtl))) as CSAT FROM [tblPLOps_Data] group by Month", ScoreConn)
</code>```

However, it displays a 0 for FCR and CSAT although you can do the math from the first three columns and see that FCR should be .89

I need to display as a percent anyway so I tried:

```<code>DataGridView1.Columns(4).DefaultCellStyle.Format = "p"
</code>```

But that just returned 0%, I also changed to decimal and that just returned 0.0

Then I read online and tried:

```<code>DataGridView1.AutoGenerateColumns = True
</code>```

But that didn't help either, anyway how to get it to return a value?

答:
```<code>((SUM(IncCnt)-SUM(AllFCR))/(SUM(IncCnt)-SUM(Prv)))
</code>```

and

```<code>((SUM(ASAT)+SUM(CSAT))/(SUM(SurveyTtl)))
</code>```

are using INTEGER division since they are both integers. You need to cast (one of) them to decimal first, ideally the deominator. Here's an example...

```<code>select 1/2       RETURNS 0
select 1/2.0     RETURNS 0.5000000
select 1.0/2     RETURNS 0.5000000
</code>```

Something like...

```<code>((SUM(IncCnt)-SUM(AllFCR))/(cast(SUM(IncCnt)-SUM(Prv) as decimal(16,2))))
</code>```

and

```<code>((SUM(ASAT)+SUM(CSAT))/(cast(SUM(SurveyTtl) as decimal(16,2))))
</code>```

Title: SQL query returns 0 for datagridview

Body:
I have a select statement that populates a datagridview:

da = New SqlDataAdapter("SELECT Month, (Sum(IncCnt)) as IncCnt, (Sum(AllFCR)) as AllFCR, (Sum(Prv)) as Prv, ((SUM(IncCnt)-SUM(AllFCR))/(SUM(IncCnt)-SUM(Prv))) as FCR, ((SUM(ASAT)+SUM(CSAT))/(SUM(SurveyTtl))) as CSAT FROM [tblPLOps_Data] group by Month", ScoreConn)

However, it displays a 0 for FCR and CSAT although you can do the math from the first three columns and see that FCR should be .89

I need to display as a percent anyway so I tried:

DataGridView1.Columns(4).DefaultCellStyle.Format = "p"

But that just returned 0%, I also changed to decimal and that just returned 0.0

Then I read online and tried:

DataGridView1.AutoGenerateColumns = True

But that didn't help either, anyway how to get it to return a value?

Body:
((SUM(IncCnt)-SUM(AllFCR))/(SUM(IncCnt)-SUM(Prv)))

and

((SUM(ASAT)+SUM(CSAT))/(SUM(SurveyTtl)))

are using INTEGER division since they are both integers. You need to cast (one of) them to decimal first, ideally the deominator. Here's an example...

select 1/2       RETURNS 0
select 1/2.0     RETURNS 0.5000000
select 1.0/2     RETURNS 0.5000000

Something like...

((SUM(IncCnt)-SUM(AllFCR))/(cast(SUM(IncCnt)-SUM(Prv) as decimal(16,2))))

and

((SUM(ASAT)+SUM(CSAT))/(cast(SUM(SurveyTtl) as decimal(16,2))))


问:
Using chained with cake php3
I'm trying to load data from select according to another select options data , so i have used Chained idea for that , but i'm having issues with getting the related data , I have make that at my view :

```<code>  echo $this->Form->input('warehouse_categories_items_id', ['options' => $warehouseCategoriesItems,'class' => 'form-control','id'=>'type']);
                                    echo $this->Form->input('warehouse_items_id', ['options' => $warehouseItems, 'class' => 'form-control','id'=>'item','data-chained'=>$query]);

<script type="text/javascript">
$(document).ready(function () {
    $("#item").chainedTo("#type");
});
</code>```

and at my controller :

```<code> $query = $this->WarehouseAddOrdersItemsForm7->find('all')
    ->contain([ 'WarehouseCategoriesItems', 'WarehouseItems' => function($q){
        return $q->where(['WarehouseItems.warehouse_categories_items_id' => 'WarehouseCategoriesItems.id']);
    }]);
$warehouseCategoriesItems = $this->WarehouseAddOrdersItemsForm7->WarehouseCategoriesItems->find('list', ['valueField' => 'category_item_name','limit' => 200]);
     $warehouseItems = $this->WarehouseAddOrdersItemsForm7->WarehouseItems->find('list', ['valueField' => 'warehouse_item_name','limit' => 200]);
</code>```

But it's only getting my the first select option data , and not getting the second related data .

答:
If you want to use cascaded select, you have 2 way:-

Local(Providing all the data to select options)

Remotely(Will request to server for option then will append/prepend the option to the select)

I am giving you the example and steps to follow for each way:-

Locally:-(Not writing code in CakePHP so that you can understand properly)

```<code><select id="mark" name="mark">
  <option value="">--</option>
  <option value="bmw">BMW</option>
  <option value="audi">Audi</option>
</select>

<select id="series" name="series">
  <option value="">--</option>
  <option value="series-3" data-chained="bmw">3 series</option>
  <option value="series-5" data-chained="bmw">5 series</option>
  <option value="series-6" data-chained="bmw">6 series</option>
  <option value="a3" data-chained="audi">A3</option>
  <option value="a4" data-chained="audi">A4</option>
  <option value="a5" data-chained="audi">A5</option>
</select>
</code>```

Notice that In data-chained, you have to write the parent select value so that by selecting parent, so that it will display only relevant child options.

Remotely/Server(If you want to use filter from server):-

You have to request to the server through AJAX, like

```<code><select id="mark" name="mark">
<option value="">--</option>
<option value="bmw">BMW</option>
<option value="audi">Audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
</select>
<select id="model" name="model">
<option value="">--</option>
</select>
<select id="engine" name="engine">
<option value="">--</option>
</select>
</code>```

1st select box with value and other with empty(Data will be bind after server response)

```<code>$("#series").remoteChained({
  parents : "#mark",
  url : "series/optionData"
});

$("#model").remoteChained({
  parents : "#series",
  url : "models/optionData"
});

$("#engine").remoteChained({
  parents : "#series, #model",
  url : "engines/optionData"
});
</code>```

In your Controller's method optionData, if you have to send the data's in JSON format(Simply find the data from DB then use PHP funciton json_encode to convert the option data to JSON).

TO CREATE data-chained ATTRIBUTE FOR THE OPTIONS, If you want local binding
You have to create an array in your controller like this,
You can do something like this,

```<code>$options = [
    ['text' => 'Series-3', 'value' => 'series-3', 'data-chained' => 'bmw'],
    ['text' => 'Series-5', 'value' => 'series-5', 'data-chained' => 'bmw'],
    ['text' => 'A-3', 'value' => 'a-3', 'data-chained' => 'audi'];

echo $this->Form->select('field', $options);
</code>```

Happy Coding:)

Title: Using chained with cake php3

Body:
I'm trying to load data from select according to another select options data , so i have used Chained idea for that , but i'm having issues with getting the related data , I have make that at my view :

  echo $this->Form->input('warehouse_categories_items_id', ['options' => $warehouseCategoriesItems,'class' => 'form-control','id'=>'type']);
                                    echo $this->Form->input('warehouse_items_id', ['options' => $warehouseItems, 'class' => 'form-control','id'=>'item','data-chained'=>$query]);

Body:
If you want to use cascaded select, you have 2 way:-

Local(Providing all the data to select options)

Remotely(Will request to server for option then will append/prepend the option to the select)

I am giving you the example and steps to follow for each way:-

Locally:-(Not writing code in CakePHP so that you can understand properly)

<select id="mark" name="mark">
  <option value="">--</option>
  <option value="bmw">BMW</option>
  <option value="audi">Audi</option>
</select>

<select id="series" name="series">
  <option value="">--</option>
  <option value="series-3" data-chained="bmw">3 series</option>
  <option value="series-5" data-chained="bmw">5 series</option>
  <option value="series-6" data-chained="bmw">6 series</option>
  <option value="a3" data-chained="audi">A3</option>
  <option value="a4" data-chained="audi">A4</option>
  <option value="a5" data-chained="audi">A5</option>
</select>

Notice that In data-chained, you have to write the parent select value so that by selecting parent, so that it will display only relevant child options.

Remotely/Server(If you want to use filter from server):-

You have to request to the server through AJAX, like

<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw">BMW</option>
<option value="audi">Audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
</select>
<select id="model" name="model">
<option value="">--</option>
</select>
<select id="engine" name="engine">
<option value="">--</option>
</select>

1st select box with value and other with empty(Data will be bind after server response)

$("#series").remoteChained({
  parents : "#mark",
  url : "series/optionData"
});

$("#model").remoteChained({
  parents : "#series",
  url : "models/optionData"
});

$("#engine").remoteChained({
  parents : "#series, #model",
  url : "engines/optionData"
});

In your Controller's method optionData, if you have to send the data's in JSON format(Simply find the data from DB then use PHP funciton json_encode to convert the option data to JSON).

TO CREATE data-chained ATTRIBUTE FOR THE OPTIONS, If you want local binding
You have to create an array in your controller like this,
You can do something like this,

$options = [
    ['text' => 'Series-3', 'value' => 'series-3', 'data-chained' => 'bmw'],
    ['text' => 'Series-5', 'value' => 'series-5', 'data-chained' => 'bmw'],
    ['text' => 'A-3', 'value' => 'a-3', 'data-chained' => 'audi'];

echo $this->Form->select('field', $options);

Happy Coding:)


问:
Convert an Array to Json Laravel
im getting this error

ErrorException in helpers.php line 685:
  preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

i want to convert the comments entity, but i dont know how that will look.

whats the best choice? toJson() or json_encode?

this is my controller

```<code>public function update($id, Request $request)
    {
        $trip = Trip::find($id);
        $trip = Trip::with('comments')->where('id', $id)->first();
        $trip->fill($request->input());

        if($request->has('comments')){
            // foreach($request->comments as $comments){
            //     $comments = Comment::find($id);
            //     $comments->fill($request->input());
            //     $comments->save();

                 $commentArray=[];
        foreach($request->comments as $key=>$commentEntity) {
            // dd($commentEntity);
            // dd($request->comments);
             $comment =Comment::find($id);
            $comment->comment=$commentEntity['comment'];
            $comment->trip_id=$commentEntity['trip_id'];
            $comment->date=date('Y,m,d,G,i,s');
            $comment->user_id=$commentEntity['user_id'];
            $comment->save();
            }
        }

       if($request->files){
        foreach($request->files as $files){
            $file = File::find($id);
            $file->save();
            }
     }

        $trip->save();
        return response()->json($trip);

    }
</code>```

I already try with :

```<code>            **// $strFromArr = serialize($comment); and
            // $comment->toJson(); and this way too
            //$json = json_encode($comment);**
</code>```

答:
Just simple it automatically converts any model to json if you return it</p>

```<code>return $trip;
</code>```

Title: Convert an Array to Json Laravel

Body:
im getting this error

ErrorException in helpers.php line 685:
  preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

i want to convert the comments entity, but i dont know how that will look.

whats the best choice? toJson() or json_encode?

this is my controller

public function update($id, Request $request)
    {
        $trip = Trip::find($id);
        $trip = Trip::with('comments')->where('id', $id)->first();
        $trip->fill($request->input());

        if($request->has('comments')){
            // foreach($request->comments as $comments){
            //     $comments = Comment::find($id);
            //     $comments->fill($request->input());
            //     $comments->save();

                 $commentArray=[];
        foreach($request->comments as $key=>$commentEntity) {
            // dd($commentEntity);
            // dd($request->comments);
             $comment =Comment::find($id);
            $comment->comment=$commentEntity['comment'];
            $comment->trip_id=$commentEntity['trip_id'];
            $comment->date=date('Y,m,d,G,i,s');
            $comment->user_id=$commentEntity['user_id'];
            $comment->save();
            }
        }

       if($request->files){
        foreach($request->files as $files){
            $file = File::find($id);
            $file->save();
            }
     }

        $trip->save();
        return response()->json($trip);

    }

I already try with :

            **// $strFromArr = serialize($comment); and
            // $comment->toJson(); and this way too
            //$json = json_encode($comment);**

Body:
Just simple it automatically converts any model to json if you return it

return $trip;


问:
What's the difference between an object and a class in Perl?
I'm having a little trouble getting my head around the conceptual difference between an object and a class.  I don't really understand the distinction between the two in any programming language, but currently I'm working with Perl, and Moose, so  I'd prefer an explanation using those things.

Cheers

答:
I don't see people using the terms the same way in other languages. That may be one reason for the question. I think maybe PHP users say "class" when they should say "object", a lot of the time?

Anyway, what about this example -- imagine you had to create two different database connections for two different databases:

```<code>my $oracle_database_handle = DBI->connect( <oracle connection details here> );

my $mysql_database_handle =  DBI->connect( <mysql connection details here>  );
</code>```

you would have created two objects for doing two different things, but they're both the same kind of thing -- DBI database connections.

LastEditorDisplayName: brian d foy

Body:
I don't see people using the terms the same way in other languages. That may be one reason for the question. I think maybe PHP users say "class" when they should say "object", a lot of the time?

Anyway, what about this example -- imagine you had to create two different database connections for two different databases:

my $oracle_database_handle = DBI->connect( <oracle connection details here> );

my $mysql_database_handle =  DBI->connect( <mysql connection details here>  );

you would have created two objects for doing two different things, but they're both the same kind of thing -- DBI database connections.

OwnerDisplayName: Ambrose


问:
jQuery - Given a DIV with a bunch of
 tags, how to find the first
 that isn't empty
Given a DIV with a lot of paragraph tags:

```<code><div>
 <p></p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
</div>
</code>```

How to magically find the first
 which isn't empty using just jQUery? ideas?

答:
I find it a little less mind-bending to use methods rather than selectors for this:

```<code>$('div').find('p').not(':empty').first()
</code>```

Edit: As per the poster's comment, here's a version that defines "empty" as "having no text content, although there may be HTML tags present":

```<code>$('div#foo').find('p').filter( function(){
  return ( $.trim($(this).text()).length );
}).first()
</code>```

Example: http://jsfiddle.net/8dem8j8L/

Title: jQuery - Given a DIV with a bunch of <P> tags, how to find the first <P> that isn't empty

Body:
Given a DIV with a lot of paragraph tags:

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

How to magically find the first
 which isn't empty using just jQUery? ideas?

Body:
I find it a little less mind-bending to use methods rather than selectors for this:

$('div').find('p').not(':empty').first()

Edit: As per the poster's comment, here's a version that defines "empty" as "having no text content, although there may be HTML tags present":

$('div#foo').find('p').filter( function(){
  return ( $.trim($(this).text()).length );
}).first()

Example: http://jsfiddle.net/8dem8j8L/


问:
java.lang.IllegalArgumentException: 'value' belongs to a different Realm
I am trying to create an Realm object and getting «java.lang.IllegalArgumentException: 'value' belongs to a different Realm.» exception.

I am using Realm.getDefaultInstance() that I've initiated in Fragment at OnCreateView.

The object I am trying to save into database uses other RealmObject as argument.

Code as follows:

```<code>@Override
public boolean onQueryTextSubmit(final String query) {
    final ProductList productList =
        realm.where(ProductList.class).equalTo("name", listName)
        .findFirst();
    ListEntry.create(realm, listId, productToAdd);
}
</code>```

ListEntry.create looks like this —

```<code>public static void create(Realm realm,
                          final long listId,
                          final Product product,) {
realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Parent parent = realm.where(Parent.class).findFirst();
        RealmList<ListEntry> entries = parent.getListEntries();
        ListEntry listEntry = realm.createObject(ListEntry.class, decrement());
        listEntry.setListId(listId);
        listEntry.setProduct(product);
        entries.add(listEntry);)
}
</code>```

Parent.class is an abstraction I use to store list of all saved entries in Lists as it is done in Realm android's adapters example (https://github.com/realm/realm-android-adapters/blob/master/example/src/main/java/io/realm/examples/adapters/model/Parent.java).

Whenever I try to save the entry at onQueryTextSubmit it returns the error, not saving a thing.

This error message is extremely ungoogleable — thus I request your help.

Any input would be greatly appreciated!

答:
While I were writing the questoin for SO I found out the solution — instead of passing RealmObject as argument I just put id of the object there and added the object to the private RealmList inside the Object during transaction.

So, instead of —

```<code>ListEntry.class:
@PrimaryKey
private long entryId;
private Product product;
</code>```

I wrote

```<code>@PrimaryKey
private long entryId;
private RealmList<Product> productArray;
</code>```

and inside a transaction —

```<code>Product product = realm.where(Product.class).equalTo("productId", productId).findFirst();
listEntry.getProductArray().add(product);
</code>```

And now everything works. Zero-copy design at it's finest.

Keeping it here for those others unfortunate with the google search.

Body:
I am trying to create an Realm object and getting «java.lang.IllegalArgumentException: 'value' belongs to a different Realm.» exception.

I am using Realm.getDefaultInstance() that I've initiated in Fragment at OnCreateView.

The object I am trying to save into database uses other RealmObject as argument.

Code as follows:

@Override
public boolean onQueryTextSubmit(final String query) {
    final ProductList productList =
        realm.where(ProductList.class).equalTo("name", listName)
        .findFirst();
    ListEntry.create(realm, listId, productToAdd);
}

ListEntry.create looks like this —

public static void create(Realm realm,
                          final long listId,
                          final Product product,) {
realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Parent parent = realm.where(Parent.class).findFirst();
        RealmList<ListEntry> entries = parent.getListEntries();
        ListEntry listEntry = realm.createObject(ListEntry.class, decrement());
        listEntry.setListId(listId);
        listEntry.setProduct(product);
        entries.add(listEntry);)
}

Parent.class is an abstraction I use to store list of all saved entries in Lists as it is done in Realm android's adapters example (https://github.com/realm/realm-android-adapters/blob/master/example/src/main/java/io/realm/examples/adapters/model/Parent.java).

Whenever I try to save the entry at onQueryTextSubmit it returns the error, not saving a thing.

This error message is extremely ungoogleable — thus I request your help.

Any input would be greatly appreciated!

Body:
While I were writing the questoin for SO I found out the solution — instead of passing RealmObject as argument I just put id of the object there and added the object to the private RealmList inside the Object during transaction.

So, instead of —

ListEntry.class:
@PrimaryKey
private long entryId;
private Product product;

I wrote

@PrimaryKey
private long entryId;
private RealmList<Product> productArray;

and inside a transaction —

Product product = realm.where(Product.class).equalTo("productId", productId).findFirst();
listEntry.getProductArray().add(product);

And now everything works. Zero-copy design at it's finest.

Keeping it here for those others unfortunate with the google search.


问:
Is a For Loop always executed at least once?
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

```<code>for (int i=6; i <=5; i++) {
    //irrelevant for this question
}
</code>```

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.

答: An entry controlled loop will never execute if the condition is false, however, exit controlled loop will execute at least once.

Body:
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

for (int i=6; i <=5; i++) {
    //irrelevant for this question
}

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.


问:
Python: Assigning grouped mean to 1-D array
Suppose that I have 2 arrays:

```<code>x    = [2, 4, 1, 7, 3, 9, 2, 5, 5, 1]
flag = [0, 1, 0, 2, 1, 1, 2, 0, 0, 2]
</code>```

The flag array indicates which "group" each element of x belongs to. How can I replace each element of x (with, say, flag value k) by the mean of all elements of x whose corresponding flag value is also k?

After such a transformation, x would look like:

```<code>x    = [3.25, 5.33, 3.25, 3.33, 5.33, 5.33, 3.33, 3.25, 3.25, 3.33]
</code>```

(I could use loops to achieve this, but that would be quite inefficient.)

Body:
Suppose that I have 2 arrays:

x    = [2, 4, 1, 7, 3, 9, 2, 5, 5, 1]
flag = [0, 1, 0, 2, 1, 1, 2, 0, 0, 2]

The flag array indicates which "group" each element of x belongs to. How can I replace each element of x (with, say, flag value k) by the mean of all elements of x whose corresponding flag value is also k?

After such a transformation, x would look like:

x    = [3.25, 5.33, 3.25, 3.33, 5.33, 5.33, 3.33, 3.25, 3.25, 3.33]

(I could use loops to achieve this, but that would be quite inefficient.)

Body:
>>> def grouped_mean(data, flags):
...     flag_set = set(flags)
...     flags = np.asarray(flags)
...     data = np.array(data)
...     for s in flag_set:
...         m = (flags == s)
...         data[m] = np.mean(data[m])
...     return data
...

>>> grouped_mean(x, flag)
array([ 3.25      ,  5.33333333,  3.25      ,  3.33333333,  5.33333333,
        5.33333333,  3.33333333,  3.25      ,  3.25      ,  3.33333333])


问:
Inserting date/time in a SQL table in SAS
I am having a little issue inserting the date time into a database table name (TestTable) in SAS EG. The date fields in the TestTable are defined as

```<code>Name = EnteredDate
Type = Date
Length = 8
Format = DATETIME22.3
Informat = DATETIME22.3

Name = LastUpdateDate
Type = Date
Length = 8
Format = DATETIME22.3
Informat = DATETIME22.3
</code>```

My existing code is as follows, where i use a select statement to insert as opposed to a values statement. Here is call a PrepTable which I dont use at all, but the select statement allows me to use the datetime() function which works perfectly in inserting the date time without any issues. See below:

```<code>INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
Select '2', datetime(), datetime()
From work.PrepTable
</code>```

I want to do the following:

```<code>INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
VALUES ('2', datetime(), date time())
</code>```

This is far more efficient I think since I dont have to query the work.PrepTable. But datetime() will not work in a values statement. I tried the following variations

```<code>INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
VALUES ('2', "&sysdate9:00:00:00"dt,"&sysdate9:00:00:00"dt)
</code>```

This method does not enter the time only the date and the date entered is wrong as well. Another variation I tried is the following after looking around on this site

```<code>INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
VALUES ('2', &today_dttm,&today_dttm)
</code>```

where &today_dttm is sourced from:

```<code>%let today_dttm=%sysfunc(dhms(%sysfunc(today()), 0, 0, 0));
</code>```

This hasn't worked to well either as i keep getting only just the date inserted and not the time. Is there a proper way to enter the current day and time when the insert statement is called without having to use the Select statement and datetime() combo.

I am a newbie to sas and any input would be greatly appreciated.
Thanks

答:
These may be useful. They work in WPS, a SAS-compatible system:

```<code>%let now=datetime();
%let yesterday=intnx('dtDay',datetime(),-1);
%let today=intnx('dtDay',datetime(),0);
%let tomorrow=intnx('dtDay',datetime(),1);
</code>```

You can expand on that idea, then use them in your PROC SQL:

```<code>PROC SQL;

SELECT &today as today FORMAT=datetime., &tomorrow as tomorrow FORMAT=datetime.
FROM tablename
;
</code>```

for example.

Body:
I am having a little issue inserting the date time into a database table name (TestTable) in SAS EG. The date fields in the TestTable are defined as

Name = EnteredDate
Type = Date
Length = 8
Format = DATETIME22.3
Informat = DATETIME22.3

Name = LastUpdateDate
Type = Date
Length = 8
Format = DATETIME22.3
Informat = DATETIME22.3

My existing code is as follows, where i use a select statement to insert as opposed to a values statement. Here is call a PrepTable which I dont use at all, but the select statement allows me to use the datetime() function which works perfectly in inserting the date time without any issues. See below:

INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
Select '2', datetime(), datetime()
From work.PrepTable

I want to do the following:

INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
VALUES ('2', datetime(), date time())

This is far more efficient I think since I dont have to query the work.PrepTable. But datetime() will not work in a values statement. I tried the following variations

INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
VALUES ('2', "&sysdate9:00:00:00"dt,"&sysdate9:00:00:00"dt)

This method does not enter the time only the date and the date entered is wrong as well. Another variation I tried is the following after looking around on this site

INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate)
VALUES ('2', &today_dttm,&today_dttm)

where &today_dttm is sourced from:

%let today_dttm=%sysfunc(dhms(%sysfunc(today()), 0, 0, 0));

This hasn't worked to well either as i keep getting only just the date inserted and not the time. Is there a proper way to enter the current day and time when the insert statement is called without having to use the Select statement and datetime() combo.

I am a newbie to sas and any input would be greatly appreciated.
Thanks

Body:
These may be useful. They work in WPS, a SAS-compatible system:

%let now=datetime();
%let yesterday=intnx('dtDay',datetime(),-1);
%let today=intnx('dtDay',datetime(),0);
%let tomorrow=intnx('dtDay',datetime(),1);

You can expand on that idea, then use them in your PROC SQL:

PROC SQL;

SELECT &today as today FORMAT=datetime., &tomorrow as tomorrow FORMAT=datetime.
FROM tablename
;

for example.