问:
Oracle: How can I move an index on LOB column to another tablespace without moving the underlying LOB column?
How can I move an index on LOB column to another tablespace without moving the underlying LOB column ?

It doesn't work like normal index movement i.e. :

```<code>ALTER INDEX <> REBUILD TABLESPACE <> ONLINE ;
</code>```

答:
You can't use a different tablespace for the LOB and its index.  If you want to move the LOB index you must also move the LOB, according to this AskTOM thread:</p>

```<code>alter table table_Name move lob(lob_name) store as (tablespace tablespace_name);
</code>```

Body:
How can I move an index on LOB column to another tablespace without moving the underlying LOB column ?

It doesn't work like normal index movement i.e. :

ALTER INDEX <> REBUILD TABLESPACE <> ONLINE ;

Body:
You can't use a different tablespace for the LOB and its index.  If you want to move the LOB index you must also move the LOB, according to this AskTOM thread:

alter table table_Name move lob(lob_name) store as (tablespace tablespace_name);

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Browser/viewer to see an R dataset in Azure Notebooks?
I understand that the command line can be used to view data, e.g. head(), tail(), etc.

However, I'd like to view the whole dataset. Is this possible within Jupyter Azure Notebooks?

答:
(Untested) if you have a DataFrame object, calling the name should print the entire dataset.
For example, if your dataframe is named dta, just have

```<code>dta
</code>```

at the end of a cell, and run that cell.

ContentLicense: CC BY-SA 3.0

Body:
(Untested) if you have a DataFrame object, calling the name should print the entire dataset.
For example, if your dataframe is named dta, just have

dta

at the end of a cell, and run that cell.


问:
Binding classes to a scoped slot for matfish2/vue-tables-2
I'm using matfish2/vue-tables-2 for creating vue tables and I'm able to use a scoped slot to add data to columns.

Here is a quick snippet:

```<code><v-server-table url="getData" :columns="columns" :options="options" ref="myTable">
    <template slot="qty" scope="props">
        {{ props.row.get_item.qty }}
    </template>
</v-server-table>
</code>```

The outputted result table looks like this:

```<code><table class="VueTables__table table table-striped table-bordered table-hover">
    <thead>
        <tr>
            <th class="VueTables__sortable created-at">
                <span title="" class="VueTables__heading">Date / Time</span>
                <span class="VueTables__sort-icon pull-right glyphicon glyphicon-chevron-down"></span>
            </th>
            <th class="VueTables__sortable sku">
                <span title="" class="VueTables__heading">Sku</span>
                <span class="VueTables__sort-icon pull-right glyphicon glyphicon-sort "></span>
            </th>
            <th class="VueTables__sortable qty">
                <span title="" class="VueTables__heading">Qty</span>
                <span class="VueTables__sort-icon pull-right glyphicon glyphicon-sort "></span>
            </th>
            <th class="customers">
                <span title="" class="VueTables__heading">Customers</span>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr class="">
            <td class="created-at">2017-11-27 12:28:10</td>
            <td class="sku">BC-SL</td>
            <td class="qty">
                392
            </td>
            <td class="customers"></td>
        </tr>
    </tbody>
</table>
</code>```

That package allows me to set column classes via options but that doesn't help because I'm not sure how to manipulate that class or toggle it without using javascript to select and manipulate the dom directly which I assume is not best practice when using Vue.

I tried v-bind:class but doesn't seem to have an affect on that template slot.

My goal is to add a condition if that props.row.get_item.qty > 0 then change background color of that TD column via a class.

Update
Temporary Workaround:

After a few search for now I was able to achieve my goal by setting the TD height to 1px and then wrap it in a DIV like so:

```<code><template slot="qty" scope="props">
    <div v-if="props.row.get_item.qty > 0" class="bis">
        {{ props.row.get_item.qty }}
    </div>
    <div v-else class="oos">
        {{ props.row.get_item.qty }}
    </div>
</template>
</code>```

And then a class to color it:

```<code>.bis {
    display:block;
    background-color: green;
    height: 100%;
    padding: 8px;
    vertical-align: middle;
}
</code>```

And here's the TD css:

```<code>td.qty {
    height: 1px;
    padding: 0px;
    text-align: center;
}
</code>```

Seems to achieve what I want but not sure if correct way or whether there's a more correct way of doing this because this relies on wrapping it with a DIV then set a 1px height on that TD trick to then finally do an display: block and 100% height. Feels a bit of a hack to me.

Simplified version derived from lamelemon's suggestion

```<code><div :class="isGreaterThanZero(props.row.get_item.qty)">
    {{ props.row.get_item.qty }}
</div>
</code>```

And method:

```<code>methods: {
    isGreaterThanZero (qty) {
        return qty ? 'bis' : 'oos';
    },
}
</code>```

答:
Another, perhaps more simple approach would be to use the rowClassCallback option, E.g:

```<code>options:{
  rowClassCallback(row) {
    return row.qty?"bis":"oos";
  }
}
</code>```

CSS:

```<code>tr.bis td:nth-child(3) {
  background: green;
}

tr.oos td:nth-child(3) {
  background: red;
}
</code>```

Or if you don't want to use a pseudo-selector apply a class to the column using columnsClasses

Body:
I'm using matfish2/vue-tables-2 for creating vue tables and I'm able to use a scoped slot to add data to columns.

Here is a quick snippet:

<v-server-table url="getData" :columns="columns" :options="options" ref="myTable">
    <template slot="qty" scope="props">
        {{ props.row.get_item.qty }}
    </template>
</v-server-table>

The outputted result table looks like this:

                Date / Time

                Sku

                Qty

                Customers

            2017-11-27 12:28:10
            BC-SL

                392

That package allows me to set column classes via options but that doesn't help because I'm not sure how to manipulate that class or toggle it without using javascript to select and manipulate the dom directly which I assume is not best practice when using Vue.

I tried v-bind:class but doesn't seem to have an affect on that template slot.

My goal is to add a condition if that props.row.get_item.qty > 0 then change background color of that TD column via a class.

Update
Temporary Workaround:

After a few search for now I was able to achieve my goal by setting the TD height to 1px and then wrap it in a DIV like so:

<template slot="qty" scope="props">

 0" class="bis">
        {{ props.row.get_item.qty }}

        {{ props.row.get_item.qty }}

</template>

And then a class to color it:

.bis {
    display:block;
    background-color: green;
    height: 100%;
    padding: 8px;
    vertical-align: middle;
}

And here's the TD css:

td.qty {
    height: 1px;
    padding: 0px;
    text-align: center;
}

Seems to achieve what I want but not sure if correct way or whether there's a more correct way of doing this because this relies on wrapping it with a DIV then set a 1px height on that TD trick to then finally do an display: block and 100% height. Feels a bit of a hack to me.

Simplified version derived from lamelemon's suggestion

    {{ props.row.get_item.qty }}

And method:

methods: {
    isGreaterThanZero (qty) {
        return qty ? 'bis' : 'oos';
    },
}

Body:
Another, perhaps more simple approach would be to use the rowClassCallback option, E.g:

options:{
  rowClassCallback(row) {
    return row.qty?"bis":"oos";
  }
}

CSS:

tr.bis td:nth-child(3) {
  background: green;
}

tr.oos td:nth-child(3) {
  background: red;
}

Or if you don't want to use a pseudo-selector apply a class to the column using columnsClasses


问:
PostgreSQL JSON field type vs MongoDB
I am building some app where part of it will have pretty much unstructured and changing data which I would like to dump as JSON. As a primary DB I am using PostgreSQL. I have never used JSON field type, but have used MongoDB before. I don't need anything fancy, 99% of the time it will be just storing and getting the data and querying by some fields of the JSON and it is of a scale that one instance of PostgreSQL could handle, nothing epic.

My question is, is PostgreSQL JSON field comparable to using MongoDB? Are there any limits or stumbling blocks that I should now about before choosing PosgresSQL for this? Bonus question : Is there an easy way to view and edit that JSON field by hand like I can when using Studio 3T app for MongoDB?(I know PostgreSQL DB apps are not the greatest for some reason..)

答:
You'll not have any problem at all using Postgres for your json data. It takes some time to get used to the json and array functions in Postgres, but they are great and will cover most of your needs. Json support in Postgres is mature and awesome.

Try to think hard before storing data in json fields, though. It's an easy way, but it can come back and bite you if your data is in fact relational. The good old normal forms does hold true even today.

I have used MongoDB in a couple of project and I doubt I'll ever use it again. I think that most real world use cases are in fact relational. Postgres has struck a perfect balance (in my view) between relational and documents with the great support for json.

If you just want to store a "blob" of json data you can use the json datatype. But if you know that you will need to manipulate the objects or pluck values from them, you should use jsonb. Jsonb will check the validity of your json data as well. I also think that jsonb is more efficient to index.

Using the json datatype or array of json as input parameter in Postgres functions is fantastic imo. I often get json from my API server that needs to be broken up into smaller peaces when data needs to be store as relational. This is easily done in Postgres. I also use this the other way around sometimes, i.e. a Postgres function consolidates relational data and packages it nicely into REST friendly json objects for output. This way I can hide the fact that I actually store the data in a normalised database.

Title: PostgreSQL JSON field type vs MongoDB


问:
Automatic cookie handling with OkHttp 3
I am using okhttp 3.0.1.

Every where I am getting example for cookie handling that is with okhttp2

```<code>OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);
</code>```

Can please some one guide me how to use in version 3. setCookieHandler method is not present in the version 3.

答:
minimal solution that persists cookie after first run

```<code>public class SharedPrefCookieJar implements CookieJar {

    Map<String, Cookie> cookieMap = new HashMap();
    private Context mContext;
    private SharedPrefsManager mSharedPrefsManager;

    @Inject
    public SharedPrefCookieJar(Context context, SharedPrefsManager sharedPrefsManager) {
        mContext = context;
        mSharedPrefsManager = sharedPrefsManager;
        cookieMap = sharedPrefsManager.getCookieMap(context);
        if (cookieMap == null) {
            cookieMap = new HashMap<>();
        }
    }

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {

        for (Cookie cookie : cookies) {
            cookieMap.put(cookie.name(), cookie);
        }
        mSharedPrefsManager.setCookieMap(mContext, cookieMap);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> validCookies = new ArrayList<>();
        for (Map.Entry<String, Cookie> entry : cookieMap.entrySet()) {
            Cookie cookie = entry.getValue();
            if (cookie.expiresAt() < System.currentTimeMillis()) {

            } else {
                validCookies.add(cookie);
            }
        }
        return validCookies;
    }

}
</code>```

