问:
Use cookie- and token-based authentication paralelly in one project
I'm working on a project where MVC and API controllers are used paralelly. Is it possible to use cookie-based auth on MVC controllers and token-based ones in API controllers? How to achieve it?

The problem is - when I construct my Startup.auth this way (below) and use [Authorize] attribute - it doesn't work as expected, because while Web API is called - it checks cookies and allow to execute method without token.

```<code>public partial class Startup
{
    private string PublicClientId { get; set; }
    private OAuthAuthorizationServerOptions OAuthOptions { get; set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(DatabaseContext.Create);
        app.CreatePerOwinContext<MobileUserManager>(MobileUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/AuthServices/SignIn"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MobileUserManager, UserEntity, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                    getUserIdCallback: (id) => (id.GetUserId<int>()))
            }
        });

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(180),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            RefreshTokenProvider = new ApplicationRefreshTokenProvider()
        };
        app.UseOAuthBearerTokens(OAuthOptions);
    }
}
</code>```

答:
You can try to override Authorize attribute and check what type of auth is current and what is required like this (just pseudo code):</p>

```<code>public class AuthorizeAttribute : AuthorizeAttribute
{
    private bool IsCookieAuthAllowed { get; }

    public ApolloAuthorizeAttribute(bool isCookieAuthAllowed = false)
    {
        IsCookieAuthAllowed = isCookieAuthAllowed;
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var identity = actionContext.ControllerContext.RequestContext.Principal?.Identity;

        if (identity == null)
            return false;

        if (identity.IsCookie())
            return IsCookieAuthAllowed && identity.IsAuthenticated;

        return base.IsAuthorized(actionContext);
    }
}
</code>```

Body:
I'm working on a project where MVC and API controllers are used paralelly. Is it possible to use cookie-based auth on MVC controllers and token-based ones in API controllers? How to achieve it?

The problem is - when I construct my Startup.auth this way (below) and use [Authorize] attribute - it doesn't work as expected, because while Web API is called - it checks cookies and allow to execute method without token.

public partial class Startup
{
    private string PublicClientId { get; set; }
    private OAuthAuthorizationServerOptions OAuthOptions { get; set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(DatabaseContext.Create);
        app.CreatePerOwinContext<MobileUserManager>(MobileUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/AuthServices/SignIn"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MobileUserManager, UserEntity, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                    getUserIdCallback: (id) => (id.GetUserId<int>()))
            }
        });

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(180),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            RefreshTokenProvider = new ApplicationRefreshTokenProvider()
        };
        app.UseOAuthBearerTokens(OAuthOptions);
    }
}

Body:
You can try to override Authorize attribute and check what type of auth is current and what is required like this (just pseudo code):

public class AuthorizeAttribute : AuthorizeAttribute
{
    private bool IsCookieAuthAllowed { get; }

    public ApolloAuthorizeAttribute(bool isCookieAuthAllowed = false)
    {
        IsCookieAuthAllowed = isCookieAuthAllowed;
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var identity = actionContext.ControllerContext.RequestContext.Principal?.Identity;

        if (identity == null)
            return false;

        if (identity.IsCookie())
            return IsCookieAuthAllowed && identity.IsAuthenticated;

        return base.IsAuthorized(actionContext);
    }
}


来源: stackexchange

问:
How can I limit the EditText box input to two characters after a decimal place?
i'm working on an android application with an EditText box. In this box i want the user to enter currency.

I have already restricted the keyboard to numbers and decimals using the handy android:inputType="numberDecimal" but i would like to be able to stop the user from entering more than two digits after the decimal place (so that the content is saved as a currency and also just because i think it's important that the user is clear about what they're entering).

However i don't have much programming experience and i don't know where to start looking (validation is a pretty huge topic haha). A bit of googling and it sounds like i should make my own extension of the InputFilter class but i'm not sure how to go about that or if there's a better way. So Any advice would really be appreciated!

答:
Use the InputFilter
http://developer.android.com/reference/android/text/InputFilter.html

ContentLicense: CC BY-SA 2.5


答:
I have found the solution. Using .~month+yearis the solution. Whole command can be found at the below;

```<code>months=aggregate(cbind(t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19,t20,t21,t22)~year(date)+month(date), FUN=sum, na.rm=TRUE, data=combined)
</code>```

Do you know any more efficient way instead of writing all variables one by one as at the above?

ContentLicense: CC BY-SA 3.0

Title: Aggregating monthly sum of time series

Body:
I have a dataframe which has 23 columns which first column is belong to date and time together.

>str(combined)

'data.frame':   100082 obs. of  23 variables:

$ date: POSIXlt, format: "2004-01-01 01:00:00" "2004-01-01 03:00:00" "2004-01-01 04:00:00" "2004-01-01 05:00:00" ...
 $ t1  : num  665 556 714 890 878 ...
 $ t2  : num  2374 2238 2336 2358 2331 ...
 $ t3  : num  2302 2091 2238 2272 2218 ...
 $ t4  : num  2400 2400 2400 2400 2400 2400 2400 2400 2400 2400 ...
 $ t5  : num  2400 2400 2400 2400 2400 2400 2400 2400 2400 2400 ...
 $ t6  : num  2400 2400 2400 2400 2400 ...
 $ t7  : num  2400 2400 2400 2400 2400 ...
 $ t8  : num  2400 2400 2400 2400 2400 ...
 $ t9  : num  2111 1843 1916 1920 1907 ...
 $ t10 : num  1834 1645 1762 1777 1751 ...
 $ t11 : num  1608 1518 1662 1687 1652 ...
 $ t12 : num  626 529 675 842 834 ...
 $ t13 : num  1766 1706 1866 1888 1852 ...
 $ t14 : num  1957 1792 1907 1916 1893 ...
 $ t15 : num  2034 1938 2068 2085 2059 ...
 $ t16 : num  497 417 538 675 668 ...
 $ t17 : num  445 364 473 591 579 ...
 $ t18 : num  376 268 358 435 417 ...
 $ t19 : num  597 473 608 709 658 ...
 $ t20 : num  638 500 641 742 676 ...
 $ t21 : num  2387 2263 2345 2371 2350 ...
 $ t22 : num  2390 2291 2363 2385 2362 ...

Date is going through the 2017 - 08 -31 23:00:00. I just want to sum all the same month values of different years. In order to do this, code at the below has been applied to my "combined" dataframe;

bymonth=aggregate(cbind(t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19,t20,t21,t22)~month(date),data=combined,FUN=sum)

This resulted the sum all the values for same months.

> str(bymonth)
'data.frame':   12 obs. of  23 variables:
 $ month(date): num  1 2 3 4 5 6 7 8 9 10 ...
 $ t1         : num  9079539 8260669 10758842 9457569 9082702 ...
 $ t2         : num  8865401 8725852 10463748 9015349 9139077 ...
 $ t3         : num  8944534 8678897 10456126 8963046 8934908 ...
 $ t4         : num  9031512 8627635 10952759 9509983 9691009 ...
 $ t5         : num  9056095 8667163 10896578 9425384 9630523 ...
 $ t6         : num  7449536 6982570 8920602 6950115 5987614 ...
 $ t7         : num  7610326 7187122 9266084 7310302 6412976 ...
 $ t8         : num  7987144 7548964 9684426 7710839 6874969 ...
 $ t9         : num  7644122 6585329 8470816 6304882 5317381 ...
 $ t10        : num  7917904 6765170 8638459 6387506 5441643 ...
 $ t11        : num  8237490 7041719 8923193 6646191 5780772 ...
 $ t12        : num  8976847 8223188 10536015 9210887 8794828 ...
 $ t13        : num  8641208 7507814 9533105 7265526 6487144 ...
 $ t14        : num  8663482 7585256 9612939 7396403 6638494 ...
 $ t15        : num  8544334 7530451 9360095 7138325 6268128 ...
 $ t16        : num  8403307 7463580 9858757 8529255 8021458 ...
 $ t17        : num  7954798 7031909 9373369 8100460 7541611 ...
 $ t18        : num  7867333 6943056 9263699 8048171 7446287 ...
 $ t19        : num  8104703 7384206 9630303 8274850 7682145 ...
 $ t20        : num  8593316 7738650 9966859 8511077 7955871 ...
 $ t21        : num  8881166 8678495 10571128 9133670 9158251 ...
 $ t22        : num  8828751 8733658 10495228 9058206 9214007 ...

But; i just want to group sum of every month of every year. For example; all the months sum for 2005, 2006, 2007, ...

After summing all the same months for different years, i want to take average of all these months for different year. Hence; i finally want to get monthly mean results.

Thanks in advance!

Body:
I have found the solution. Using .~month+yearis the solution. Whole command can be found at the below;

months=aggregate(cbind(t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19,t20,t21,t22)~year(date)+month(date), FUN=sum, na.rm=TRUE, data=combined)

Do you know any more efficient way instead of writing all variables one by one as at the above?


问:
Removing the clicked item from menu list using angular 4

Hi,

I have a notification menu list in which i am binding the data which is coming from the REST API. My notification menu will look like this. See below image for clarity.

In the notifications, when ever i click on any of the list item then it should be removed from the list and on the above also there is notification bubble in red color with some count that how many notifications i have received. What i want to achieve is when i click on the notification menu list then the clicked list item should be removed from it also the count should decrease in red color bubble above the bell icon. For example, when i click on notification list item of first item the it should be removed as well as the count should be decreased.

notification.component.ts

```<code>try {

      this.currentUser = JSON.parse(this.cookieService.get('user-is-logged-in-details'));
      console.log(this.currentUser.uid);
      this._userService.getBellNotification(this.currentUser.uid)
      .subscribe(data => this.cookieData = data);
      } catch (e) {
          console.log("Catch Block Error from Notification.Component.ts");
          //console.log("currentUser", this.currentUser.uid);
      }
</code>```