with dagger

```<code>@Module
public class ApiModule {

    @Provides
    @Singleton
    InstagramService provideInstagramService(OkHttpClient client)
    {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(InstagramService.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        InstagramService instagramService = retrofit.create(InstagramService.class);
        return instagramService;
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(SharedPrefCookieJar sharedPrefCookieJar){
        OkHttpClient client;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if(BuildConfig.DEBUG)
        {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new InstagramHeaderInterceptor())
                .addNetworkInterceptor(new LoggingInterceptor());

        }
        client = builder.cookieJar(sharedPrefCookieJar).build();
        return client;
    }
}
</code>```

Title: Automatic cookie handling with OkHttp 3

Body:
I am using okhttp 3.0.1.

Every where I am getting example for cookie handling that is with okhttp2

OkHttpClient client = new OkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

Can please some one guide me how to use in version 3. setCookieHandler method is not present in the version 3.

Body:
minimal solution that persists cookie after first run

public class SharedPrefCookieJar implements CookieJar {

    Map<String, Cookie> cookieMap = new HashMap();
    private Context mContext;
    private SharedPrefsManager mSharedPrefsManager;

    @Inject
    public SharedPrefCookieJar(Context context, SharedPrefsManager sharedPrefsManager) {
        mContext = context;
        mSharedPrefsManager = sharedPrefsManager;
        cookieMap = sharedPrefsManager.getCookieMap(context);
        if (cookieMap == null) {
            cookieMap = new HashMap<>();
        }
    }

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {

        for (Cookie cookie : cookies) {
            cookieMap.put(cookie.name(), cookie);
        }
        mSharedPrefsManager.setCookieMap(mContext, cookieMap);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> validCookies = new ArrayList<>();
        for (Map.Entry<String, Cookie> entry : cookieMap.entrySet()) {
            Cookie cookie = entry.getValue();
            if (cookie.expiresAt() < System.currentTimeMillis()) {

            } else {
                validCookies.add(cookie);
            }
        }
        return validCookies;
    }

}

with dagger

@Module
public class ApiModule {

    @Provides
    @Singleton
    InstagramService provideInstagramService(OkHttpClient client)
    {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(InstagramService.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        InstagramService instagramService = retrofit.create(InstagramService.class);
        return instagramService;
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(SharedPrefCookieJar sharedPrefCookieJar){
        OkHttpClient client;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if(BuildConfig.DEBUG)
        {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new InstagramHeaderInterceptor())
                .addNetworkInterceptor(new LoggingInterceptor());

        }
        client = builder.cookieJar(sharedPrefCookieJar).build();
        return client;
    }
}


问:
Evaluate the probability density of Gaussian distribution on a square grid
I need to generate an image mask of dimensions m × n corresponding to a two-dimensional Gaussian with center at µ = (i, j) and σ^2 = 25, using NumPy.

After searching on the net, I found this documentation which looks promising. However, there are a few problems:

Generated matrix is not a mask (binary)

Covariance (σ^2) is given as a matrix and not as an integer

Perhaps using some mathematical properties, this could be transformed into what I want, but I can't see it because I'm not really good at maths.

答:
numpy.random.multivariate_normal will give you samples drawn from a multivariate Gaussian distribution with mean 0 and variance 1. You want to compute the probability density function (PDF) for this distribution, not draw samples from it.

The easiest thing to do is use the scipy.stats.multivariate_normal.pdf function, as follows:

```<code>m, n = 100, 100
lims = (-3, 3) # support of the PDF
xx, yy = np.meshgrid(np.linspace(*lims, m), np.linspace(*lims, n))
points = np.stack((xx, yy), axis=-1)
mean = (1, 2) # Whatever your (i, j) is
covariance = 25.0
pdf = scipy.stats.multivariate_normal.pdf(points, mean, covariance)
</code>```

pdf now gives the height of the Gaussian function at each of the points in the plane between -3 and 3 on both the x- and y-axes.

You can apply this window to whatever images you want, by just doing image * pdf.

EDITS:

Thanks to CrazyIvan for pointing out the pdf function takes a grid of points directly. Also note that np.linspace(*lims, m) uses Python3-specific tuple-unpacking. If you have an older version, just do np.linspace(lims[0], lims[1], m).

Body:
numpy.random.multivariate_normal will give you samples drawn from a multivariate Gaussian distribution with mean 0 and variance 1. You want to compute the probability density function (PDF) for this distribution, not draw samples from it.

The easiest thing to do is use the scipy.stats.multivariate_normal.pdf function, as follows:

m, n = 100, 100
lims = (-3, 3) # support of the PDF
xx, yy = np.meshgrid(np.linspace(*lims, m), np.linspace(*lims, n))
points = np.stack((xx, yy), axis=-1)
mean = (1, 2) # Whatever your (i, j) is
covariance = 25.0
pdf = scipy.stats.multivariate_normal.pdf(points, mean, covariance)

pdf now gives the height of the Gaussian function at each of the points in the plane between -3 and 3 on both the x- and y-axes.

You can apply this window to whatever images you want, by just doing image * pdf.

EDITS:

Thanks to CrazyIvan for pointing out the pdf function takes a grid of points directly. Also note that np.linspace(*lims, m) uses Python3-specific tuple-unpacking. If you have an older version, just do np.linspace(lims[0], lims[1], m).


问:
How can I control the width of a table header cell that contains rotated text?
I played around with this for an hour or so before deciding that I was over my head when it comes to CSS stuff like this.  Basically I am attempting to have a header cell with rotated text on my page.   The rotation seemed to be simple enough--thanks stackoverflow community!--but the width of the column is not working for me.  Does anyone have any tips for getting the "Overall Satisfaction" column to be narrow?

Target is for IE, although I would love to have it work in the big browsers.

You can see some of my leftovers from messing around with it... DIV's in each TH cell, height of the TR, etc.  None of that is necessary for what I am trying to accomplish.

The whole point of rotating the text was to save horizontal real estate and from what I am seeing, that is not happening.

Here's my simplified try:

```<code><style>
.rotate {
    padding: 0px 0px 0px 0px;
    margin: 0px;
}
.rotate div {
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);

    writing-mode: bt-rl;

    padding: 0px 0px 0px 0px;
    margin: 0px;
    text-align: left;
    vertical-align: top;
}
</style>

<table border=1>
    <thead>
        <tr style="line-height: 200px">
            <th><div>Facility</div></th>
            <th><div>Date</div></th>
            <th><div>Score</div></th>
            <th class="rotate"><div>Overall Satisfaction</div></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Los Angeles</td>
            <td>11/12/2010</td>
            <td>3.5</td>
            <td>2.5</td>
        </tr>
        <tr>
            <td>San Diego</td>
            <td>11/17/2010</td>
            <td>10.0</td>
            <td>10.0</td>
        </tr>
    </tody>
</table>
</code>```

答:
In the table level css declaration add  table-layout:fixed; This ensures that the width of the tables columns stays exactly as you declare it no matter what images or text is placerd in each cell.

By the way - instead of:

```
.rotate {
    padding: 0px 0px 0px 0px;
    margin: 0px;
}
.rotate div {
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);

    writing-mode: bt-rl;

    padding: 0px 0px 0px 0px;
    margin: 0px;
    text-align: left;
    vertical-align: top;
}

<th><div>Facility</div></th>
```

try:

```
.rotation {
    display:block;
    /* for firefox, safari, chrome, etc. */
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);/* For Opera*/
    -khtml-transform: rotate(-90deg);/* For Lunix*/
    /* for ie */
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
<th>Facility</th>
```

which is less code and a simplified approach and solves the IE issues.

(Sorry for the answer layout problem above)

ContentLicense: CC BY-SA 2.5

Body:
I played around with this for an hour or so before deciding that I was over my head when it comes to CSS stuff like this.  Basically I am attempting to have a header cell with rotated text on my page.   The rotation seemed to be simple enough--thanks stackoverflow community!--but the width of the column is not working for me.  Does anyone have any tips for getting the "Overall Satisfaction" column to be narrow?

Target is for IE, although I would love to have it work in the big browsers.

You can see some of my leftovers from messing around with it... DIV's in each TH cell, height of the TR, etc.  None of that is necessary for what I am trying to accomplish.

The whole point of rotating the text was to save horizontal real estate and from what I am seeing, that is not happening.

Here's my simplified try:

Facility

Date

Score

Overall Satisfaction

            Los Angeles
            11/12/2010
            3.5
            2.5

            San Diego
            11/17/2010
            10.0
            10.0

    </tody>

Body:
In the table level css declaration add  table-layout:fixed; This ensures that the width of the tables columns stays exactly as you declare it no matter what images or text is placerd in each cell.

By the way - instead of:

.rotate {
    padding: 0px 0px 0px 0px;
    margin: 0px;
}
.rotate div {
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);

    writing-mode: bt-rl;

    padding: 0px 0px 0px 0px;
    margin: 0px;
    text-align: left;
    vertical-align: top;
}

<th><div>Facility</div></th>

try:

.rotation {
    display:block;
    /* for firefox, safari, chrome, etc. */
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);/* For Opera*/
    -khtml-transform: rotate(-90deg);/* For Lunix*/
    /* for ie */
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
<th>Facility</th>

which is less code and a simplified approach and solves the IE issues.

(Sorry for the answer layout problem above)


问:
Excel VBA - Output cell formula (list) based on input cells that range from x to y
I am trying to accomplish the below in excel and believe I need to use VBA. Any help would be greatly appreciated!

Excel input

```<code>Cell A1 = A2*B2*C2
A2 ranges from x to y
B2 ranges from x to y
C2 ranges from x to y
</code>```

Excel Output

```<code>Original Inputs, Formula Calculation (vertical list)

A2 B2 C2 , A1
</code>```

答:
I think the following code will help you:</p>

```<code>Sub foo2()
Dim A2(), B2(), C2() As Variant 'Declare the variables as Variant arrays
Dim LastRowA, LastRowB, LastRowC As Long

LastRowA = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row with data on column A
LastRowB = Sheet1.Cells(Rows.Count, "B").End(xlUp).Row 'find the last row with data on column B
LastRowC = Sheet1.Cells(Rows.Count, "C").End(xlUp).Row 'find the last row with data on column C

A2 = Sheet1.Range("A1:A" & LastRowA) 'take all values form A1 to the last row in that column into the A2 array
B2 = Sheet1.Range("B1:B" & LastRowB)
C2 = Sheet1.Range("C1:C" & LastRowC)

For x = LBound(A2) To UBound(A2) 'loop from the begining of the array until the end
    Sheet1.Cells(x, 6).Value = A2(x, 1) 'enter the values of A2 into the column F which is the number 6
    Sheet1.Cells(x, 7).Value = B2(x, 1) 'edit this values to "paste" the values wherever you wish
    Sheet1.Cells(x, 8).Value = C2(x, 1)
    Sheet1.Cells(x, 9).FormulaR1C1 = "=RC[-3]*RC[-2]*RC[-1]" 'this will enter the formula in those cells
Next x
End Sub
</code>```

Body:
I am trying to accomplish the below in excel and believe I need to use VBA. Any help would be greatly appreciated!

Excel input

Cell A1 = A2*B2*C2
A2 ranges from x to y
B2 ranges from x to y
C2 ranges from x to y

Excel Output

Original Inputs, Formula Calculation (vertical list)

A2 B2 C2 , A1

Body:
I think the following code will help you:

Sub foo2()
Dim A2(), B2(), C2() As Variant 'Declare the variables as Variant arrays
Dim LastRowA, LastRowB, LastRowC As Long

LastRowA = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row with data on column A
LastRowB = Sheet1.Cells(Rows.Count, "B").End(xlUp).Row 'find the last row with data on column B
LastRowC = Sheet1.Cells(Rows.Count, "C").End(xlUp).Row 'find the last row with data on column C

A2 = Sheet1.Range("A1:A" & LastRowA) 'take all values form A1 to the last row in that column into the A2 array
B2 = Sheet1.Range("B1:B" & LastRowB)
C2 = Sheet1.Range("C1:C" & LastRowC)

For x = LBound(A2) To UBound(A2) 'loop from the begining of the array until the end
    Sheet1.Cells(x, 6).Value = A2(x, 1) 'enter the values of A2 into the column F which is the number 6
    Sheet1.Cells(x, 7).Value = B2(x, 1) 'edit this values to "paste" the values wherever you wish
    Sheet1.Cells(x, 8).Value = C2(x, 1)
    Sheet1.Cells(x, 9).FormulaR1C1 = "=RC[-3]*RC[-2]*RC[-1]" 'this will enter the formula in those cells
Next x
End Sub


问:
Why is my UITableView cut off in iOS 7?
In iOS 6, my login tableview that consisted of two rows (Username and Password) was completely shown correctly. In iOS 7, the bottom row is cut off, and I don't know why or how to correct the issue. Nothing changed except for upgrading to Xcode 5 and running on the iOS 7 simulator.

UPDATE: adding more images

答:
The translucent = NO fixed it for some cases.  In others, I ended up adjusting the tableView in viewDidLoad</p>

```<code>- (void)viewDidLoad
{
 [super viewDidLoad];

 CGRect f = self.tableView.frame;
 f.origin.y += self.navigationController.navigationBar.frame.size.height;
 f.size.height -= self.navigationController.navigationBar.frame.size.height;
 self.tableView.frame = f;
}
</code>```

Title: Why is my UITableView cut off in iOS 7?

Body:
The translucent = NO fixed it for some cases.  In others, I ended up adjusting the tableView in viewDidLoad

- (void)viewDidLoad
{
 [super viewDidLoad];

 CGRect f = self.tableView.frame;
 f.origin.y += self.navigationController.navigationBar.frame.size.height;
 f.size.height -= self.navigationController.navigationBar.frame.size.height;
 self.tableView.frame = f;
}


问:
In Neo4j, is it possible to have the same relationship name for different entities
Let`s use the movie DB as an example.
If I would insert all people that worked on a movie in the DB, it would be difficult to find relationship names for everyone. Would it be a problem to have entities like: sound_designer, sound_engineer, set_designer, set_assistance, cable_guy, etc with the same relationship "WORKS_IN" to a Movie entity. Is it possible? Is it a good solution? Would I have problems? Are there alternatives?</p>

答:
Gabor's answer in the comments is a good one, there are no problems with nodes of differing labels having relationships of the same type to the same node.

Multi-labeling nodes with their role isn't a bad idea, however that assumes that a person's role is constant throughout the years captured by the graph, which may not hold true. Or rather, the labels would capture what roles they have been in their entire history, but what specific role they played within a particular movie is likely something you want as a property of the relationship itself, like a role property. Which might even be a list, if a person might have multiple roles for the same movie, similar to actors playing a part (where there is a roles list property on :ACTED_IN relationships).


问:
Flex/AS3: When to remove listeners?
I have an array of FileReference objects which have several listeners attached to each of them, should I be removing each listener in it's handler method, or should I remove them all in the complete handler?

I read somewhere to use weak references for listeners, but I would think it would be better to explicitly remove listeners (yes?/no?)

```<code>for each(var f:Object in fileCollection){
   var myFile:FileReference = f.file;
   myFile.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData)
   myFile.addEventListener(ProgressEvent.PROGRESS, onProgress);
   myFile.addEventListener(IOErrorEvent.IO_ERROR, onError);
   myFile.addEventListener(Event.COMPLETE, onComplete);
 }

 private function onUploadCompleteData(e:DataEvent):void{
   // doin my thing here
   removeListeners(e)
 }

 private function removeListeners(e:Event):void{
   var myFile:FileReference = FileReference(e.target)
   myFile.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData)
   myFile.removeEventListener(ProgressEvent.PROGRESS, onProgress);
   myFile.removeEventListener(IOErrorEvent.IO_ERROR, onError);
   myFile.removeEventListener(Event.COMPLETE, onComplete);
 }
</code>```

答:
It's always a good idea to remove your listeners explicitly when you no longer need them, yeah, and the way you're doing it is fine.  It might seem a little verbose, but it's still good practice, and it keeps you in the habit of knowing where your listeners are, since not knowing leads so often to leaks and unexpected behavior.

As for useWeakReference, I almost always use it myself, in addition to removing unneeded listeners.  For me, it's become the rule rather than the exception.  If you had to choose one, though, remove your listeners explicitly.  Personally, though, I do both.

In fact, the I've found the number of occasions in which it'd be best to leave useWeakReference false, since doing so will prevent objects from being garbage collected, is especially rare.  Indeed, before I learned what that argument was for (blog post here), I spent a ton of time scratching my head after getting runtime exceptions stemming from the Flex framework making calls on components I was sure I'd removed from the display list.

Deepa Subramaniam mentioned it obliquely in her component-model talk at last year's MAX conference (an excellent talk well worth checking out); I believe the way she put it was something like, "I don't know why the Flash player team chose to make false the default rather than true, but 99% of the time, you're going to want to set that value to true."

OwnerDisplayName: Ronn Lixx

Title: Flex/AS3: When to remove listeners?

Body:
I have an array of FileReference objects which have several listeners attached to each of them, should I be removing each listener in it's handler method, or should I remove them all in the complete handler?

I read somewhere to use weak references for listeners, but I would think it would be better to explicitly remove listeners (yes?/no?)

for each(var f:Object in fileCollection){
   var myFile:FileReference = f.file;
   myFile.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData)
   myFile.addEventListener(ProgressEvent.PROGRESS, onProgress);
   myFile.addEventListener(IOErrorEvent.IO_ERROR, onError);
   myFile.addEventListener(Event.COMPLETE, onComplete);
 }

 private function onUploadCompleteData(e:DataEvent):void{
   // doin my thing here
   removeListeners(e)
 }

 private function removeListeners(e:Event):void{
   var myFile:FileReference = FileReference(e.target)
   myFile.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData)
   myFile.removeEventListener(ProgressEvent.PROGRESS, onProgress);
   myFile.removeEventListener(IOErrorEvent.IO_ERROR, onError);
   myFile.removeEventListener(Event.COMPLETE, onComplete);
 }

LastEditorDisplayName: mmattax

OwnerDisplayName: Christian Nunciato

LastEditorDisplayName: Christian Nunciato


问:
Problem understanding output of C program
I have the following program:

```<code>#include<stdio.h>
int main()
{
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char*)iptr+1));
return 0;
}
</code>```

The output is:

```<code>1 1
</code>```

I am not able to understand why the second value is 1.
Please explain.

答:
Same reason the first value is coming out 1. You're accessing a single byte at a time from an int. Since 257 is 0x0101, the two least significant bytes each contain the value 1.

Probably your int is 4 bytes long and stored little-endian, although I suppose it could be 2 bytes long with either endian-ness.

Body:
I have the following program:

#include<stdio.h>
int main()
{
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char*)iptr+1));
return 0;
}

The output is:

1 1

I am not able to understand why the second value is 1.
Please explain.


问:
Referential integrity constraint violation - failing when add more then 2 records
When im loading my initial tests data i retrieve integrity constraint violation exception. It only occurs, when im adding more then 2 records, using addShift method. Im using h2, in memory database.

Loading:

```<code>public void load() {
    shiftService.addShift(1, LocalDate.now(), ShiftType.DAY, 1);
    shiftService.addShift(2, LocalDate.now().plusDays(1), ShiftType.NIGHT, 1);
    shiftService.addShift(2, LocalDate.now().plusDays(5), ShiftType.NIGHT, 2);
}
</code>```

Shift Service:

```<code>@Transactional
public void addShift(long userId, LocalDate shiftDate, ShiftType shiftType, long groupId) {
    Optional<User> user = userService.findOne(userId);
    if (user.isPresent()) {
        Optional<Group> group = groupService.getOne(groupId);
        if (group.isPresent()) {
            Shift shift = new Shift(shiftDate, shiftType, group.get());
            user.get().addShift(shift);
        }
    }
}
</code>```

Caused by:

```<code>org.h2.jdbc.JdbcSQLException: Referential integrity constraint
violation: "FKG5R8KJRL3GG3EKESMHT77GO7L: PUBLIC.SHIFT FOREIGN KEY(ID)
REFERENCES PUBLIC.GROUPS(ID) (3)"; SQL statement:
insert into shift (id, group_id, shift_date, shift_type) values (null, ?, ?,
?) [23506-196]
</code>```

Model:

Shift:

```<code>@Entity
public class Shift {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private LocalDate shiftDate;
    private ShiftType shiftType;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_shifts", joinColumns = @JoinColumn(name = "shift_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
    private Set<User> users = new HashSet<>();

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "group_id")
    private Group group;