apiservice.service.ts

```<code>getBellNotification(uid: any){
        const urlBell = this.config.apiUrl+'api/supplier-notification/'+uid+'?_format=json';
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        headers.append('Authorization', 'Basic ' + btoa('apiuser:@piUser@2017Supplier'));
        let requestoptions = new RequestOptions({headers: headers});
        return this.http.get(urlBell, requestoptions)
        .map(response => response.json())
        .catch(this.handleErrorObservable);
    }
</code>```

notification.component.html

```<code><span
    class="notification"
    dropdown (onShown)="onShown()"
    (onHidden)="onHidden()"
    (isOpenChange)="isOpenChange()">
    <a
        href dropdownToggle
        (click)="false">
        <i
        class="glyphicon glyphicon-bell"
        [ngClass]="cookieData?.search_unread_count != 0 ? 'notification-icon': ' '">
    <span *ngIf="cookieData?.search_unread_count != 0">{{cookieData.search_unread_count}}</span>
    </i>
    </a>
      <ul
        *dropdownMenu
        class="dropdown-menu notify-drop">
          <div
            class="notify-drop-title">Notifications</div>
            <div
                class="drop-content"
                *ngFor="let item of cookieData.search_result">
                <li
                    data-id="{{item.id}}"
                    class="notification-items unread">
                    <i
                        class="fa fa-dot-circle-o"
                        aria-hidden="true">
                    </i>
                    <a
                        data-link="admin-invoice-list"
                        href="javascript:;">{{item.message}}
                    </a>
                </li>
            </div>
      </ul>
</span>
</code>```

Can anyone please suggest me how it can be achieved?

答:
@federico scamuzzi ise explained what you missed exactly. but him answer is need some correction for your objects and requirements. I have update that in here, try it and let me know if you have any clarification. </p>

```<code>           <div
            class="drop-content"
            *ngFor="let item of cookieData.search_result">
            <li (click)="remove(item)"
                data-id="{{item.id}}"
                class="notification-items unread">
                <i
                    class="fa fa-dot-circle-o"
                    aria-hidden="true">
                </i>
                <a
                    data-link="admin-invoice-list"
                    href="javascript:;">{{item.message}}
                </a>
            </li>
</code>```

<p>and your remove function should be </p>

```<code>remove(item:any){
    //ALSO CALL A BACKEND API... TO REMOVE THEM .. THIS IS ONLY FRONT END
    this.cookieData.search_result = this.cookieData.search_result.filter(xx=>xx.id != item.id);
    this.cookieData.search_unread_count=this.cookieData.search_result.length;

    }
</code>```

Body:
Hi,

I have a notification menu list in which i am binding the data which is coming from the REST API. My notification menu will look like this. See below image for clarity.

In the notifications, when ever i click on any of the list item then it should be removed from the list and on the above also there is notification bubble in red color with some count that how many notifications i have received. What i want to achieve is when i click on the notification menu list then the clicked list item should be removed from it also the count should decrease in red color bubble above the bell icon. For example, when i click on notification list item of first item the it should be removed as well as the count should be decreased.

notification.component.ts

try {

      this.currentUser = JSON.parse(this.cookieService.get('user-is-logged-in-details'));
      console.log(this.currentUser.uid);
      this._userService.getBellNotification(this.currentUser.uid)
      .subscribe(data => this.cookieData = data);
      } catch (e) {
          console.log("Catch Block Error from Notification.Component.ts");
          //console.log("currentUser", this.currentUser.uid);
      }

apiservice.service.ts

getBellNotification(uid: any){
        const urlBell = this.config.apiUrl+'api/supplier-notification/'+uid+'?_format=json';
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        headers.append('Authorization', 'Basic ' + btoa('apiuser:@piUser@2017Supplier'));
        let requestoptions = new RequestOptions({headers: headers});
        return this.http.get(urlBell, requestoptions)
        .map(response => response.json())
        .catch(this.handleErrorObservable);
    }

notification.component.html

    {{cookieData.search_unread_count}}

Notifications

                    {{item.message}}

Can anyone please suggest me how it can be achieved?

Body:
@federico scamuzzi ise explained what you missed exactly. but him answer is need some correction for your objects and requirements. I have update that in here, try it and let me know if you have any clarification.

           <div
            class="drop-content"
            *ngFor="let item of cookieData.search_result">
            <li (click)="remove(item)"
                data-id="{{item.id}}"
                class="notification-items unread">
                <i
                    class="fa fa-dot-circle-o"
                    aria-hidden="true">
                </i>
                <a
                    data-link="admin-invoice-list"
                    href="javascript:;">{{item.message}}
                </a>
            </li>

and your remove function should be

remove(item:any){
    //ALSO CALL A BACKEND API... TO REMOVE THEM .. THIS IS ONLY FRONT END
    this.cookieData.search_result = this.cookieData.search_result.filter(xx=>xx.id != item.id);
    this.cookieData.search_unread_count=this.cookieData.search_result.length;

    }


问:
Adobe BlazeDS 4 artifacts maven repository?
Does anybody know if Adobe has a maven repository to download the latest BlazeDS artifacts from?
I only can find the "older" versions of BlazeDS in the central mvn repository.

The other option is to deploy the downloaded BlazeDS jar files from the Adobe website into my local repository but it would be nice when Adobe provides the artifacts via a maven repository.

答: No, Adobe does not have a maven repository for BlazeDS. This thread can help. You can find BlazeDS 4 in the Spring maven repository: http://s3browse.springsource.com/browse/maven.springframework.org/external/com/adobe/blazeds/</p>


问:
mySQL time sum php now() in laravel seed
I have an expires_at column in mysql table. I want to fill this table using Laravel Seeding. Also i have "life_time" column in another table.

For example;

if the "life_time" is 00:05:00, my expires_at should be NOW() + 00:05:00...

expires_at is timestamp but life_time is only time. How can i create an expires_at using Carbon::now() + life_time or any time method which is showing current date.

Actually, i am trying to "A user send an image to other user using my cloud. This image has an expire date which is, if the other user does not download image from my cloud in life_time, i will delete." ... So i created a life time each file types. 5 min for images, 10 min for videos etc. I know send date and life time so i need to create expire date.

答:
There are many in-built functions in Carbon. you need to use  addHours(),addMinutes() , addSeconds() to add specific time in exist time.

For more information please visit : http://carbon.nesbot.com/docs/

Hope this will help you.


问:
Trigger to HCATALOG
Can I add a trigger to HCATALOG to track any changes to HIVE tables?  I want to notify an audience about the HIVE table changes. If adding triggers is not possible, what are the other approaches?</p>

答:
You can query the Hive metastore as below

Example Query

```<code>SELECT d.*, t.*
  FROM hive.TBLS t
  JOIN hive.DBS d
    ON t.DB_ID = d.DB_ID
 WHERE t.CREATE_TIME BETWEEN unix_timestamp('01-Dec-15  10.00.00', 'dd-MMM-yy hh.mm.ss')
                         AND unix_timestamp('07-Dec-15  10.00.00', 'dd-MMM-yy hh.mm.ss');
</code>```

This query gives you all tables created between 1st Dec 10AM to 7th Dec 10AM.

SELECT the columns you are interested in.

Hope this helps

Title: Trigger to HCATALOG

Body:
You can query the Hive metastore as below

Example Query

SELECT d.*, t.*
  FROM hive.TBLS t
  JOIN hive.DBS d
    ON t.DB_ID = d.DB_ID
 WHERE t.CREATE_TIME BETWEEN unix_timestamp('01-Dec-15  10.00.00', 'dd-MMM-yy hh.mm.ss')
                         AND unix_timestamp('07-Dec-15  10.00.00', 'dd-MMM-yy hh.mm.ss');

This query gives you all tables created between 1st Dec 10AM to 7th Dec 10AM.

SELECT the columns you are interested in.

Hope this helps


问:
SSIS Excel Import (Column Names Changing)
I have an Excel file that loosely resembles the following format:

I'll explain the next step of the SSIS element first as the column names are not "important" as I am un-pivoting the data in a data flow to start getting it usable:

The issue is, the file will be updated - years and quarters will be removed (historical), new ones added to replace the old ones.  That means, as we all know, the metadata on a data flow is broken.

The cell range and position etc. will always remain the same.

Is there a way it can be handled in a data flow with the column names (2016q1) being fluid?

Thanks

答: If the columns remain in order, then you can skip header rows and select 1st row does not contain headers.</p>


问:
Algorithm for optimal "intersection" of two results?
I have two results and like to get the best "order" of both these.
Example:

We have a race with 5 people in one race, and 7 in another. The outcome is:
Race 1.

```<code>1. Karl
2. Fred
3. John
4. Peter
5. Sid
</code>```

Race 2.

```<code>1. Steven
2. John
3. Karl
4. Peter
5. Aron
6. Fred
7. Kevin
</code>```

The questin is: whats the top 7 of both these races?

Its quite obvious that that nr 1 is Karl in this case, since he hold one 1st place and one 3rd, which is better than Johns second and third place. However, Steven could be equally good but he did only participate in one race and should suffer some kind of penalty for that.

What are the known algorithms for this problem? Are there any trivial solutions? I just can't figure it out

答: Another approach would be to create an ordering of the top nodes which are consistent with the  ordering of the previous races.  This could be done by using a max-flow algorithm.</p>

Body:
I have two results and like to get the best "order" of both these.
Example:

We have a race with 5 people in one race, and 7 in another. The outcome is:
Race 1.

1. Karl
2. Fred
3. John
4. Peter
5. Sid

Race 2.

1. Steven
2. John
3. Karl
4. Peter
5. Aron
6. Fred
7. Kevin