</code>```

Group:

```<code>@Entity
@Table(name = "groups") // Group is reserved name in SQL
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_group", joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
    private Set<User> users = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "moderator_group", joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
    private Set<User> moderators = new HashSet<>();

    @OneToMany(mappedBy = "id", cascade = CascadeType.ALL)
    private Set<Shift> shifts;
</code>```

User:

```<code>@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String email;
    private String password;
    private String firstName;
    private String lastName;
    private String phone;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_authority",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}
    )
    private Set<Authority> authorities = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_group",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "group_id", referencedColumnName = "id")}
    )
    private Set<Group> usingGroups = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "moderator_group",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "group_id", referencedColumnName = "id")}
    )
    private Set<Group> moderatingGroups = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_shifts",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "shift_id", referencedColumnName = "id")}
    )
    private Set<Shift> shifts = new HashSet<>();
</code>```

Do you have any ideas why i got this exception?

答:
Your mapping in Group is wrong.

```<code>@OneToMany(mappedBy = "id", cascade = CascadeType.ALL)
private Set<Shift> shifts;
</code>```

This should be rather:

```<code>@OneToMany(mappedBy = "group", cascade = CascadeType.ALL)
private Set<Shift> shifts;
</code>```

Explanation:

Hibernate is adding a foreign key constraint between id in shift and id in group. You are probably adding 2 groups, and after you try to add more than 2 shifts, the constraint isn't fulfilled, because a group with id 3 doesn't exist.

Body:
When im loading my initial tests data i retrieve integrity constraint violation exception. It only occurs, when im adding more then 2 records, using addShift method. Im using h2, in memory database.

Loading:

public void load() {
    shiftService.addShift(1, LocalDate.now(), ShiftType.DAY, 1);
    shiftService.addShift(2, LocalDate.now().plusDays(1), ShiftType.NIGHT, 1);
    shiftService.addShift(2, LocalDate.now().plusDays(5), ShiftType.NIGHT, 2);
}

Shift Service:

@Transactional
public void addShift(long userId, LocalDate shiftDate, ShiftType shiftType, long groupId) {
    Optional<User> user = userService.findOne(userId);
    if (user.isPresent()) {
        Optional<Group> group = groupService.getOne(groupId);
        if (group.isPresent()) {
            Shift shift = new Shift(shiftDate, shiftType, group.get());
            user.get().addShift(shift);
        }
    }
}

Caused by:

org.h2.jdbc.JdbcSQLException: Referential integrity constraint
violation: "FKG5R8KJRL3GG3EKESMHT77GO7L: PUBLIC.SHIFT FOREIGN KEY(ID)
REFERENCES PUBLIC.GROUPS(ID) (3)"; SQL statement:
insert into shift (id, group_id, shift_date, shift_type) values (null, ?, ?,
?) [23506-196]

Model:

Shift:

@Entity
public class Shift {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private LocalDate shiftDate;
    private ShiftType shiftType;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_shifts", joinColumns = @JoinColumn(name = "shift_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
    private Set<User> users = new HashSet<>();

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "group_id")
    private Group group;

Group:

@Entity
@Table(name = "groups") // Group is reserved name in SQL
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_group", joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
    private Set<User> users = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "moderator_group", joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
    private Set<User> moderators = new HashSet<>();

    @OneToMany(mappedBy = "id", cascade = CascadeType.ALL)
    private Set<Shift> shifts;

User:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String email;
    private String password;
    private String firstName;
    private String lastName;
    private String phone;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_authority",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}
    )
    private Set<Authority> authorities = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_group",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "group_id", referencedColumnName = "id")}
    )
    private Set<Group> usingGroups = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "moderator_group",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "group_id", referencedColumnName = "id")}
    )
    private Set<Group> moderatingGroups = new HashSet<>();

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_shifts",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "shift_id", referencedColumnName = "id")}
    )
    private Set<Shift> shifts = new HashSet<>();

Do you have any ideas why i got this exception?

Body:
Your mapping in Group is wrong.

@OneToMany(mappedBy = "id", cascade = CascadeType.ALL)
private Set<Shift> shifts;

This should be rather:

@OneToMany(mappedBy = "group", cascade = CascadeType.ALL)
private Set<Shift> shifts;

Explanation:

Hibernate is adding a foreign key constraint between id in shift and id in group. You are probably adding 2 groups, and after you try to add more than 2 shifts, the constraint isn't fulfilled, because a group with id 3 doesn't exist.


问:
Search for multiple user supplied terms in db column
How do I search for multiple user supplied terms in db column while still properly escaping them?  I want this but with proper escaping:

```<code>select * from foo where description like '%<user term>%'
</code>```

If I do:

```<code>select * from foo where description like $1
</code>```

then I'm not sure how to insert the %'s around the user's term.

答:
just use %user term%, eg:

```<code>t=# create role "weird name";
CREATE ROLE
t=# prepare s(text) as select rolname from pg_roles where rolname like $1;
PREPARE
t=# execute s('%rd na%');
  rolname
------------
 weird name
(1 row)
</code>```

Body:
How do I search for multiple user supplied terms in db column while still properly escaping them?  I want this but with proper escaping:

select * from foo where description like '%<user term>%'

If I do:

select * from foo where description like $1

then I'm not sure how to insert the %'s around the user's term.

Body:
just use %user term%, eg:

t=# create role "weird name";
CREATE ROLE
t=# prepare s(text) as select rolname from pg_roles where rolname like $1;
PREPARE
t=# execute s('%rd na%');
  rolname
------------
 weird name
(1 row)


问:
Laravel eloquent update column value by adding new value
I am using updateOrCreate() method to update points of current user:

```<code>   $point->updateOrCreate(
        ['user_id' => auth()->id()],
        ['score' => request('totalScore')]
    );
</code>```

If request('totalScore') is  50, and current value of column score is 10, I want to update it to 60. But as you can see, the above-mentioned approach directly replaces 10 with 50.

Google search returned results containing query builder's increment() method. But I didn't have to use the query builder in my entire application. Why should I use it now? Would it be possible to update the value using the Eloquent methods?

答:
Previous answer had a problem (see comments). So I had to come up with another solution. I created a local query scope called updateOrCreateAndIncrement() in my model:

```<code>public function scopeUpdateOrCreateAndIncrement($query, $totalScore){
        if(!$query->where('user_id',auth()->id())->first()){
            $query->create(['user_id' => auth()->id(), 'score' => $totalScore]);
        } else {
            $query->where('user_id',auth()->id())->increment('score', $totalScore);
        }
    }
</code>```

And in the controllers update() method, I can easily call $point->updateOrCreateAndIncrement():

```<code>public function update(Request $request, Points $point){
    $point->updateOrCreateAndIncrement(request('totalScore'));
}
</code>```

Body:
I am using updateOrCreate() method to update points of current user:

   $point->updateOrCreate(
        ['user_id' => auth()->id()],
        ['score' => request('totalScore')]
    );

If request('totalScore') is  50, and current value of column score is 10, I want to update it to 60. But as you can see, the above-mentioned approach directly replaces 10 with 50.

Google search returned results containing query builder's increment() method. But I didn't have to use the query builder in my entire application. Why should I use it now? Would it be possible to update the value using the Eloquent methods?

Body:
Previous answer had a problem (see comments). So I had to come up with another solution. I created a local query scope called updateOrCreateAndIncrement() in my model:

public function scopeUpdateOrCreateAndIncrement($query, $totalScore){
        if(!$query->where('user_id',auth()->id())->first()){
            $query->create(['user_id' => auth()->id(), 'score' => $totalScore]);
        } else {
            $query->where('user_id',auth()->id())->increment('score', $totalScore);
        }
    }

And in the controllers update() method, I can easily call $point->updateOrCreateAndIncrement():

public function update(Request $request, Points $point){
    $point->updateOrCreateAndIncrement(request('totalScore'));
}


问:
setting up signed cookies for aws cloudfront https with php SDK
I am setting up a HLS streaming service through cloudfront and implementing several security measures for content protection. I have successfully made it work under http, I can stream video and watch it in my website with a lot of content protection security measures.  For more details on how I managed to make it work for http you can consult it in a post I made in drupal.org about secure hls streaming.

But now I need to add https to the formula because some encryption keys for hls encrypted segments are being transmitted, but I am having problems. Now I am working to add https to the formula. I have added a certificate to my site and I have added a different certificate in cludfront because my certificate is not a wildcard one.

My site certificate works for subdomain.mydomain.com

My cloudfront certificate is for *.mydomain.com

My cloudfront distribution has a cname of cdn.mydomain.com

When I create the cookie I set the secure parameter to true in the call (6th parameter after domain):

```<code>setcookie($name, $value, strtotime('+1 hour'), "/", ".mydomain.com", true, true);
</code>```

But when I try to access some test data in my site

```<code>if (readfile('https://cdn.mydomain.com/privacy_test.txt')==0)
    print "Error in cdn access";
</code>```

I don't see the contents of the file in my website, but the error message.

So it seems I need more things to do to make cloudfront aws signed cookies work under https. Any help?

答:
Simply setting the $secure parameter of setcookie() does not create a signed cookie. The process to create a signed cookie is a bit complicated. First, review Using Signed Cookies, specifically the Canned and Custom policy sections. You will need to familiarize yourself with creating a Policy, base64encoding that Policy and creating a Signature from the encoded policy.

Leveraging the code examples outlined in here, I then use the following code in a few of my applications to set the cookies:

```<code>public static function getCustomSignedCookies()
{
    $domain = '.' . explode('.', apache_request_headers()['Host'], 2)[1];
    $dt = new DateTime();
    $dt->add(new DateInterval('P1Y')); // 1 year
    $expires = $dt->getTimestamp();
    $url = Config::get('cloudfront_url') . '/*';
    $policy = self::getCustomPolicy($url, $expires);
    $encodedPolicy = self::url_safe_base64_encode($policy);
    $signature = self::getSignature($policy);

    $cookies = [
        [
            'name' => 'CloudFront-Policy'
            , 'value' => $encodedPolicy
            , 'expires' => $expires
            , 'path' => '/'
            , 'domain' => $domain
            , 'secure' => true
            , 'httpOnly' => true
        ],
        [
            'name' => 'CloudFront-Signature'
            , 'value' => $signature
            , 'expires' => $expires
            , 'path' => '/'
            , 'domain' => $domain
            , 'secure' => true
            , 'httpOnly' => true
        ],
        [
            'name' => 'CloudFront-Key-Pair-Id'
            , 'value' => self::$keyPair
            , 'expires' => $expires
            , 'path' => '/'
            , 'domain' => $domain
            , 'secure' => true
            , 'httpOnly' => true
        ]
    ];

    return $cookies;
}