The questin is: whats the top 7 of both these races?

Its quite obvious that that nr 1 is Karl in this case, since he hold one 1st place and one 3rd, which is better than Johns second and third place. However, Steven could be equally good but he did only participate in one race and should suffer some kind of penalty for that.

What are the known algorithms for this problem? Are there any trivial solutions? I just can't figure it out


问:
How avoid having double loop?
From healthkit, I will receive some datas, for example steps data.

I save in my server this datas. Il have then an array of datas:

1.- startDate, endDate, value

2.- startDate, endDate, value

etc

It can be very lot of values in my server.

Then I get the values in the Healthkit. I have lot of values. Values who are in the server and new values.

I want to upload to the server only the new values.

I do so:

```<code>for each value in my server {
    for each value in healthkit{
        if(startDate, endDate and value are not equal to the value in the server){
            then save the value in the server
        }
    }
}
</code>```

The algo will work, but it's very very slow. I can have lot of values in the two systems. Most of them the same in the two places.

Have you an idea how to do better?

I cannot save a flag in the healthKit.

I'm using ionic with angular 4 and typescript.

答:
This answer assumes that the data on your server and the data from healthKit are sorted in the same way, or that you can sort them without affecting anything else.

For example you can sort your data on the server and the data from healthKit by StartDate, break ties by EndDate, then break ties by value.

Now you have two sorted arrays that you want to merge. The idea is to use the merge function of merge sort explained here.

You will end up with an array containing all the data without repetitions, which you can save on your server.

Edit:

```<code>void mergeArrays(int arr1[], int arr2[], int n1,
                             int n2, int arr3[])
{
    int i = 0, j = 0, k = 0;

    // Traverse both array
    while (i<n1 && j <n2)
    {
        // Check if current element of first
        // array is smaller than current element
        // of second array. If yes, store first
        // array element and increment first array
        // index. Otherwise do same with second array
        if (arr1[i] < arr2[j])
            arr3[k++] = arr1[i++];
        else if (arr2[j] < arr1[i])
            j++;
        else
            j++,i++;
    }

    // Store remaining elements of first array (healthKit Array)
    while (i < n1)
        arr3[k++] = arr1[i++];
}
</code>```

Title: How avoid having double loop?

Body:
From healthkit, I will receive some datas, for example steps data.

I save in my server this datas. Il have then an array of datas:

1.- startDate, endDate, value

2.- startDate, endDate, value

etc

It can be very lot of values in my server.

Then I get the values in the Healthkit. I have lot of values. Values who are in the server and new values.

I want to upload to the server only the new values.

I do so:

for each value in my server {
    for each value in healthkit{
        if(startDate, endDate and value are not equal to the value in the server){
            then save the value in the server
        }
    }
}

The algo will work, but it's very very slow. I can have lot of values in the two systems. Most of them the same in the two places.

Have you an idea how to do better?

I cannot save a flag in the healthKit.

I'm using ionic with angular 4 and typescript.

Body:
This answer assumes that the data on your server and the data from healthKit are sorted in the same way, or that you can sort them without affecting anything else.

For example you can sort your data on the server and the data from healthKit by StartDate, break ties by EndDate, then break ties by value.

Now you have two sorted arrays that you want to merge. The idea is to use the merge function of merge sort explained here.

You will end up with an array containing all the data without repetitions, which you can save on your server.

Edit:

void mergeArrays(int arr1[], int arr2[], int n1,
                             int n2, int arr3[])
{
    int i = 0, j = 0, k = 0;

    // Traverse both array
    while (i<n1 && j <n2)
    {
        // Check if current element of first
        // array is smaller than current element
        // of second array. If yes, store first
        // array element and increment first array
        // index. Otherwise do same with second array
        if (arr1[i] < arr2[j])
            arr3[k++] = arr1[i++];
        else if (arr2[j] < arr1[i])
            j++;
        else
            j++,i++;
    }

    // Store remaining elements of first array (healthKit Array)
    while (i < n1)
        arr3[k++] = arr1[i++];
}


问:
Using Azure Table Storage's retry policy with Azure Functions
I'm trying to put together an API using Azure Functions and store its data in Table Storage.  I have all this working, but I want to implement the retry policies which the Azure Storage Client provides.

Does anyone know if this is implemented 'behind the scenes' or is there some code I need add to the binding that passes the CloudTable into the function.

Thanks for your help.

答: I would go with Polly as you suggested. It's awesome. See my answer to a similar query here: Read retry on Azure Table which should give you a good idea as to implementation.</p>


问:
bootstrap 4 modal-header trying to get badge aligned on right
I'm trying to get the "Banana Score" badge to float right, but to no avail. Does anyone know if this is even possible in Bootstrap 4.

I've tried all sorts of variations around flex, the best I had was a hack using columns, but this looks worse than the example below.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Customer
            Banana Score  4

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

答:
No need to add any new style. Just add the bootstrap classes w-100 and float-right to the heading tag h5

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Customer
            Banana Score  4

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

Body:
No need to add any new style. Just add the bootstrap classes w-100 and float-right to the heading tag h5

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">

          <h5 class="modal-title w-100 float-right" id="exampleModalLabel">Customer
            <span id="test" class="badge badge-secondary float-right">Banana Score  <span class="badge badge-light">4</span></span></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


问:
Understanding deadlock
I am trying to understand how to create a deadlock from https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html.

Instead of copy and pasting the sample code, I chose to write it by myself.

The last line in the link says "neither block will ever end because each thread is waiting for the other to exit bow" but never mentions about System.out.format.

I then wrote the below code and it never entered deadlock

```<code>public class DeadlockTest {
  static class Resource {
    public synchronized void test1(Resource r) {
      System.out.print("test1");
      r.test2();
    }
    public synchronized void test2() {
      System.out.print("test2");
    }
  }
  public static void main(String... a) {
    final Resource r1 = new Resource();
    final Resource r2 = new Resource();
    new Thread(new Runnable() {
      public void run() {
        r1.test1(r2);
      }
    }).start();
    new Thread(new Runnable() {
      public void run() {
        r2.test1(r1);
      }
    }).start();
  }
}
</code>```

So I tried to compare line by line and found that only the print statement is wrong. Instead of using System.out.format I used System.out.print. So the code never ran in to a dead lock situation. I then changed it to System.out.format and I was able to simulate a dead lock.

I even copied the example code from the link, changed the format statement to print/println and it was not entering deadlock.

Can anyone please explain how to exactly create a deadlock?

答:
I took your code to test it. It indeed ran fine.

Only when I added a Thread.sleep(100) or the String.format in test1, it blocked. It seems as if your "work" method (print) is too fast. Before the second thread can cause the block by calling test1, the first thread is already finished with test2.

To stay in the tutorials example: Your threads did not in fact "bow at each other at the same time", but only "very quickly after one another". Make the bowing a little slower and you increase the chances of them bowing at the same time (still not guaranteed, e.g. if the system takes longer to schedule the second thread).

Title: Understanding deadlock

Body:
I am trying to understand how to create a deadlock from https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html.

Instead of copy and pasting the sample code, I chose to write it by myself.

The last line in the link says "neither block will ever end because each thread is waiting for the other to exit bow" but never mentions about System.out.format.

I then wrote the below code and it never entered deadlock

public class DeadlockTest {
  static class Resource {
    public synchronized void test1(Resource r) {
      System.out.print("test1");
      r.test2();
    }
    public synchronized void test2() {
      System.out.print("test2");
    }
  }
  public static void main(String... a) {
    final Resource r1 = new Resource();
    final Resource r2 = new Resource();
    new Thread(new Runnable() {
      public void run() {
        r1.test1(r2);
      }
    }).start();
    new Thread(new Runnable() {
      public void run() {
        r2.test1(r1);
      }
    }).start();
  }
}

So I tried to compare line by line and found that only the print statement is wrong. Instead of using System.out.format I used System.out.print. So the code never ran in to a dead lock situation. I then changed it to System.out.format and I was able to simulate a dead lock.

I even copied the example code from the link, changed the format statement to print/println and it was not entering deadlock.

Can anyone please explain how to exactly create a deadlock?


问:
How to do multi-conditional loops with Ansible?
I have roles and users. I would like to loop over my roles for users that contains the state=present.

```<code>iam_roles:
  - name: "developers-role"
    assume_role_policy_document: "developers"
    state: present
    managed_policy:
      - arn:aws:iam::XXXXXXXXXXX:policy/CustomAmazonS3ReadOnlyAccess

  - name: "bigdata-role"
    assume_role_policy_document: "bigdata"
    state: present
    managed_policy:
      - arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess
      - arn:aws:iam::XXXXXXXXXXX:policy/CustomAmazonRDSReadOnlyAccess

 iam_users:
   - name: test-user-1
     state: present
     groups: [developers]
     password:
     slack_name:
     access_key_state: create

   - name: test-user-2
     state: present
     groups: [developers]
     password:
     slack_name:
</code>```

I'm trying filter and get only the users with the state=present and use it on my when clause, but no luck so far.

```<code>- name: Loop all the present users
  debug: msg={{ item }}
  when: "{{ item.state == 'present' }}"
  with_items: "{{ iam_users }}"
  tags: always
  register: present_users

- set_fact:
    iam_present_users: "{{ present_users.results }}"
  tags: always

- name: Show only present users, ideally
  debug: msg="{{ iam_present_users }}"
  tags: always

- name: Manage AWS IAM Roles
  iam_role:
    name: "{{ item.name }}"
    assume_role_policy_document: "{{ lookup('template', policies_path + '/assume-role/' + item.assume_role_policy_document + '.json') }}"
    state: "{{ item.state }}"
    managed_policy: "{{ item.managed_policy }}"
  when: "{{ item.managed_policy is defined and iam_present_users is defined }}"
  with_items: "{{ iam_roles }}"
  tags: manage_roles
</code>```