public static function setCloudFrontCookies()
{
    ob_start();

    foreach (self::getCustomSignedCookies() as $cookie)
    {
        setcookie
        (
            $cookie['name']
            , $cookie['value']
            , $cookie['expires']
            , $cookie['path']
            , $cookie['domain']
            , $cookie['secure']
            , $cookie['httpOnly']
        );
    }

    ob_end_flush();
}
</code>```

Body:
I am setting up a HLS streaming service through cloudfront and implementing several security measures for content protection. I have successfully made it work under http, I can stream video and watch it in my website with a lot of content protection security measures.  For more details on how I managed to make it work for http you can consult it in a post I made in drupal.org about secure hls streaming.

But now I need to add https to the formula because some encryption keys for hls encrypted segments are being transmitted, but I am having problems. Now I am working to add https to the formula. I have added a certificate to my site and I have added a different certificate in cludfront because my certificate is not a wildcard one.

My site certificate works for subdomain.mydomain.com

My cloudfront certificate is for *.mydomain.com

My cloudfront distribution has a cname of cdn.mydomain.com

When I create the cookie I set the secure parameter to true in the call (6th parameter after domain):

setcookie($name, $value, strtotime('+1 hour'), "/", ".mydomain.com", true, true);

But when I try to access some test data in my site

if (readfile('https://cdn.mydomain.com/privacy_test.txt')==0)
    print "Error in cdn access";

I don't see the contents of the file in my website, but the error message.

So it seems I need more things to do to make cloudfront aws signed cookies work under https. Any help?

Body:
Simply setting the $secure parameter of setcookie() does not create a signed cookie. The process to create a signed cookie is a bit complicated. First, review Using Signed Cookies, specifically the Canned and Custom policy sections. You will need to familiarize yourself with creating a Policy, base64encoding that Policy and creating a Signature from the encoded policy.

Leveraging the code examples outlined in here, I then use the following code in a few of my applications to set the cookies:

public static function getCustomSignedCookies()
{
    $domain = '.' . explode('.', apache_request_headers()['Host'], 2)[1];
    $dt = new DateTime();
    $dt->add(new DateInterval('P1Y')); // 1 year
    $expires = $dt->getTimestamp();
    $url = Config::get('cloudfront_url') . '/*';
    $policy = self::getCustomPolicy($url, $expires);
    $encodedPolicy = self::url_safe_base64_encode($policy);
    $signature = self::getSignature($policy);

    $cookies = [
        [
            'name' => 'CloudFront-Policy'
            , 'value' => $encodedPolicy
            , 'expires' => $expires
            , 'path' => '/'
            , 'domain' => $domain
            , 'secure' => true
            , 'httpOnly' => true
        ],
        [
            'name' => 'CloudFront-Signature'
            , 'value' => $signature
            , 'expires' => $expires
            , 'path' => '/'
            , 'domain' => $domain
            , 'secure' => true
            , 'httpOnly' => true
        ],
        [
            'name' => 'CloudFront-Key-Pair-Id'
            , 'value' => self::$keyPair
            , 'expires' => $expires
            , 'path' => '/'
            , 'domain' => $domain
            , 'secure' => true
            , 'httpOnly' => true
        ]
    ];

    return $cookies;
}

public static function setCloudFrontCookies()
{
    ob_start();

    foreach (self::getCustomSignedCookies() as $cookie)
    {
        setcookie
        (
            $cookie['name']
            , $cookie['value']
            , $cookie['expires']
            , $cookie['path']
            , $cookie['domain']
            , $cookie['secure']
            , $cookie['httpOnly']
        );
    }

    ob_end_flush();
}


问:
Having another Where Filter on Laravel
I am trying to do a search and would only like to return the users with status of 1,4. Although when I try to use this, it grabs them all and ignores my last where.

```<code>$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->whereIn('status', [1,4])
                        ->get();
</code>```

I have also tried

```<code>$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->where('status', 1)
                        ->where('status', 4)
                        ->get();
</code>```

答:
I just figured it out</p>

```<code>   $officiants = Officiant::where('status', 1)
                                    ->orWhere('status', 4)
                                    ->where(function ($query) use ($item) {
                                      $query->where('email', 'like',  '%'.$item.'%')
                                            ->where('lname', 'like', '%'.$item.'%')
                                            ->where('lname', 'like', '%'.$item.'%');
                                    })->get();
</code>```

Title: Having another Where Filter on Laravel

Body:
I am trying to do a search and would only like to return the users with status of 1,4. Although when I try to use this, it grabs them all and ignores my last where.

$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->whereIn('status', [1,4])
                        ->get();

I have also tried

$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->where('status', 1)
                        ->where('status', 4)
                        ->get();

Body:
I just figured it out

   $officiants = Officiant::where('status', 1)
                                    ->orWhere('status', 4)
                                    ->where(function ($query) use ($item) {
                                      $query->where('email', 'like',  '%'.$item.'%')
                                            ->where('lname', 'like', '%'.$item.'%')
                                            ->where('lname', 'like', '%'.$item.'%');
                                    })->get();


问:
Could not find io.objectbox:objectbox-gradle-plugin:1.3.3
I am trying to integrate object box in my existing android project but getting error.
Is there any JAVA 8 version issue or object box compatibility issue.
is there any gradle version and object box compatibility issue. i am stuck at this point.

Error:Could not find io.objectbox:objectbox-gradle-plugin:1.3.3.
Searched in the following locations:
    file:/Applications/Android Studio.app/Contents/gradle/m2repository/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.pom
    file:/Applications/Android Studio.app/Contents/gradle/m2repository/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.jar
    https://maven.fabric.io/public/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.pom
    https://maven.fabric.io/public/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.jar```
</div>
</div>
</p>

<p>following are my gradle files
Build.gradle :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
ext {
    compileSdkVersion = 25
    minSDKVersion = 18
    targetSDKVersion = 25
    buildToolsVersion = "26.0.2"
    supportLibVersion = "25.3.1"
    playServicesVersion = "11.0.2"
    digitsVersion = "1.10.3"
    crashlyticsVersion = "2.8.0"
    facebookStethoVersion = "1.5.0"
    facebookSDKVersion = "4.7.0"
    jUnitVersion = "4.12"
    squareUpOkHttpVersion = "3.9.1"
    squareUpRetrofitVersion = "2.3.0"
    squareUpPicassoVersion = "2.5.2"
    eventBusVersion = "3.1.1"
    commonsIOVersion = "2.5"
    commonsLangVersion = "3.7"
    ThinDownloadManagerVersion = "1.3.0"
    exoplayerVersion = "r1.5.8"
    constraintLayoutVersion = "1.0.2"
    leakCanaryVersion = "1.5.1"
    textDrawableVersion = '1.0.1'
    badgeViewVersion = '1.1.0'
    zxingVersion = '3.5.0'
    multidexVersion = '1.0.2'
    androidTagViewVersion = '1.1.4'
    ical4jVersion = '2.0.5'
    calendarViewVersion = '1.0.4'
    commonsCodecVersion = '1.10'
    concurrentUtilVersion = '3.1'
    AndroidAudioRecorderVersion = '0.3.0'
    objectboxVersion = '1.3.3'
}
buildscript {
    repositories {
        maven { url "http://objectbox.net/beta-repo/" }
        jcenter()
        mavenCentral()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
//        classpath 'com.google.gms:google-services:1.5.0'
        classpath 'com.google.gms:google-services:3.1.0'
//        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.3"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
        maven { url "http://objectbox.net/beta-repo/" }
    }
}

dependencies {
}</code>```

and Module Level gradle :

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
    }
}
configurations {
    // referenced in some portable lib. use android internal instead
    compile.exclude group: 'commons-logging'
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'io.objectbox'
//apply plugin: 'sonar'
//apply plugin: "org.sonarqube"

repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven {
        url "https://jitpack.io"
    }
    google()
}

android {

    dexOptions {
        jumboMode true
    }
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
//        jackOptions {
//            enabled true
//        }
        android.defaultConfig.vectorDrawables.useSupportLibrary = true
        applicationId "com.example.example2"
        minSdkVersion rootProject.ext.minSDKVersion
        targetSdkVersion rootProject.ext.targetSDKVersion
        multiDexEnabled true
    }
//    compileOptions {
//        sourceCompatibility JavaVersion.VERSION_1_8
//        targetCompatibility JavaVersion.VERSION_1_8
//    }

    }
    sourceSets {
        main {
            assets.srcDirs = ['src/main/assets', 'src/main/assets/']
        }

    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile("com.crashlytics.sdk.android:crashlytics:${rootProject.ext.crashlyticsVersion}@aar") {
        transitive = true
    }
    compile("com.digits.sdk.android:digits:${rootProject.ext.digitsVersion}@aar") {
        transitive = true
    }

    compile "com.google.android.gms:play-services-location:${rootProject.ext.playServicesVersion}"
    compile "com.google.firebase:firebase-messaging:${rootProject.ext.playServicesVersion}"
    compile "com.google.firebase:firebase-auth:${rootProject.ext.playServicesVersion}"
    compile "com.google.firebase:firebase-core:${rootProject.ext.playServicesVersion}"

    compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:design:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:support-v13:${rootProject.ext.supportLibVersion}"
    androidTestCompile "com.android.support:support-annotations:${rootProject.ext.supportLibVersion}"

    compile "com.facebook.stetho:stetho:${rootProject.ext.facebookStethoVersion}"
    compile "com.facebook.stetho:stetho-okhttp3:${rootProject.ext.facebookStethoVersion}"
    compile "com.facebook.android:facebook-android-sdk:${rootProject.ext.facebookSDKVersion}"

    compile "com.squareup.okhttp3:okhttp:${rootProject.ext.squareUpOkHttpVersion}"
    compile "com.squareup.okhttp3:logging-interceptor:${rootProject.ext.squareUpOkHttpVersion}"
    compile "com.squareup.picasso:picasso:${rootProject.ext.squareUpPicassoVersion}"
    compile "com.squareup.retrofit2:retrofit:${rootProject.ext.squareUpRetrofitVersion}"
    compile "com.squareup.retrofit2:converter-gson:${rootProject.ext.squareUpRetrofitVersion}"

    testCompile "junit:junit:${rootProject.ext.jUnitVersion}"

    compile "commons-io:commons-io:${rootProject.ext.commonsIOVersion}"
    compile "org.apache.commons:commons-lang3:${rootProject.ext.commonsLangVersion}"

    compile "com.mani:ThinDownloadManager:${rootProject.ext.ThinDownloadManagerVersion}"
    compile "com.google.android.exoplayer:exoplayer:${rootProject.ext.exoplayerVersion}"
    compile "com.android.support.constraint:constraint-layout:${rootProject.ext.constraintLayoutVersion}"

    debugCompile "com.squareup.leakcanary:leakcanary-android:${rootProject.ext.leakCanaryVersion}"
    releaseCompile "com.squareup.leakcanary:leakcanary-android-no-op:${rootProject.ext.leakCanaryVersion}"
    testCompile "com.squareup.leakcanary:leakcanary-android-no-op:${rootProject.ext.leakCanaryVersion}"
    compile "org.greenrobot:eventbus:${rootProject.ext.eventBusVersion}"
    compile "com.amulyakhare:com.amulyakhare.textdrawable:${rootProject.ext.textDrawableVersion}"
    compile "q.rorbin:badgeview:${rootProject.ext.badgeViewVersion}"
    compile "com.journeyapps:zxing-android-embedded:${rootProject.ext.zxingVersion}"
    compile "co.lujun:androidtagview:${rootProject.ext.androidTagViewVersion}"
    compile "org.mnode.ical4j:ical4j:${rootProject.ext.ical4jVersion}"
    compile "com.android.support:multidex:${rootProject.ext.multidexVersion}"
    compile "backport-util-concurrent:backport-util-concurrent:${rootProject.ext.concurrentUtilVersion}"
    compile "commons-codec:commons-codec:${rootProject.ext.commonsCodecVersion}"
    compile "com.github.tibolte:agendacalendarview:${rootProject.ext.calendarViewVersion}"
    compile "com.github.adrielcafe:AndroidAudioRecorder:${rootProject.ext.AndroidAudioRecorderVersion}"
    debugCompile "io.objectbox:objectbox-android-objectbrowser:$objectboxVersion"
    releaseCompile "io.objectbox:objectbox-android:$objectboxVersion"

}

apply plugin: 'com.google.gms.google-services'```

答:
In your module's gradle.build you are lacking the repo.

Move this part from the top gradle file to the module one:

```<code>buildscript {
    repositories {
        maven { url "http://objectbox.net/beta-repo/" }
    }
}
</code>```

Body:
I am trying to integrate object box in my existing android project but getting error.
Is there any JAVA 8 version issue or object box compatibility issue.
is there any gradle version and object box compatibility issue. i am stuck at this point.

Error:Could not find io.objectbox:objectbox-gradle-plugin:1.3.3.
Searched in the following locations:
    file:/Applications/Android Studio.app/Contents/gradle/m2repository/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.pom
    file:/Applications/Android Studio.app/Contents/gradle/m2repository/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.jar
    https://maven.fabric.io/public/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.pom
    https://maven.fabric.io/public/io/objectbox/objectbox-gradle-plugin/1.3.3/objectbox-gradle-plugin-1.3.3.jar

following are my gradle files
Build.gradle :

// Top-level build file where you can add configuration options common to all sub-projects/modules.
ext {
    compileSdkVersion = 25
    minSDKVersion = 18
    targetSDKVersion = 25
    buildToolsVersion = "26.0.2"
    supportLibVersion = "25.3.1"
    playServicesVersion = "11.0.2"
    digitsVersion = "1.10.3"
    crashlyticsVersion = "2.8.0"
    facebookStethoVersion = "1.5.0"
    facebookSDKVersion = "4.7.0"
    jUnitVersion = "4.12"
    squareUpOkHttpVersion = "3.9.1"
    squareUpRetrofitVersion = "2.3.0"
    squareUpPicassoVersion = "2.5.2"
    eventBusVersion = "3.1.1"
    commonsIOVersion = "2.5"
    commonsLangVersion = "3.7"
    ThinDownloadManagerVersion = "1.3.0"
    exoplayerVersion = "r1.5.8"
    constraintLayoutVersion = "1.0.2"
    leakCanaryVersion = "1.5.1"
    textDrawableVersion = '1.0.1'
    badgeViewVersion = '1.1.0'
    zxingVersion = '3.5.0'
    multidexVersion = '1.0.2'
    androidTagViewVersion = '1.1.4'
    ical4jVersion = '2.0.5'
    calendarViewVersion = '1.0.4'
    commonsCodecVersion = '1.10'
    concurrentUtilVersion = '3.1'
    AndroidAudioRecorderVersion = '0.3.0'
    objectboxVersion = '1.3.3'
}
buildscript {
    repositories {
        maven { url "http://objectbox.net/beta-repo/" }
        jcenter()
        mavenCentral()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
//        classpath 'com.google.gms:google-services:1.5.0'
        classpath 'com.google.gms:google-services:3.1.0'
//        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.3"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
        maven { url "http://objectbox.net/beta-repo/" }
    }
}

dependencies {
}

and Module Level gradle :

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
    }
}
configurations {
    // referenced in some portable lib. use android internal instead
    compile.exclude group: 'commons-logging'
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'io.objectbox'
//apply plugin: 'sonar'
//apply plugin: "org.sonarqube"

repositories {
    maven { url 'https://maven.fabric.io/public' }
    maven {
        url "https://jitpack.io"
    }
    google()
}

android {

    dexOptions {
        jumboMode true
    }
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
//        jackOptions {
//            enabled true
//        }
        android.defaultConfig.vectorDrawables.useSupportLibrary = true
        applicationId "com.example.example2"
        minSdkVersion rootProject.ext.minSDKVersion
        targetSdkVersion rootProject.ext.targetSDKVersion
        multiDexEnabled true
    }
//    compileOptions {
//        sourceCompatibility JavaVersion.VERSION_1_8
//        targetCompatibility JavaVersion.VERSION_1_8
//    }

    }
    sourceSets {
        main {
            assets.srcDirs = ['src/main/assets', 'src/main/assets/']
        }

    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile("com.crashlytics.sdk.android:crashlytics:${rootProject.ext.crashlyticsVersion}@aar") {
        transitive = true
    }
    compile("com.digits.sdk.android:digits:${rootProject.ext.digitsVersion}@aar") {
        transitive = true
    }

    compile "com.google.android.gms:play-services-location:${rootProject.ext.playServicesVersion}"
    compile "com.google.firebase:firebase-messaging:${rootProject.ext.playServicesVersion}"
    compile "com.google.firebase:firebase-auth:${rootProject.ext.playServicesVersion}"
    compile "com.google.firebase:firebase-core:${rootProject.ext.playServicesVersion}"

    compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:design:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
    compile "com.android.support:support-v13:${rootProject.ext.supportLibVersion}"
    androidTestCompile "com.android.support:support-annotations:${rootProject.ext.supportLibVersion}"

    compile "com.facebook.stetho:stetho:${rootProject.ext.facebookStethoVersion}"
    compile "com.facebook.stetho:stetho-okhttp3:${rootProject.ext.facebookStethoVersion}"
    compile "com.facebook.android:facebook-android-sdk:${rootProject.ext.facebookSDKVersion}"

    compile "com.squareup.okhttp3:okhttp:${rootProject.ext.squareUpOkHttpVersion}"
    compile "com.squareup.okhttp3:logging-interceptor:${rootProject.ext.squareUpOkHttpVersion}"
    compile "com.squareup.picasso:picasso:${rootProject.ext.squareUpPicassoVersion}"
    compile "com.squareup.retrofit2:retrofit:${rootProject.ext.squareUpRetrofitVersion}"
    compile "com.squareup.retrofit2:converter-gson:${rootProject.ext.squareUpRetrofitVersion}"

    testCompile "junit:junit:${rootProject.ext.jUnitVersion}"

    compile "commons-io:commons-io:${rootProject.ext.commonsIOVersion}"
    compile "org.apache.commons:commons-lang3:${rootProject.ext.commonsLangVersion}"

    compile "com.mani:ThinDownloadManager:${rootProject.ext.ThinDownloadManagerVersion}"
    compile "com.google.android.exoplayer:exoplayer:${rootProject.ext.exoplayerVersion}"
    compile "com.android.support.constraint:constraint-layout:${rootProject.ext.constraintLayoutVersion}"

    debugCompile "com.squareup.leakcanary:leakcanary-android:${rootProject.ext.leakCanaryVersion}"
    releaseCompile "com.squareup.leakcanary:leakcanary-android-no-op:${rootProject.ext.leakCanaryVersion}"
    testCompile "com.squareup.leakcanary:leakcanary-android-no-op:${rootProject.ext.leakCanaryVersion}"
    compile "org.greenrobot:eventbus:${rootProject.ext.eventBusVersion}"
    compile "com.amulyakhare:com.amulyakhare.textdrawable:${rootProject.ext.textDrawableVersion}"
    compile "q.rorbin:badgeview:${rootProject.ext.badgeViewVersion}"
    compile "com.journeyapps:zxing-android-embedded:${rootProject.ext.zxingVersion}"
    compile "co.lujun:androidtagview:${rootProject.ext.androidTagViewVersion}"
    compile "org.mnode.ical4j:ical4j:${rootProject.ext.ical4jVersion}"
    compile "com.android.support:multidex:${rootProject.ext.multidexVersion}"
    compile "backport-util-concurrent:backport-util-concurrent:${rootProject.ext.concurrentUtilVersion}"
    compile "commons-codec:commons-codec:${rootProject.ext.commonsCodecVersion}"
    compile "com.github.tibolte:agendacalendarview:${rootProject.ext.calendarViewVersion}"
    compile "com.github.adrielcafe:AndroidAudioRecorder:${rootProject.ext.AndroidAudioRecorderVersion}"
    debugCompile "io.objectbox:objectbox-android-objectbrowser:$objectboxVersion"
    releaseCompile "io.objectbox:objectbox-android:$objectboxVersion"

}

apply plugin: 'com.google.gms.google-services'

Body:
In your module's gradle.build you are lacking the repo.