答:
Your use of a debug statement to try to extract users seems odd.  If you want to select objects from a list based on the value of an attribute, your best choice is probably the Jinja2 selectattr filter.  For example, given this input:

```<code>iam_users:
  - name: test-user-1
    state: present
    groups: [developers]
    password:
    slack_name:
    access_key_state: create

  - name: test-user-2
    state: present
    groups: [developers]
    password:
    slack_name:

  - name: test-user-3
    state: absent
    groups: [developers]
    password:
    slack_name:
</code>```

You could use this set_fact task:

```<code>- set_fact:
    iam_present_users: "{{ iam_users|selectattr('state', 'equalto', 'present')|list }}"
</code>```

Which would result in iam_present_users containing:

```<code>"iam_present_users": [
    {
        "access_key_state": "create",
        "groups": [
            "developers"
        ],
        "name": "test-user-1",
        "password": null,
        "slack_name": null,
        "state": "present"
    },
    {
        "groups": [
            "developers"
        ],
        "name": "test-user-2",
        "password": null,
        "slack_name": null,
        "state": "present"
    }
]
</code>```

See the jinja documentation for the stock list of filters, and the ansible documentation for a list of filters specific to ansible.

Body:
I have roles and users. I would like to loop over my roles for users that contains the state=present.

iam_roles:
  - name: "developers-role"
    assume_role_policy_document: "developers"
    state: present
    managed_policy:
      - arn:aws:iam::XXXXXXXXXXX:policy/CustomAmazonS3ReadOnlyAccess

  - name: "bigdata-role"
    assume_role_policy_document: "bigdata"
    state: present
    managed_policy:
      - arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess
      - arn:aws:iam::XXXXXXXXXXX:policy/CustomAmazonRDSReadOnlyAccess

 iam_users:
   - name: test-user-1
     state: present
     groups: [developers]
     password:
     slack_name:
     access_key_state: create

   - name: test-user-2
     state: present
     groups: [developers]
     password:
     slack_name:

I'm trying filter and get only the users with the state=present and use it on my when clause, but no luck so far.

- name: Loop all the present users
  debug: msg={{ item }}
  when: "{{ item.state == 'present' }}"
  with_items: "{{ iam_users }}"
  tags: always
  register: present_users

- set_fact:
    iam_present_users: "{{ present_users.results }}"
  tags: always

- name: Show only present users, ideally
  debug: msg="{{ iam_present_users }}"
  tags: always

- name: Manage AWS IAM Roles
  iam_role:
    name: "{{ item.name }}"
    assume_role_policy_document: "{{ lookup('template', policies_path + '/assume-role/' + item.assume_role_policy_document + '.json') }}"
    state: "{{ item.state }}"
    managed_policy: "{{ item.managed_policy }}"
  when: "{{ item.managed_policy is defined and iam_present_users is defined }}"
  with_items: "{{ iam_roles }}"
  tags: manage_roles

Body:
Your use of a debug statement to try to extract users seems odd.  If you want to select objects from a list based on the value of an attribute, your best choice is probably the Jinja2 selectattr filter.  For example, given this input:

iam_users:
  - name: test-user-1
    state: present
    groups: [developers]
    password:
    slack_name:
    access_key_state: create

  - name: test-user-2
    state: present
    groups: [developers]
    password:
    slack_name:

  - name: test-user-3
    state: absent
    groups: [developers]
    password:
    slack_name:

You could use this set_fact task:

- set_fact:
    iam_present_users: "{{ iam_users|selectattr('state', 'equalto', 'present')|list }}"

Which would result in iam_present_users containing:

"iam_present_users": [
    {
        "access_key_state": "create",
        "groups": [
            "developers"
        ],
        "name": "test-user-1",
        "password": null,
        "slack_name": null,
        "state": "present"
    },
    {
        "groups": [
            "developers"
        ],
        "name": "test-user-2",
        "password": null,
        "slack_name": null,
        "state": "present"
    }
]

See the jinja documentation for the stock list of filters, and the ansible documentation for a list of filters specific to ansible.


问:
Could not compile dependency :mimerl when adding wallaby to my Elixir/Phoenix project
I'm new to Elixir/Phoenix and I'm now looking to write tests using Wallaby (or Hound, but it's the same issue).

For your information, I'm using a Docker image.

I'm trying to get Cabbage and Wallaby working, but as soon as I add Wallaby dependency to my project:

```<code>...
  defp deps do
    {:phoenix, "~> 1.3.0"},
    ...
    {:cowboy, "~> 1.0"},
    {:wallaby, "~> 0.19.2"}
  end
...
</code>```

then I have the following error when I run mix test:

```<code>escript: exception error: no match of right hand side value undefined
  in function  rebar_log:log/3 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar_log.erl, line 94)
  in call from rebar3:handle_error/1 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar3.erl, line 325)
  in call from escript:run/2 (escript.erl, line 759)
  in call from escript:start/1 (escript.erl, line 277)
  in call from init:start_em/1
  in call from init:do_boot/3
** (Mix) Could not compile dependency :mimerl, "/root/.mix/rebar3 bare compile --paths "/application/_build/test/lib/*/ebin"" command failed. You can recompile this dependency with "mix deps.compile mimerl", update it with "mix deps.update mimerl" or clean it with "mix deps.clean mimerl"
</code>```

Anyone who knows why do I have this error and how I could fix it?

答:
I finally figured out what was causing this issue: proxy!

I first tried to run this rebar3 process manually:

```<code>docker run --rm -it <container-name> /root/.mix/rebar3
</code>```

And I was already having the error.
Playing around in the container, I discovered that removing the proxy was making the process no more through any errors.

So, no matter about Docker, it was all about unsetting the company proxy of my machine in order to get it working through the public network.

Body:
I'm new to Elixir/Phoenix and I'm now looking to write tests using Wallaby (or Hound, but it's the same issue).

For your information, I'm using a Docker image.

I'm trying to get Cabbage and Wallaby working, but as soon as I add Wallaby dependency to my project:

...
  defp deps do
    {:phoenix, "~> 1.3.0"},
    ...
    {:cowboy, "~> 1.0"},
    {:wallaby, "~> 0.19.2"}
  end
...

then I have the following error when I run mix test:

escript: exception error: no match of right hand side value undefined
  in function  rebar_log:log/3 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar_log.erl, line 94)
  in call from rebar3:handle_error/1 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar3.erl, line 325)
  in call from escript:run/2 (escript.erl, line 759)
  in call from escript:start/1 (escript.erl, line 277)
  in call from init:start_em/1
  in call from init:do_boot/3