Move this part from the top gradle file to the module one:

buildscript {
    repositories {
        maven { url "http://objectbox.net/beta-repo/" }
    }
}


问:
Visual Studio 2015 loop performance degradation when storing pointers in struct
I found that the following loop

```<code>std::vector<int> x,y,z;
...
unsigned int res=0;
auto p=x.data();
auto q=y.data();
auto r=z.data();
for(unsigned int i=0;i<N;++i){
  res+=*p++ +*q++ +*r++;
}
</code>```

runs almost twice as fast as this one, which merely packs the pointers in a struct:

```<code>struct pdata{int *px,*py,*pz;};

unsigned int res=0;
pdata d{x.data(),y.data(),z.data()};
for(unsigned int i=0;i<N;++i){
  res+=*d.px++ +*d.py++ +*d.pz++;
}
return res;
</code>```

Is this a known performance issue? Please find below complete program and performance measurements for Visual C++ 2015 in 32-bit (x86) release mode (default settings), Windows 7 64-bit, Intel Core i5-2520M @2.5GHz:

```<code>#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <numeric>

std::chrono::high_resolution_clock::time_point measure_start,measure_pause;

template<typename F>
double measure(F f)
{
  using namespace std::chrono;

  static const int              num_trials=10;
  static const milliseconds     min_time_per_trial(200);
  std::array<double,num_trials> trials;
  volatile decltype(f())        res; /* to avoid optimizing f() away */

  for(int i=0;i<num_trials;++i){
    int                               runs=0;
    high_resolution_clock::time_point t2;

    measure_start=high_resolution_clock::now();
    do{
      res=f();
      ++runs;
      t2=high_resolution_clock::now();
    }while(t2-measure_start<min_time_per_trial);
    trials[i]=duration_cast<duration<double>>(t2-measure_start).count()/runs;
  }
  (void)res; /* var not used warn */

  std::sort(trials.begin(),trials.end());
  return std::accumulate(
    trials.begin()+2,trials.end()-2,0.0)/(trials.size()-4);
}

template<typename F>
double measure(unsigned int n,F f)
{
  double t=measure(f);
  return (t/n)*10E9;
}

#include <iostream>
#include <vector>

int main()
{
  static const unsigned int N=100000;
  std::vector<int> x(N),y(N),z(N);

  for(int i=0;i<N;i++){
    x[i]=i;
    y[i]=i+1;
    z[i]=i+2;
  }

  std::cout<<measure(N,[&]{
    unsigned int res=0;
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();
    for(unsigned int i=0;i<N;++i){
      res+=*p++ +*q++ +*r++;
    }
    return res;
  })<<",";

  std::cout<<measure(N,[&]{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
      res+=*d.px++ +*d.py++ +*d.pz++;
    }
    return res;
  })<<"\n";
}
</code>```

Output

```<code>4.24541,7.44588
</code>```

Thank you,

答:
There's nothing inherently wrong with your code in either case, and using a different c++ compiler yields different results.

I put each version of your code in a separate function f() and g(), and compiled on a recent g++ (7.2) with -O2 and the results for both versions are literally identical in output.

```<code>unsigned int f(std::vector<int>& x, std::vector<int>& y, std::vector<int>& z)
{
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();

    unsigned int res = 0;
    for(unsigned int i=0;i<N;++i){
        res+=*p++ + *q++ + *r++;
    }
    return res;
}

unsigned int g(std::vector<int>& x, std::vector<int>& y, std::vector<int>& z)
{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
        res += *d.px++ +*d.py++ +*d.pz++;
    }
    return res;
}
</code>```

And the relevant output:

First, f(), your faster version:

```<code>f(std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&):
  mov r8, QWORD PTR [rdi]
  xor eax, eax
  mov rdi, QWORD PTR [rsi]
  mov rsi, QWORD PTR [rdx]
  xor edx, edx
.L2:
  mov ecx, DWORD PTR [rdi+rdx]
  add ecx, DWORD PTR [r8+rdx]
  add ecx, DWORD PTR [rsi+rdx]
  add rdx, 4
  add eax, ecx
  cmp rdx, 4000000
  jne .L2
  rep ret
</code>```

The version with pointers in the struct incur zero additional overhead:

```<code>g(std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&):
  mov r8, QWORD PTR [rdi]
  xor eax, eax
  mov rdi, QWORD PTR [rsi]
  mov rsi, QWORD PTR [rdx]
  xor edx, edx
.L6:
  mov ecx, DWORD PTR [rdi+rdx]
  add ecx, DWORD PTR [r8+rdx]
  add ecx, DWORD PTR [rsi+rdx]
  add rdx, 4
  add eax, ecx
  cmp rdx, 4000000
  jne .L6
  rep ret
</code>```

You can see for yourself on Godbolt:
https://godbolt.org/g/DBqhDh

So this is an issue with MSVC.  Hopefully it's better on a newer version.

Body:
I found that the following loop

std::vector<int> x,y,z;
...
unsigned int res=0;
auto p=x.data();
auto q=y.data();
auto r=z.data();
for(unsigned int i=0;i<N;++i){
  res+=*p++ +*q++ +*r++;
}

runs almost twice as fast as this one, which merely packs the pointers in a struct:

struct pdata{int *px,*py,*pz;};

unsigned int res=0;
pdata d{x.data(),y.data(),z.data()};
for(unsigned int i=0;i<N;++i){
  res+=*d.px++ +*d.py++ +*d.pz++;
}
return res;

Is this a known performance issue? Please find below complete program and performance measurements for Visual C++ 2015 in 32-bit (x86) release mode (default settings), Windows 7 64-bit, Intel Core i5-2520M @2.5GHz:

#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <numeric>

std::chrono::high_resolution_clock::time_point measure_start,measure_pause;

template<typename F>
double measure(F f)
{
  using namespace std::chrono;

  static const int              num_trials=10;
  static const milliseconds     min_time_per_trial(200);
  std::array<double,num_trials> trials;
  volatile decltype(f())        res; /* to avoid optimizing f() away */

  for(int i=0;i<num_trials;++i){
    int                               runs=0;
    high_resolution_clock::time_point t2;

    measure_start=high_resolution_clock::now();
    do{
      res=f();
      ++runs;
      t2=high_resolution_clock::now();
    }while(t2-measure_start<min_time_per_trial);
    trials[i]=duration_cast<duration<double>>(t2-measure_start).count()/runs;
  }
  (void)res; /* var not used warn */

  std::sort(trials.begin(),trials.end());
  return std::accumulate(
    trials.begin()+2,trials.end()-2,0.0)/(trials.size()-4);
}

template<typename F>
double measure(unsigned int n,F f)
{
  double t=measure(f);
  return (t/n)*10E9;
}

#include <iostream>
#include <vector>

int main()
{
  static const unsigned int N=100000;
  std::vector<int> x(N),y(N),z(N);

  for(int i=0;i<N;i++){
    x[i]=i;
    y[i]=i+1;
    z[i]=i+2;
  }

  std::cout<<measure(N,[&]{
    unsigned int res=0;
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();
    for(unsigned int i=0;i<N;++i){
      res+=*p++ +*q++ +*r++;
    }
    return res;
  })<<",";

  std::cout<<measure(N,[&]{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
      res+=*d.px++ +*d.py++ +*d.pz++;
    }
    return res;
  })<<"\n";
}

Output

4.24541,7.44588

Thank you,

Body:
There's nothing inherently wrong with your code in either case, and using a different c++ compiler yields different results.

I put each version of your code in a separate function f() and g(), and compiled on a recent g++ (7.2) with -O2 and the results for both versions are literally identical in output.

unsigned int f(std::vector<int>& x, std::vector<int>& y, std::vector<int>& z)
{
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();

    unsigned int res = 0;
    for(unsigned int i=0;i<N;++i){
        res+=*p++ + *q++ + *r++;
    }
    return res;
}

unsigned int g(std::vector<int>& x, std::vector<int>& y, std::vector<int>& z)
{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
        res += *d.px++ +*d.py++ +*d.pz++;
    }
    return res;
}

And the relevant output:

First, f(), your faster version:

f(std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&):
  mov r8, QWORD PTR [rdi]
  xor eax, eax
  mov rdi, QWORD PTR [rsi]
  mov rsi, QWORD PTR [rdx]
  xor edx, edx
.L2:
  mov ecx, DWORD PTR [rdi+rdx]
  add ecx, DWORD PTR [r8+rdx]
  add ecx, DWORD PTR [rsi+rdx]
  add rdx, 4
  add eax, ecx
  cmp rdx, 4000000
  jne .L2
  rep ret

The version with pointers in the struct incur zero additional overhead:

g(std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&, std::vector<int, std::allocator<int> >&):
  mov r8, QWORD PTR [rdi]
  xor eax, eax
  mov rdi, QWORD PTR [rsi]
  mov rsi, QWORD PTR [rdx]
  xor edx, edx
.L6:
  mov ecx, DWORD PTR [rdi+rdx]
  add ecx, DWORD PTR [r8+rdx]
  add ecx, DWORD PTR [rsi+rdx]
  add rdx, 4
  add eax, ecx
  cmp rdx, 4000000
  jne .L6
  rep ret

You can see for yourself on Godbolt:
https://godbolt.org/g/DBqhDh

So this is an issue with MSVC.  Hopefully it's better on a newer version.


问:
How to display mysql database tables and their respective column names
i have several tables in a mysql database called automobile.

In database.php below,i loop through all tables in the database and display them.I pass an  element inside each table that once cliked leads to  table_fields.php

database.php

```<code><ul class = "list-group">

<?php
error_reporting(E_ALL ^ E_DEPRECATED);

echo"<p class = 'jumbotron'>Table List</p>";

$link = mysql_connect("localhost","root","");

mysql_select_db("automobile") or die(mysql_error());

$result = mysql_query("show tables");

while($table = mysql_fetch_array($result)) { // go through each row that was
 returned in $result

 echo"<li class='list-group-item'>";
 echo"<a href= 'table_fields.php'>";

 echo $table[0]. "<BR>";    // print the table that was returned on that row.

 echo "</a>";
 echo "</li>";

}
?>
</code>```

In table_fields .php below,i have created a script that displays columns from the first table.The table name is 'amin'.

table_fields.php