** (Mix) Could not compile dependency :mimerl, "/root/.mix/rebar3 bare compile --paths "/application/_build/test/lib/*/ebin"" command failed. You can recompile this dependency with "mix deps.compile mimerl", update it with "mix deps.update mimerl" or clean it with "mix deps.clean mimerl"

Anyone who knows why do I have this error and how I could fix it?

Body:
I finally figured out what was causing this issue: proxy!

I first tried to run this rebar3 process manually:

docker run --rm -it <container-name> /root/.mix/rebar3

And I was already having the error.
Playing around in the container, I discovered that removing the proxy was making the process no more through any errors.

So, no matter about Docker, it was all about unsetting the company proxy of my machine in order to get it working through the public network.


问:
Role of 'prepare' command & 'safemode' in HDFS Rolling Upgrade
In HDFS rolling upgrade page at a high level I am seeing the steps mentioned like below

hdfs dfsadmin -rollingUpgrade prepare

Upgrade standby NN2 and start NN2 with hdfs dfsadmin -rollingUpgrade started

Shutdown, upgrade NN1 and start NN1 with hdfs dfsadmin -rollingUpgrade started

But in cloudera documentation of Hadoop to prepare the cluster for upgrade it is just saying to enter NN in safemode & save namespace

```<code>sudo -u hdfs hdfs dfsadmin -safemode enter
sudo -u hdfs hdfs dfsadmin -saveNamespace
</code>```

Can some one let me know why there is a difference in the above steps?

Is it just sufficient to enter in -safemode before doing the upgrade?

If yes what does -rollingUpgrade started do then?

In the cloudera documentation I am not seeing anything about -safemode leave. When it will leave the safemode? Will it auto leave the safemode ?

答:
The Cloudera instructions are not for upgrading with zero downtime on the core Hadoop services. It explicitly says to shutdown everything.

I assume rollingUpgrade started command flags the namenode process to tell it not to attempt to become the active in case the standby fails over during the upgrade and it also makes the namenode become the standby, which is different from safe mode. Safe mode prevents metadata updates in the middle of the upgrade process

I do not think it automatically leaves safe mode. Please comment on the answer once you get there and figure that out

Body:
In HDFS rolling upgrade page at a high level I am seeing the steps mentioned like below

hdfs dfsadmin -rollingUpgrade prepare

Upgrade standby NN2 and start NN2 with hdfs dfsadmin -rollingUpgrade started

Shutdown, upgrade NN1 and start NN1 with hdfs dfsadmin -rollingUpgrade started

But in cloudera documentation of Hadoop to prepare the cluster for upgrade it is just saying to enter NN in safemode & save namespace

sudo -u hdfs hdfs dfsadmin -safemode enter
sudo -u hdfs hdfs dfsadmin -saveNamespace

Can some one let me know why there is a difference in the above steps?

Is it just sufficient to enter in -safemode before doing the upgrade?

If yes what does -rollingUpgrade started do then?

In the cloudera documentation I am not seeing anything about -safemode leave. When it will leave the safemode? Will it auto leave the safemode ?


问:
gradle: find to which project does a file belong
Let's consider this sample multi gradle project structure

```<code>build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java
</code>```

And let's say from git changelog I have changed files:

```<code>project-a/project-a-b/src/test.java
project-c/src/test2.java
</code>```

I need to find out to which project they belong

```<code>project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c
</code>```

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it

答:
I'd traverse up the parent hierarchy of the file until I found a project dir match</p>

```<code>public Project getOwningProject(File findMe) {
    Map<String, Project> map = [:]
    allprojects.each { Project p ->
        map[p.projectDir.absolutePath] = p
    }
    File dir = findMe.directory ? findMe : findMe.parentFile
    while (dir != null) {
       Project p = map[dir.absolutePath]
       if (p) return p
       dir = dir.parentFile
    }
    return null
}
</code>```

Body:
Let's consider this sample multi gradle project structure

build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java

And let's say from git changelog I have changed files:

project-a/project-a-b/src/test.java
project-c/src/test2.java

I need to find out to which project they belong

project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it

Body:
I'd traverse up the parent hierarchy of the file until I found a project dir match

public Project getOwningProject(File findMe) {
    Map<String, Project> map = [:]
    allprojects.each { Project p ->
        map[p.projectDir.absolutePath] = p
    }
    File dir = findMe.directory ? findMe : findMe.parentFile
    while (dir != null) {
       Project p = map[dir.absolutePath]
       if (p) return p
       dir = dir.parentFile
    }
    return null
}


问:
How do I change the default port (9000) that Play uses when I execute the "run" command?
How can I change the default port used by the play framework in development mode when issueing the "run" command on the play console.

This is for playframework 2.0 beta.

Using the http.port configuration parameter either on the command line or in the application.conf seems to have no effect:

```<code>C:\dev\prototype\activiti-preso>play run --http.port=8080
[info] Loading project definition from C:\dev\prototype\activiti-preso\project
[info] Set current project to activiti-preso (in build file:/C:/dev/prototype/activiti-preso/)

Windows, really? Ok, disabling colors.

--- (Running the application from SBT, auto-reloading is enabled) ---

[error] org.jboss.netty.channel.ChannelException: Failed to bind to: 0.0.0.0/0.0.0.0:9000
[error] Use 'last' for the full log.
</code>```

答:
Hope this helps someone.

via sbt settings:

```<code>...
.settings(PlayKeys.playDefaultPort := 8855)
...
</code>```

Body:
How can I change the default port used by the play framework in development mode when issueing the "run" command on the play console.

This is for playframework 2.0 beta.

Using the http.port configuration parameter either on the command line or in the application.conf seems to have no effect:

C:\dev\prototype\activiti-preso>play run --http.port=8080
[info] Loading project definition from C:\dev\prototype\activiti-preso\project
[info] Set current project to activiti-preso (in build file:/C:/dev/prototype/activiti-preso/)

Windows, really? Ok, disabling colors.

--- (Running the application from SBT, auto-reloading is enabled) ---

[error] org.jboss.netty.channel.ChannelException: Failed to bind to: 0.0.0.0/0.0.0.0:9000
[error] Use 'last' for the full log.

Body:
Hope this helps someone.

via sbt settings:

...
.settings(PlayKeys.playDefaultPort := 8855)
...


问:
List of Subpath strings Compared to List of FileInfo
I have the below method that is comparing a list (Rows) of subpaths to a List<FileInfo>, and adding any missing entries to a list _missingImageFolderEnteries. I'm using LINQ and have noticed it seems surprisingly slow to process. Any ideas why or thoughts on how to improve performance? Perhaps LINQ isn't right here but I thought it should be more efficient than standard looping.

```<code>private List<FileInfo> _imageFilesInFolderPathList = new List<FileInfo>();
private readonly List<Tuple<string, string>> _missingImageFolderEnteries = new List<Tuple<string, string>>();
private void CrossCheckImageWithFolder(EnumerableRowCollection<DataRow> Rows)
{
    foreach (var dr in Rows)
    {
        var filepath = dr[ImagePathHeader].ToString();

        if (!_imageFilesInFolderPathList.Any(row =>
            row.FullName.EndsWith(FilePathHandler.FormatSubPath(filepath))))
            _missingImageFolderEnteries.Add(
                new Tuple<string, string>(
                    filepath.Substring(CommonInitFolder.Length).StartsWith("\\")
                        ? filepath.Substring(CommonInitFolder.Length)
                        : "\\" + filepath.Substring(CommonInitFolder.Length),
                    " does not exist in image folder"));
    }

    _missingImageFolderEnteries.Sort((x, y) => y.Item1.CompareTo(x.Item1));
}

public static string FormatSubPath(string path, bool needsSlash = true)
{
    var returnPath = path;
    if (returnPath.StartsWith("."))
        returnPath = returnPath.Substring(1);
    if (!returnPath.StartsWith("\\") && needsSlash)
        returnPath = "\\" + returnPath;
    else if (returnPath.StartsWith("\\") && !needsSlash)
        returnPath = returnPath.Substring(1);

    return returnPath;
}
</code>```

答:
Linq is a level of abstraction so it could never be faster than manual loop.

As for your problem I would try converting _imageFilesInFolderPathList to HashSet<string> containing names of files. Also you will need to compare whole string insted of using EndsWith to get performance boost.

Body:
I have the below method that is comparing a list (Rows) of subpaths to a List<FileInfo>, and adding any missing entries to a list _missingImageFolderEnteries. I'm using LINQ and have noticed it seems surprisingly slow to process. Any ideas why or thoughts on how to improve performance? Perhaps LINQ isn't right here but I thought it should be more efficient than standard looping.

private List<FileInfo> _imageFilesInFolderPathList = new List<FileInfo>();
private readonly List<Tuple<string, string>> _missingImageFolderEnteries = new List<Tuple<string, string>>();
private void CrossCheckImageWithFolder(EnumerableRowCollection<DataRow> Rows)
{
    foreach (var dr in Rows)
    {
        var filepath = dr[ImagePathHeader].ToString();

        if (!_imageFilesInFolderPathList.Any(row =>
            row.FullName.EndsWith(FilePathHandler.FormatSubPath(filepath))))
            _missingImageFolderEnteries.Add(
                new Tuple<string, string>(
                    filepath.Substring(CommonInitFolder.Length).StartsWith("\\")
                        ? filepath.Substring(CommonInitFolder.Length)
                        : "\\" + filepath.Substring(CommonInitFolder.Length),
                    " does not exist in image folder"));
    }

    _missingImageFolderEnteries.Sort((x, y) => y.Item1.CompareTo(x.Item1));
}

public static string FormatSubPath(string path, bool needsSlash = true)
{
    var returnPath = path;
    if (returnPath.StartsWith("."))
        returnPath = returnPath.Substring(1);
    if (!returnPath.StartsWith("\\") && needsSlash)
        returnPath = "\\" + returnPath;
    else if (returnPath.StartsWith("\\") && !needsSlash)
        returnPath = returnPath.Substring(1);

    return returnPath;
}


问:
Android..error while finding address given location
I am an android beginner getting the error: cannot resolve the symbol isPresent, in my following code snippet. Experts, please help!</p>

```<code>Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
    if(Geocoder.isPresent()){
        try {
            List<Address> addresses = geo.getFromLocation(l.getLatitude(),l.getLongitude(),1);
            if (addresses != null && addresses.size() >0){
                Address address = addresses.get(0);
                String addressText = String.format("%s,%s,%s", address.getLocality(),address.getCountryName());
                TextView place =(TextView)findViewById(R.id.place);
                place.setText(addressText);
            }

        }
        catch(IOException e){
            e.printStackTrace();
        }
</code>```

答:
Please change </p>

```<code>if(Geocoder.isPresent()){
  //code here
 }
</code>```

<p>replace it with </p>

```<code>  if(geo.isPresent()){
   //code here
  }
</code>```

Body:
I am an android beginner getting the error: cannot resolve the symbol isPresent, in my following code snippet. Experts, please help!

Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
    if(Geocoder.isPresent()){
        try {
            List<Address> addresses = geo.getFromLocation(l.getLatitude(),l.getLongitude(),1);
            if (addresses != null && addresses.size() >0){
                Address address = addresses.get(0);
                String addressText = String.format("%s,%s,%s", address.getLocality(),address.getCountryName());
                TextView place =(TextView)findViewById(R.id.place);
                place.setText(addressText);
            }

        }
        catch(IOException e){
            e.printStackTrace();
        }

Body:
Please change

if(Geocoder.isPresent()){
  //code here
 }

replace it with

  if(geo.isPresent()){
   //code here
  }


问:
Can't delete cells from UITableView, just the data from said cells

I am making an app that stores events and their data, and it was working flawlessly until I tried to add Core Data, since then, I've been having issues with it. One is the fact that using the delete func doesn't really delete the tablecell, just the data inside. If I try to delete the blank cell, it does nothing. Below is the code for the delete function I am using.

Also, my app for some reason starts with one of these blank cell, which can't be deleted.

```<code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {
        PersistenceService.context.delete(events[indexPath.row])

        do {
            try PersistenceService.context.save()
            eventLog.reloadData()
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }
}
</code>```

答:
You have to remove the item from the context and from the data source array and it's highly recommended to use deleteRows rather than reloading the entire table view to take advantage of the animation

```<code>PersistenceService.context.delete(events[indexPath.row])
events.remove(at: indexPath.row)
eventLog.deleteRows(at: [indexPath], with: .fade)

... save context
</code>```

Body:
I am making an app that stores events and their data, and it was working flawlessly until I tried to add Core Data, since then, I've been having issues with it. One is the fact that using the delete func doesn't really delete the tablecell, just the data inside. If I try to delete the blank cell, it does nothing. Below is the code for the delete function I am using.

Also, my app for some reason starts with one of these blank cell, which can't be deleted.

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {
        PersistenceService.context.delete(events[indexPath.row])

        do {
            try PersistenceService.context.save()
            eventLog.reloadData()
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }
}

Body:
You have to remove the item from the context and from the data source array and it's highly recommended to use deleteRows rather than reloading the entire table view to take advantage of the animation

PersistenceService.context.delete(events[indexPath.row])
events.remove(at: indexPath.row)
eventLog.deleteRows(at: [indexPath], with: .fade)

... save context


问:
Cant find a simple way to vibrate the phone (source code android)
```<code>Context mcontext;
this.Context= mcontext;
//private Context context;
//this.context=context;
//super(mcontext);
Vibrator mVibrator = (Vibrator) mcontext.getSystemService(Context.VIBRATOR_SERVICE);
mVibrator.vibrate(300)
</code>```

I searched online a lot for simple code to play a beep and I found one. But I am unable to add and compile few line of code to make the phone vibrate. All the threads I have come across uses getsystemservice().
Link to some code to vibrate on stackoverflow

First getsystemservice() function alone does not work and somewhere I read it needs to be called by a context object. I made a context object. Then it says context needs to be initialized. I tried this.context = context and that gives another error. I am getting into these cycle of compilation errors for what should be a simple job to just vibrate the phone. Please tell me what I am doing wrong here.

This question is different as I took the experience from other threads. As other threads give answer to use getsystemservice() alone but that does not work because it needs a context.

Update: came across this thread here How to pass context from MainActivity to another class in Android?

So I did this

```<code>public class MyNonActivityClass{

// variable to hold context
private Context context;

//save the context received via constructor in a local variable

public MyNonActivityClass(Context context){
this.context=context;
}

}
</code>```

But then I get error mcallback might not have been initialized here.

```<code>private final Callback mCallback;
</code>```

And then where do I add this

```<code>MyNonActivityClass mClass = new MyNonActivityClass(this);
</code>```

答:
From where you are calling the Vibrator service ?

If its from activity then,

```<code>Vibrator mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)
</code>```

or if its from Frgament then,

```<code> Vibrator mVibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)
</code>```

or update this in your code like,

```<code>void vibrate(Context mcontext ){
    Vibrator mVibrator = (Vibrator)
    mcontext.getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)
}
</code>```

Body:
Context mcontext;
this.Context= mcontext;
//private Context context;
//this.context=context;
//super(mcontext);
Vibrator mVibrator = (Vibrator) mcontext.getSystemService(Context.VIBRATOR_SERVICE);
mVibrator.vibrate(300)

I searched online a lot for simple code to play a beep and I found one. But I am unable to add and compile few line of code to make the phone vibrate. All the threads I have come across uses getsystemservice().
Link to some code to vibrate on stackoverflow

First getsystemservice() function alone does not work and somewhere I read it needs to be called by a context object. I made a context object. Then it says context needs to be initialized. I tried this.context = context and that gives another error. I am getting into these cycle of compilation errors for what should be a simple job to just vibrate the phone. Please tell me what I am doing wrong here.

This question is different as I took the experience from other threads. As other threads give answer to use getsystemservice() alone but that does not work because it needs a context.

Update: came across this thread here How to pass context from MainActivity to another class in Android?

So I did this

public class MyNonActivityClass{

// variable to hold context
private Context context;

//save the context received via constructor in a local variable

public MyNonActivityClass(Context context){
this.context=context;
}

}

But then I get error mcallback might not have been initialized here.

private final Callback mCallback;

And then where do I add this

MyNonActivityClass mClass = new MyNonActivityClass(this);

Body:
From where you are calling the Vibrator service ?

If its from activity then,

Vibrator mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)

or if its from Frgament then,

 Vibrator mVibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)

or update this in your code like,

void vibrate(Context mcontext ){
    Vibrator mVibrator = (Vibrator)
    mcontext.getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)
}


问:
Javascript Assign function does not work

I have an application showing two datatables. Both tables use the button extension to support a column visibility dialog.
The second table has a first column without title. In the column visibility Dialog the button should have a title, that is why i override the columnText function of the colvis extension

```<code>var buttons= [{
    extend: 'colvis',
    postfixButtons: ['colvisRestore'],
    collectionLayout: 'fixed three-column'
}];
if("secondTable" === tableName) {
    buttons[0]['columnText'] = function (dt, idx, title) {
        if (idx === 0) {
            return "firstColumnTitle";
        } else {
            return title;
        }
    };
    //add default buttons to buttons
    buttons[0]['buttons'] = [{extend: 'columnsToggle'}];
    //add one extra button to the collection
    buttons[0]['buttons'].push([
    {
        extend: 'columnToggle',
        text: 'HR',
        columns: [1, 2]
    }]);
}
DataTable({
    rowId: 'id',
    ajax: 'content.do',
    buttons: buttons
});
</code>```

I would expect to have the columntext function called for second table only

if i add buttons the columnText function is no longer called. Why?

答:
Thanks to the comments above @davidkonrad and @Adelin. If found the reason.

instead of assigning the columnText function to the colvis extension, i need to assign it to the columnsToggle Extension inside.

```<code>if("secondTable" === tableName) {
  //add default buttons to buttons
  buttons[0]['buttons'] = [{
    extend: 'columnsToggle',
    columnText: function (dt, idx, title) {
    if (idx === 0) {
      return "firstColumnTitle";
    } else {
      return title;
    }
  }}];
  //add one extra button to the collection
  buttons[0]['buttons'].push([
  {
    extend: 'columnToggle',
    text: 'HR',
    columns: [1, 2]
  }]);
}
</code>```

Body:
I have an application showing two datatables. Both tables use the button extension to support a column visibility dialog.
The second table has a first column without title. In the column visibility Dialog the button should have a title, that is why i override the columnText function of the colvis extension

var buttons= [{
    extend: 'colvis',
    postfixButtons: ['colvisRestore'],
    collectionLayout: 'fixed three-column'
}];
if("secondTable" === tableName) {
    buttons[0]['columnText'] = function (dt, idx, title) {
        if (idx === 0) {
            return "firstColumnTitle";
        } else {
            return title;
        }
    };
    //add default buttons to buttons
    buttons[0]['buttons'] = [{extend: 'columnsToggle'}];
    //add one extra button to the collection
    buttons[0]['buttons'].push([
    {
        extend: 'columnToggle',
        text: 'HR',
        columns: [1, 2]
    }]);
}
DataTable({
    rowId: 'id',
    ajax: 'content.do',
    buttons: buttons
});

I would expect to have the columntext function called for second table only

if i add buttons the columnText function is no longer called. Why?

Body:
Thanks to the comments above @davidkonrad and @Adelin. If found the reason.

instead of assigning the columnText function to the colvis extension, i need to assign it to the columnsToggle Extension inside.

if("secondTable" === tableName) {
  //add default buttons to buttons
  buttons[0]['buttons'] = [{
    extend: 'columnsToggle',
    columnText: function (dt, idx, title) {
    if (idx === 0) {
      return "firstColumnTitle";
    } else {
      return title;
    }
  }}];
  //add one extra button to the collection
  buttons[0]['buttons'].push([
  {
    extend: 'columnToggle',
    text: 'HR',
    columns: [1, 2]
  }]);
}


问:
How to identify a unix timestamp from a date?
Any ideas how I can make a simple IF-statement that sort 31-10-2017 or 12-01-2016 from 1511431687?

I am converting from a set date, to use unix timestamp, and need a solution to sort out what is what. I want to display the date in human readable format (days/ month/year).

So I have a $data that is inside a loop. It pulls the date from a flat file. The old stuff has just saved the date as a date. For instance 31-10-2017 (exactly like that).

Now I use unix timestamp. For instance 1511431687.

I see people have used a simple IF-statement, but I can not use it as both are 10 units long. Else that would have worked well.

```<code>$data = // either a timestamp, or a date in this format: 31-10-2017

if (strlen($data) === 10) // it's a timestamp
$data =  date("d-m-Y H:i:s", $data);
</code>```

答:
Maybe naive, but a solution might be to check if $data has a numeric value.</p>

```<code>if (is_numeric($data)) { // it's a timestamp
    $data =  date("d-m-Y H:i:s", (int) $data);
}
</code>```

Body:
Any ideas how I can make a simple IF-statement that sort 31-10-2017 or 12-01-2016 from 1511431687?

I am converting from a set date, to use unix timestamp, and need a solution to sort out what is what. I want to display the date in human readable format (days/ month/year).

So I have a $data that is inside a loop. It pulls the date from a flat file. The old stuff has just saved the date as a date. For instance 31-10-2017 (exactly like that).

Now I use unix timestamp. For instance 1511431687.

I see people have used a simple IF-statement, but I can not use it as both are 10 units long. Else that would have worked well.

$data = // either a timestamp, or a date in this format: 31-10-2017

if (strlen($data) === 10) // it's a timestamp
$data =  date("d-m-Y H:i:s", $data);

Body:
Maybe naive, but a solution might be to check if $data has a numeric value.

if (is_numeric($data)) { // it's a timestamp
    $data =  date("d-m-Y H:i:s", (int) $data);
}


问:
Alternate color for listview item UWP
I have a class to color alternate the background of item, but if I delete a item, the background color does not update.
Is there a way to refresh the background color after deleting an item?

The code for alterante color.
class listview:

```<code>public class AlternatingRowListView : ListView
{
    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        base.PrepareContainerForItemOverride(element, item);
        var listViewItem = element as ListViewItem;
        if (listViewItem != null)
        {
            var index = IndexFromContainer(element);

            if (index % 2 == 0)
            {
                listViewItem.Background = new SolidColorBrush(Colors.LightBlue);
            }
            else
            {
                listViewItem.Background = new SolidColorBrush(Colors.Transparent);
            }
        }

    }
}
</code>```

code xaml:

```<code><local:AlternatingRowListView x:Name="listview">
        <ListViewItem>item 1</ListViewItem>
        <ListViewItem>item 2</ListViewItem>
        <ListViewItem>item 3</ListViewItem>
        <ListViewItem>item 4</ListViewItem>
        <local:AlternatingRowListView.ItemTemplate>
            <DataTemplate>

            </DataTemplate>
        </local:AlternatingRowListView.ItemTemplate>
</local:AlternatingRowListView>
</code>```

Thanks in advance.

答:
if you are searching alternate odd/even row colors:

in app.xml

```<code><Application
  ...
  <Application.Resources>
    <AlternateColorConverterx:Key="AlternateColorConverter" />
   ...
  </Application.Resources>
</code>```

generate a new class namely AlternateColorConverter.cs

(modify your hex colors.)

```<code>  class AlternateColorConverter : IValueConverter
{
    private static int idx_=-1;
    private static int odd_=0;
    private static int idx(int offset)
    {
        int idx_before = idx_;
        idx_ = (idx_ + 1) % (offset);

        if (idx_ < idx_before) odd_=(odd_+1)%2;
        return odd_;
    }

    public static Color GetColorFromHex(string hexString)
    {
        Color x = (Color)XamlBindingHelper.ConvertValue(typeof(Color), hexString);
        return x;
    }

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        int param = System.Convert.ToInt32(parameter);
        return new SolidColorBrush(ColorUtils.GetColorFromHex((idx(param) == 0) ? "#F24C27" : "#FBBA42"));
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}
</code>```

and in yourpage.xml.cs :

(where ConverterParameter(offset) depends on column count. usually 2)

```<code><ListView HorizontalAlignment="Stretch" Style="{StaticResource ListViewStyle}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                <Setter Property="MaxHeight" Value="20"/>
                <Setter Property="MinHeight" Value="20"/>
                <Setter Property="Padding" Value="0"/>
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="Models:YourObservableArray">
                <Grid HorizontalAlignment="Stretch" Margin="0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="180*"/>
                        <ColumnDefinition Width="100*"/>
                    </Grid.ColumnDefinitions>
                    <Border Background="{Binding Converter={StaticResource AlternateColorConverter},ConverterParameter=2}" HorizontalAlignment="Stretch" Grid.Column="0"  Margin="0">
                        <TextBlock Text="{x:Bind Field1}" HorizontalAlignment="Stretch"/>
                    </Border>
                    <Border Background="{Binding Converter={StaticResource AlternateColorConverter},ConverterParameter=2}" HorizontalAlignment="Stretch" Grid.Column="0"  Margin="0">
                        <TextBlock Text="{x:Bind Field2}" HorizontalAlignment="Stretch"/>
                    </Border>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

Title: Alternate color for listview item UWP

Body:
I have a class to color alternate the background of item, but if I delete a item, the background color does not update.
Is there a way to refresh the background color after deleting an item?

The code for alterante color.
class listview:

public class AlternatingRowListView : ListView
{
    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        base.PrepareContainerForItemOverride(element, item);
        var listViewItem = element as ListViewItem;
        if (listViewItem != null)
        {
            var index = IndexFromContainer(element);

            if (index % 2 == 0)
            {
                listViewItem.Background = new SolidColorBrush(Colors.LightBlue);
            }
            else
            {
                listViewItem.Background = new SolidColorBrush(Colors.Transparent);
            }
        }

    }
}

code xaml:

<local:AlternatingRowListView x:Name="listview">
        <ListViewItem>item 1</ListViewItem>
        <ListViewItem>item 2</ListViewItem>
        <ListViewItem>item 3</ListViewItem>
        <ListViewItem>item 4</ListViewItem>
        <local:AlternatingRowListView.ItemTemplate>
            <DataTemplate>

            </DataTemplate>
        </local:AlternatingRowListView.ItemTemplate>
</local:AlternatingRowListView>

Thanks in advance.

Body:
if you are searching alternate odd/even row colors:

in app.xml

<Application
  ...
  <Application.Resources>
    <AlternateColorConverterx:Key="AlternateColorConverter" />
   ...
  </Application.Resources>

generate a new class namely AlternateColorConverter.cs

(modify your hex colors.)

  class AlternateColorConverter : IValueConverter
{
    private static int idx_=-1;
    private static int odd_=0;
    private static int idx(int offset)
    {
        int idx_before = idx_;
        idx_ = (idx_ + 1) % (offset);

        if (idx_ < idx_before) odd_=(odd_+1)%2;
        return odd_;
    }

    public static Color GetColorFromHex(string hexString)
    {
        Color x = (Color)XamlBindingHelper.ConvertValue(typeof(Color), hexString);
        return x;
    }

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        int param = System.Convert.ToInt32(parameter);
        return new SolidColorBrush(ColorUtils.GetColorFromHex((idx(param) == 0) ? "#F24C27" : "#FBBA42"));
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

and in yourpage.xml.cs :

(where ConverterParameter(offset) depends on column count. usually 2)

<ListView HorizontalAlignment="Stretch" Style="{StaticResource ListViewStyle}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                <Setter Property="MaxHeight" Value="20"/>
                <Setter Property="MinHeight" Value="20"/>
                <Setter Property="Padding" Value="0"/>
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="Models:YourObservableArray">
                <Grid HorizontalAlignment="Stretch" Margin="0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="180*"/>
                        <ColumnDefinition Width="100*"/>
                    </Grid.ColumnDefinitions>
                    <Border Background="{Binding Converter={StaticResource AlternateColorConverter},ConverterParameter=2}" HorizontalAlignment="Stretch" Grid.Column="0"  Margin="0">
                        <TextBlock Text="{x:Bind Field1}" HorizontalAlignment="Stretch"/>
                    </Border>
                    <Border Background="{Binding Converter={StaticResource AlternateColorConverter},ConverterParameter=2}" HorizontalAlignment="Stretch" Grid.Column="0"  Margin="0">
                        <TextBlock Text="{x:Bind Field2}" HorizontalAlignment="Stretch"/>
                    </Border>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>


问:
CSS Opacity Transitions glitch on iPad Pro Retina
I'm having trouble on iPad Pro Retina with basic css opacity transitions

```<code>.fading-element {
    transition: opacity 1s;
    opacity: 1;
}

.fading-element.fade {
    opacity: 0;
}
</code>```

This works fine everywhere else but on iPad Pro on both Safari/Chrome the completed state appears momentarily before the transition begins.

https://codepen.io/mradammorley/pen/vWPxQG

答:
Issue no longer on IOS 11.2, but for those not yet updated to that version, try adding -webkit-tap-highlight-color: transparent; to affected element.

In Safari's documentation this "Overrides the highlight color shown when the user taps a link or a JavaScript clickable element in Safari on iOS."

Ref: https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariCSSRef/Articles/StandardCSSProperties.html#//apple_ref/doc/uid/TP30001266-_webkit_tap_highlight_color

Body:
I'm having trouble on iPad Pro Retina with basic css opacity transitions

.fading-element {
    transition: opacity 1s;
    opacity: 1;
}

.fading-element.fade {
    opacity: 0;
}

This works fine everywhere else but on iPad Pro on both Safari/Chrome the completed state appears momentarily before the transition begins.

https://codepen.io/mradammorley/pen/vWPxQG


问:
How to ensure my Google Home Assistant application is not rejected?

During our testing, we were unable to complete at least one of the behaviors or actions advertised by your app. Please make sure that a user can complete all core conversational flows listed in your registration information or recommended by your app.

Thank you for submitting your assistant app for review!

During testing, your app was unable to complete a function detailed in the app’s description. The reviewer interacted with the app by saying: “how many iphones were sold in the UK?” and app replied “I didn't get that. Can you try with other question?" and left conversation.

How can I resolve the above point to approve my Google Assistant action skills?

答: It means that somewhere, either in your app description or in a Dialogflow intent(they have full access to see what's in your intents) you hinted that “how many iphones were sold in the UK?” would be a valid question. Try changing the description/intents to properly match the restrictions of your app.</p>


问:
Iterate through two dimensional array while changing each element
I want to fill a two dimensional array with certain values. I want to get:

```<code>[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]
</code>```

How can I do it?

This is my code:

```<code>game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field
</code>```

答:
Just a note that building a Matrix is simple because it has an inherent notion of rows and columns:

```<code>Matrix.build(3){|i,j| "Num#{i}#{j}"}
</code>```

I think the Matrix class is often overlooked. The built-in methods to operate on rows, columns, submatrices, etc, can sometimes be really handy.

Body:
I want to fill a two dimensional array with certain values. I want to get:

[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]

How can I do it?

This is my code:

game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field

Body:
Just a note that building a Matrix is simple because it has an inherent notion of rows and columns:

Matrix.build(3){|i,j| "Num#{i}#{j}"}

I think the Matrix class is often overlooked. The built-in methods to operate on rows, columns, submatrices, etc, can sometimes be really handy.


问:
Automatic update a Windows application
How do I develop my Windows application so it will auto update on the client machine, like Firefox, Skype, etc.?

Is there any simple approach or any open source library which help me to do it just following some steps or a few lines of code?

答:
ClickOnce is what you're searching for.

You might also find these SO questions interesting (which offers some different solutions):

Auto update for WinForms application

How do I implement an auto update strategy for my in-house winform app

Title: Automatic update a Windows application


问:
Clickable Json links
I'm browsing a json file with Firefox to navigate, I have to copy and paste the links in the document.

Is there a possibility to make these links hyperlink-style clickable?

答:
Use following GreaseMonkey script (optionally fire it for JSON paths on your domain too).

```<code>// ==UserScript==
// @name        JSON links
// @namespace   http://example.com/json-links
// @description Clickable links in JSON
// @include     http://localhost/*
// @version     1
// @grant       none
// ==/UserScript==

setTimeout(function() {
    Array.forEach(
        document.querySelectorAll('.objectBox-string'),
        function(span) {
            var url = span.firstChild.nodeValue;
            url = /^\s*"((?:http|https|ftp):\/\/.*)"\s*$/.exec(url);
            if(!url) return;
            url = url[1];

            var a = document.createElement('a');
            a.href = url;
            a.appendChild(span.firstChild);

            span.parentNode.replaceChild(a, span);
        }
    );
}, 300);  // FF dev tools transform JSON into HTML dynamically therefore timeout
</code>```

If you need to run it on local files too, see this answer:

Run Greasemonkey on html files located on the local filesystem?

(although I don't know if it works in the current version of Firefox).

Title: Clickable Json links

Body:
Use following GreaseMonkey script (optionally fire it for JSON paths on your domain too).

// ==UserScript==
// @name        JSON links
// @namespace   http://example.com/json-links
// @description Clickable links in JSON
// @include     http://localhost/*
// @version     1
// @grant       none
// ==/UserScript==

setTimeout(function() {
    Array.forEach(
        document.querySelectorAll('.objectBox-string'),
        function(span) {
            var url = span.firstChild.nodeValue;
            url = /^\s*"((?:http|https|ftp):\/\/.*)"\s*$/.exec(url);
            if(!url) return;
            url = url[1];

            var a = document.createElement('a');
            a.href = url;
            a.appendChild(span.firstChild);

            span.parentNode.replaceChild(a, span);
        }
    );
}, 300);  // FF dev tools transform JSON into HTML dynamically therefore timeout

If you need to run it on local files too, see this answer:

Run Greasemonkey on html files located on the local filesystem?

(although I don't know if it works in the current version of Firefox).


问:
JS Scrolling doesn't seem to work on my website

So I am trying to use the smooth scrolling animation used in this template:

https://blackrockdigital.github.io/startbootstrap-scrolling-nav/

After adding the js files to my directory, including the basic JQuery files, I've seen the custom .js file that adds the scrolling uses the .class parameter in an anchor tag to detect if clicking it should trigger the smoothscrolling. So I added those to my anchor tags.

Below is the relevant code.

I will include a live preview too.

index.html file

```<code><!-- Navigation section -->
<section class="nav" id="nav">
    <div class="container">
        <div class="row" style="width: 100%; text-align: center;">
            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#about">About me</a>
            </div>

            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#work">My work</a>
            </div>

            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                <a class="js-scroll-trigger btn btn-lg btn-nav" href="#contact">Contact</a>
            </div>
        </div>
    </div>
</section>
</code>```

Script imports in index.html

```<code><!-- Import js -->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/scrolling-nav.js"></script>
</code>```

Scrolling-nav.js

```<code>(function($) {
  "use strict"; // Start of use strict

  // Smooth scrolling using jQuery easing
  $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
  });

})(jQuery); // End of use strict
</code>```

I have nearly no experience with JQuery / JS, so it's hard for me to understand where it might be going wrong.

Here is a live preview of the website with above code in it:

Live preview

Full code:

Github link

If there's any information missing, let me know.

答:
Add this code in you jquery</p>

```<code>    $(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});
</code>```

Body:
So I am trying to use the smooth scrolling animation used in this template:

https://blackrockdigital.github.io/startbootstrap-scrolling-nav/

After adding the js files to my directory, including the basic JQuery files, I've seen the custom .js file that adds the scrolling uses the .class parameter in an anchor tag to detect if clicking it should trigger the smoothscrolling. So I added those to my anchor tags.

Below is the relevant code.

I will include a live preview too.

index.html file

                About me

                My work

                Contact

Script imports in index.html

Scrolling-nav.js

(function($) {
  "use strict"; // Start of use strict

  // Smooth scrolling using jQuery easing
  $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
  });

})(jQuery); // End of use strict

I have nearly no experience with JQuery / JS, so it's hard for me to understand where it might be going wrong.

Here is a live preview of the website with above code in it:

Live preview

Full code:

Github link

If there's any information missing, let me know.

Body:
Add this code in you jquery

    $(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});


问:
Find the value of one column based on maximum value in another column per group
I have a query which gives me three columns: an ID, the day of week of event and count of how many events each day of week has, i.e.

```<code>ID    Day_Name    Cnt
1     Thursday    1
2     Monday      3
2     Thursday    2
2     Sunday      2
3     Tuesday     7
3     Wednesday   3
</code>```

I get this by using query

```<code>SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
FROM EVENT AS E

INNER JOIN PERSON AS P
ON P.ID_2 = E.ID_2

WHERE E.EVENT_DATE > '2016-01-01'
AND E.EVENT_STATUS LIKE '%OCCURED%'

GROUP BY P.ID, DAYNAME(E.EVENT_DATE)
</code>```

I would like to reduce this query to only return the day of week for each user with the maximum count. At the same time, I would like to change the column with counts to instead show the frequency of events for that weekday. For the example above I would like to change the output to be

```<code>ID    Day_Name    Frequency
1     Thursday    1
2     Monday      0.429
3     Tuesday     0.7
</code>```

Thankful if anyone got an idea

答:
So here's a partial answer...

```<code>SELECT a.*
  FROM ([your query here]) a
  JOIN
     ( SELECT id,MAX(cnt) cnt FROM ([your query here]) GROUP BY id ) b
    ON b.id = a.id
   AND b.cnt = a.cnt;
</code>```

For a more complete answer I suggest you provide the original 18 row data set. See: Why should I provide an MCVE for what seems to me to be a very simple SQL query?

Body:
I have a query which gives me three columns: an ID, the day of week of event and count of how many events each day of week has, i.e.

ID    Day_Name    Cnt
1     Thursday    1
2     Monday      3
2     Thursday    2
2     Sunday      2
3     Tuesday     7
3     Wednesday   3

I get this by using query

SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
FROM EVENT AS E

INNER JOIN PERSON AS P
ON P.ID_2 = E.ID_2

WHERE E.EVENT_DATE > '2016-01-01'
AND E.EVENT_STATUS LIKE '%OCCURED%'

GROUP BY P.ID, DAYNAME(E.EVENT_DATE)

I would like to reduce this query to only return the day of week for each user with the maximum count. At the same time, I would like to change the column with counts to instead show the frequency of events for that weekday. For the example above I would like to change the output to be

ID    Day_Name    Frequency
1     Thursday    1
2     Monday      0.429
3     Tuesday     0.7

Thankful if anyone got an idea

Body:
So here's a partial answer...

SELECT a.*
  FROM ([your query here]) a
  JOIN
     ( SELECT id,MAX(cnt) cnt FROM ([your query here]) GROUP BY id ) b
    ON b.id = a.id
   AND b.cnt = a.cnt;

For a more complete answer I suggest you provide the original 18 row data set. See: Why should I provide an MCVE for what seems to me to be a very simple SQL query?


问:
Trigger shell script if a file has been modified
I have created a shell script which basically does 2 function,

1.Loads the data from .csv into table using sql loader.

2.Runs a procedure in oracle DB once the data is loaded.

What i want to know is that if someone populates the .csv file with valid data,i want to trigger the shell script automatically after waiting for 1 minute

答:
inotifywait should do the trick, and, if you need to wait for a minute insert a "sleep 60" command.

See here: https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes


问:
ionic cordova run android failed with exit code 1 in ionic 3
I'm making a simple camera preview project in ionic 3. I first added the platform with the command:

$ ionic cordova platform add android

Then when I try to run the project with:

$ ionic cordova run android

I get this message

I tried removing the android platform and then again adding it but it doesn't work.

答: You have installed app with same package name, uninstall it and try again</p>


问:
Facebook Api only returns 25 events max?
I am testing my new iframe app,

trying to get all events of an user, using the graph api.

```<code>$tempevent = $facebook->api('/me/events', 'get', array("fields"=>"id, name, start_time"));
</code>```

so it only returns 25 events .. the farthest events.

Any ideas?

Just checked out the JS-Version.. same result.

```<code>FB.api('/me/events', function(response) {
    console.log("event id: " + response.data[0].id); //k
    console.log("event id: " + response.data[24].id);  //k
    console.log("event id: " + response.data[25].id); //not k
});
</code>```

答:
Use FQL:

```<code>$tempevent = $this->facebook->api(array(
    'method' => 'fql.query',
    'query' => 'SELECT eid, name, start_time FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid = me())'
));
</code>```

Explanation:

Here you are getting all the events from the event table where the event id (eid) is IN the event_member table where the user me() is linked to, whether he is attending, unsure, declined, or not_replied.

Body:
I am testing my new iframe app,

trying to get all events of an user, using the graph api.

$tempevent = $facebook->api('/me/events', 'get', array("fields"=>"id, name, start_time"));

so it only returns 25 events .. the farthest events.

Any ideas?

Just checked out the JS-Version.. same result.

FB.api('/me/events', function(response) {
    console.log("event id: " + response.data[0].id); //k
    console.log("event id: " + response.data[24].id);  //k
    console.log("event id: " + response.data[25].id); //not k
});

Body:
Use FQL:

$tempevent = $this->facebook->api(array(
    'method' => 'fql.query',
    'query' => 'SELECT eid, name, start_time FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid = me())'
));

Explanation:

Here you are getting all the events from the event table where the event id (eid) is IN the event_member table where the user me() is linked to, whether he is attending, unsure, declined, or not_replied.