```<code><html>

<head>

<script src = "jquery.min.js"></script>
<script src = "bootstrap.min.js"></script>
<script src = "angular.min.js"></script>
<script src = "form.js"></script>

<link rel = "stylesheet" href ="bootstrap.min.css" >

</head>

<body class = "container">

<?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);

echo "<table class ='table table-striped table-bordered' style ='width:100%'>";
echo "<tr>";

for ( $i = 0; $i < $numcolumn; $i++ ) {
  $columnnames = mysql_field_name($result, $i);

  echo "<th>".$columnnames. "</th>";

 }

   echo "</tr>";
   echo "</table>";
  ?>

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

As you have probably noticed the code in table_fields.php displays columns from 'amin' table only yet it is referenced by all  elements in database.php.Therefore no matter which table i click i see columns for 'amin' table.

My question is how do i pass table name into code logic so that each table in table_fields.php file displays its respective columns and not columns from the amin table ?

答:
You need to pass the table name to the table_fields.php file as an argument. The easiest way to do this as a query string parameter.

```<code>echo '<a href="table_fields.php?table=' . $table[0] . '">' . $table[0] . '</a>';
</code>```

Then in your table_fields.php file, you can access the table name using $table = $_GET['table'];.

I would however suggest being very careful to not use unsanitized input from the URL. So you should use prepared PDO statements, and NOT use the mysql functions.

Body:
i have several tables in a mysql database called automobile.

In database.php below,i loop through all tables in the database and display them.I pass an  element inside each table that once cliked leads to  table_fields.php

database.php

<?php
error_reporting(E_ALL ^ E_DEPRECATED);

echo"
Table List
";

$link = mysql_connect("localhost","root","");

mysql_select_db("automobile") or die(mysql_error());

$result = mysql_query("show tables");

while($table = mysql_fetch_array($result)) { // go through each row that was
 returned in $result

 echo"
";
 echo"";

 echo $table[0]. "
";    // print the table that was returned on that row.

 echo "";
 echo "
";

}
?>

In table_fields .php below,i have created a script that displays columns from the first table.The table name is 'amin'.

table_fields.php

<link rel = "stylesheet" href ="bootstrap.min.css" >

<?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);

echo "
";
echo "
";

for ( $i = 0; $i < $numcolumn; $i++ ) {
  $columnnames = mysql_field_name($result, $i);

  echo "".$columnnames. "	";

 }

   echo "
";
   echo "
";
  ?>

As you have probably noticed the code in table_fields.php displays columns from 'amin' table only yet it is referenced by all  elements in database.php.Therefore no matter which table i click i see columns for 'amin' table.

My question is how do i pass table name into code logic so that each table in table_fields.php file displays its respective columns and not columns from the amin table ?

Body:
You need to pass the table name to the table_fields.php file as an argument. The easiest way to do this as a query string parameter.

echo '<a href="table_fields.php?table=' . $table[0] . '">' . $table[0] . '</a>';

Then in your table_fields.php file, you can access the table name using $table = $_GET['table'];.

I would however suggest being very careful to not use unsanitized input from the URL. So you should use prepared PDO statements, and NOT use the mysql functions.


问:
Mirror cells from one sheet to another within the same workbook with special conditions

What are you trying to accomplish?

I'm trying to mirror the contents of a row of respective cells from one sheet to another. However, the caveat here are: I'm restricted to MS Excel not Access - I can use modules, the initials in column B are to be used as the condition to populate the corresponding sheets. Like:  Primary key in MS Access and finally the sheets should be populated in real time; nothing should have to be run.
Said spreadsheet attached here.

What have you tried so far?

a. Well, I tried the =Value(x) and  =Grand Budget!A(x) formulas. I setup the corresponding initials worksheets with the respective initials in the main sheet so for example: on sheet "Grand Budget" all NA initials and data in the corresponding row i.e. Description, Vendor and Amount will be mirrored on worksheet "NA"
It works great until the third caveat is unfulfilled: it doesn't work in real time because I cannot predict what the next initial will be so I can't setup the next cell with a formula.

b. I also tried filtering the "Grand Budget" sheet by initials in column B, selecting the needed row data, named it and imported the named table to the corresponding initial worksheet. Source.

What do you have in mind - conceptually?

I'm thinking, it's time for modules or if someone knows a hidden excel formula, lay it on me.
 all I have right is an if statement in c++ in my mind: if(current_cell == desired_initial) {populate()};

I'm willing to aid in interpreting anything that may have been transposed incorrectly.

答:
Apparently there is no way to uniquely  identify the rows on the Grand Budget sheet, we only know the sheet on which the row should go.

So if you really need to do this Real Time, I'm afraid you'll have to repopulate the entire user-sheet whenever there is a change anywhere in columns C-E of the budget sheet. And if there's a change in column B, you'll have to completely repopulate 2 user-sheets...
That tends to be a very error-prone process, so it's probably best to completely repopulate all user-sheets  ...

My advice would be to ask your client to change the requirements... For instance, ask them if it's okay to have some Recalculate button to start your process.

If your client really doesn't want to use a button, you could ask if it's okay if your macro (which repopulates all user-sheets) starts automatically whenever you open the workbook and whenever you leave the Grand Budget sheet (which in effect also is the only input sheet).

By the way: What do you want to happen if they put nonexistent initials in column B?

Update: "I just spoke with said client, and i quote: "do what you must!" I like the recalculate button idea, please do pitch it to me!" – Nana Amponsah

If you don't have much experience with vba, it might be best to start with the second part: Create a new sheet for new initials.

```<code>Option Explicit

Sub CreateNewSheet(Initials As String)
    'Checks whether a sheet with the name "Initials" exists
    'Creates a new sheet if it doesn't exist yet.

    '*** Your code goes here ***
End Sub
</code>```

Please Note: Before you start, you should make a backup of the original workbook.

The first part of this page tells you how to make a module for your program.

And you might have a look at:

https://superuser.com/questions/1041635/how-can-i-tell-if-sheet-a-exists-in-a-workbook

How to Add a Named Sheet at the end of all excel sheets

Body:
Apparently there is no way to uniquely  identify the rows on the Grand Budget sheet, we only know the sheet on which the row should go.

So if you really need to do this Real Time, I'm afraid you'll have to repopulate the entire user-sheet whenever there is a change anywhere in columns C-E of the budget sheet. And if there's a change in column B, you'll have to completely repopulate 2 user-sheets...
That tends to be a very error-prone process, so it's probably best to completely repopulate all user-sheets  ...

My advice would be to ask your client to change the requirements... For instance, ask them if it's okay to have some Recalculate button to start your process.

If your client really doesn't want to use a button, you could ask if it's okay if your macro (which repopulates all user-sheets) starts automatically whenever you open the workbook and whenever you leave the Grand Budget sheet (which in effect also is the only input sheet).

By the way: What do you want to happen if they put nonexistent initials in column B?

Update: "I just spoke with said client, and i quote: "do what you must!" I like the recalculate button idea, please do pitch it to me!" – Nana Amponsah

If you don't have much experience with vba, it might be best to start with the second part: Create a new sheet for new initials.

Option Explicit

Sub CreateNewSheet(Initials As String)
    'Checks whether a sheet with the name "Initials" exists
    'Creates a new sheet if it doesn't exist yet.

    '*** Your code goes here ***
End Sub

Please Note: Before you start, you should make a backup of the original workbook.

The first part of this page tells you how to make a module for your program.

And you might have a look at:

https://superuser.com/questions/1041635/how-can-i-tell-if-sheet-a-exists-in-a-workbook

How to Add a Named Sheet at the end of all excel sheets


问:
SharePoint 2013 JavaScript OnClick event
On our SharePoint 2013 page we have a button which runs an EXE

I want to generate a JS Alert when the button is clicked so that users know to click RUN

The buttons are being generated by a Content Search Web Part which is reading from a list with a Title and URL field.

For the EXE my url is this: file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe

I tried to embed the JavaScript inline using code such as: javascript:open('file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe') or more basically: JavaScript:alert('TEST');

But SharePoint is giving me an "Invalid URL" message when I try to embed JS in this manner.

I have instead now moved to a Script Editor Web Part and am trying to add the Alert to the OnClick event of my button but this is where I am stuck.

My Script Editor code:

```<code><script style="javascript;">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick="javascript:alert('event has been triggered')";</script>
</code>```

Here is an image of the IE Debug screen which is how I'm pulling the ID.  This H2 element is wrapped in an HREF which is wrapped in two DIV tags which make up an LI

With the above snippet IE Debug is giving me this error message:
Unable to set property 'onclick' of undefined or null reference

I am hoping that this is as simple as misplaced quotations, or assigning the OnClick event to the wrong element, but I'm spinning my wheels. Any help appreciated and I'm happy to clarify

答:
You should associate a function to the onclick event on img

```<code><script type="text/javascript">
    var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
    img.onclick = function () {
    alert('event has been triggered');
};
</script>
</code>```

Body:
On our SharePoint 2013 page we have a button which runs an EXE

I want to generate a JS Alert when the button is clicked so that users know to click RUN

The buttons are being generated by a Content Search Web Part which is reading from a list with a Title and URL field.

For the EXE my url is this: file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe

I tried to embed the JavaScript inline using code such as: javascript:open('file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe') or more basically: JavaScript:alert('TEST');

But SharePoint is giving me an "Invalid URL" message when I try to embed JS in this manner.

I have instead now moved to a Script Editor Web Part and am trying to add the Alert to the OnClick event of my button but this is where I am stuck.

My Script Editor code:

Here is an image of the IE Debug screen which is how I'm pulling the ID.  This H2 element is wrapped in an HREF which is wrapped in two DIV tags which make up an LI

With the above snippet IE Debug is giving me this error message:
Unable to set property 'onclick' of undefined or null reference

I am hoping that this is as simple as misplaced quotations, or assigning the OnClick event to the wrong element, but I'm spinning my wheels. Any help appreciated and I'm happy to clarify

Body:
You should associate a function to the onclick event on img

<script type="text/javascript">
    var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
    img.onclick = function () {
    alert('event has been triggered');
};
</script>


答:
Because 257 in binary is 00000001 00000001: So both the first and the second bytes representing it are set to 1.

(char*)iptr is the char (thus 1 byte) pointed by iptr, and (char*)iptr+1 is the next byte.

Title: Problem understanding output of C program

Body:
I have the following program:

#include<stdio.h>
int main()
{
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char*)iptr+1));
return 0;
}

The output is:

1 1

I am not able to understand why the second value is 1.
Please explain.