问:
Firebase send push notification from devices (IOS)
In ios I am using Firebase database and FCM. I have to send push notification from devices to devices by devices token. I have FCM API "https://fcm.googleapis.com/fcm/send" This is post method and add parameter
Like :

```<code>Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
    ...
  },
}
</code>```

but when I try to call this API this is alway return me an error , and the same API calling from android devices this is working in android, not in ios Here is my code and error, please give me the solution

```<code>-(void)sendPush
{

     NSDictionary *noti = @{@"body": @"This is a Firebase Cloud Messaging Topic Message", @"title": @"high"};
    NSDictionary *data = @{@"text": @"This is a Firebase Cloud Messaging Topic Message", @"title": @"high"};
    NSDictionary *params = @{@"to": @"dbpuoXnzY3o:APA91bH3AE_XCbsLpOXycNULcSh1GHzohEFdopmzkY_n8bm78E9_5fHyY3PLCwi5HtTLU_IoOwfdbDc5qCbyzc6tD9Ahg0EviCfbAmhftmMsPqfi0WC...",@"notification":noti,@"data":data};
    NSLog(@"%@",params);

    [NetworkManager postNotification:params getUrl:@"https://fcm.googleapis.com/fcm/send" success:^(id response) {
         NSLog(@"%@",response);

    } failure:^(NSError *error) {

    }];

}
</code>```

in nslog this looks like this

```<code>{
    data =     {
        text = "This is a Firebase Cloud Messaging Topic Message";
        title = high;
    };
    notification =     {
        body = "This is a Firebase Cloud Messaging Topic Message";
        title = high;
    };
    to = "dbpuoXnzY3o:APA91bH3AE_XCbsLpOXycNULcSh1GHzohEFdopmzkY_n8bm78E9_5fHyY3PLCwi5HtTLU_IoOwfdbDc5qCbyzc6tD9Ahg0EviCfbAmhftmMsPqfi0WC...";
}
</code>```

Afnetworking calling function

```<code> AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    manager.responseSerializer = [AFJSONResponseSerializer
                                  serializerWithReadingOptions:NSJSONReadingAllowFragments];
   // [manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"AIzaSyADxgFPrxx....." forHTTPHeaderField:@"key"];

   // NSLog(@"Token==%@",[GeneralSetting sharedInstance].token_number);
    [manager POST:URL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:appDelegate.window animated:YES];
        success(responseObject);

        ////NSLog(@"success!");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        [MBProgressHUD hideHUDForView:appDelegate.window animated:YES];
      NSLog(@"error: %@", error.description);

        // [self alert:@"" title:@""];
    }];
</code>```

ERROR is

```<code>error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo={NSUnderlyingError=0x17024a1d0 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17402fa40> { URL: https://fcm.googleapis.com/fcm/send } { status code: 401, headers {
    "Cache-Control" = "private, max-age=0";
    "Content-Encoding" = gzip;
    "Content-Length" = 259;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Tue, 04 Jul 2017 10:17:43 GMT";
    Expires = "Tue, 04 Jul 2017 10:17:43 GMT";
    Server = GSE;
    "alt-svc" = "quic=\":443\"; ma=2592000; v=\"39,38,37,36,35\"";
    "x-content-type-options" = nosniff;
    "x-frame-options" = SAMEORIGIN;
    "x-xss-protection" = "1; mode=block";
} },
</code>```

Please help me , Please give me solution

I have tried from postmen this is working from postmen

same data i am sending from code this is not working may be problem is sending dictionary
I am using this code

```<code>NSDictionary *noti = @{@"body": @"Hello", @"title": @"This is test message"};

    NSDictionary *params = @{@"to": [GeneralSetting sharedInstance].token_number,@"notification":noti};
    NSLog(@"%@",params);
</code>```

AND

```<code>[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"key=AIzaSy.....tBxdYAIRp2KBG0NoS8dOqgy4" forHTTPHeaderField:@"Authorization"];
</code>```

The Response is

```<code>{
    notification =     {
        body = Hello;
        title = "This is test message";
    };
    to = "dQgCDOK3sec:APA91zFbkqkgyTNrsYsEmUJwpCtMs1VAmXF9DpF_zQfBYui3UjCA9nYtS_TK549RPnlWEfe-jSvD9MMc3lTFNsGJlyIOqNm84s8GoW1LfTGG0geuWEclb";
}

 Request failed: bad request (400)
</code>```

答:
You can either:

1) Allow your app to accept the text/html data with:

```<code>manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
// OR
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
</code>```

2) Or better, change your data type so it is application/json as @user3589771 mentioned.

Make sure AFHTTPSessionManager is correctly formatting the JSON with AFJSONRequestSerializer

References: Here and Here

Body:
In ios I am using Firebase database and FCM. I have to send push notification from devices to devices by devices token. I have FCM API "https://fcm.googleapis.com/fcm/send" This is post method and add parameter
Like :

Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
    ...
  },
}

but when I try to call this API this is alway return me an error , and the same API calling from android devices this is working in android, not in ios Here is my code and error, please give me the solution

-(void)sendPush
{

     NSDictionary *noti = @{@"body": @"This is a Firebase Cloud Messaging Topic Message", @"title": @"high"};
    NSDictionary *data = @{@"text": @"This is a Firebase Cloud Messaging Topic Message", @"title": @"high"};
    NSDictionary *params = @{@"to": @"dbpuoXnzY3o:APA91bH3AE_XCbsLpOXycNULcSh1GHzohEFdopmzkY_n8bm78E9_5fHyY3PLCwi5HtTLU_IoOwfdbDc5qCbyzc6tD9Ahg0EviCfbAmhftmMsPqfi0WC...",@"notification":noti,@"data":data};
    NSLog(@"%@",params);

    [NetworkManager postNotification:params getUrl:@"https://fcm.googleapis.com/fcm/send" success:^(id response) {
         NSLog(@"%@",response);

    } failure:^(NSError *error) {

    }];

}

in nslog this looks like this

{
    data =     {
        text = "This is a Firebase Cloud Messaging Topic Message";
        title = high;
    };
    notification =     {
        body = "This is a Firebase Cloud Messaging Topic Message";
        title = high;
    };
    to = "dbpuoXnzY3o:APA91bH3AE_XCbsLpOXycNULcSh1GHzohEFdopmzkY_n8bm78E9_5fHyY3PLCwi5HtTLU_IoOwfdbDc5qCbyzc6tD9Ahg0EviCfbAmhftmMsPqfi0WC...";
}

Afnetworking calling function

 AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    manager.responseSerializer = [AFJSONResponseSerializer
                                  serializerWithReadingOptions:NSJSONReadingAllowFragments];
   // [manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"AIzaSyADxgFPrxx....." forHTTPHeaderField:@"key"];

   // NSLog(@"Token==%@",[GeneralSetting sharedInstance].token_number);
    [manager POST:URL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:appDelegate.window animated:YES];
        success(responseObject);

        ////NSLog(@"success!");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        [MBProgressHUD hideHUDForView:appDelegate.window animated:YES];
      NSLog(@"error: %@", error.description);

        // [self alert:@"" title:@""];
    }];

ERROR is

error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo={NSUnderlyingError=0x17024a1d0 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17402fa40> { URL: https://fcm.googleapis.com/fcm/send } { status code: 401, headers {
    "Cache-Control" = "private, max-age=0";
    "Content-Encoding" = gzip;
    "Content-Length" = 259;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Tue, 04 Jul 2017 10:17:43 GMT";
    Expires = "Tue, 04 Jul 2017 10:17:43 GMT";
    Server = GSE;
    "alt-svc" = "quic=\":443\"; ma=2592000; v=\"39,38,37,36,35\"";
    "x-content-type-options" = nosniff;
    "x-frame-options" = SAMEORIGIN;
    "x-xss-protection" = "1; mode=block";
} },

Please help me , Please give me solution

I have tried from postmen this is working from postmen

same data i am sending from code this is not working may be problem is sending dictionary
I am using this code

NSDictionary *noti = @{@"body": @"Hello", @"title": @"This is test message"};

    NSDictionary *params = @{@"to": [GeneralSetting sharedInstance].token_number,@"notification":noti};
    NSLog(@"%@",params);

AND

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"key=AIzaSy.....tBxdYAIRp2KBG0NoS8dOqgy4" forHTTPHeaderField:@"Authorization"];

The Response is

{
    notification =     {
        body = Hello;
        title = "This is test message";
    };
    to = "dQgCDOK3sec:APA91zFbkqkgyTNrsYsEmUJwpCtMs1VAmXF9DpF_zQfBYui3UjCA9nYtS_TK549RPnlWEfe-jSvD9MMc3lTFNsGJlyIOqNm84s8GoW1LfTGG0geuWEclb";
}

 Request failed: bad request (400)

Body:
You can either:

1) Allow your app to accept the text/html data with:

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
// OR
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

2) Or better, change your data type so it is application/json as @user3589771 mentioned.

Make sure AFHTTPSessionManager is correctly formatting the JSON with AFJSONRequestSerializer

References: Here and Here


来源: stackexchange

问:
Newtonsoft.json not working with Dotfuscator Xamarin PCL + Android release mode
I am using Dotfuscator "PreEmptive Solutions" for my Xamarin.Android project.
The Newtonsoft.json library does not work in my PCL (it works fine in Xamarin.Android only) while I am using Dotfuscator for release mode.
If I disabled Dotfuscator the app works fine.

Any idea how to fix it?

答:
if you link all assemblies from Android build --> linker

Note make sure you choose Release mode from Configuration

you need yo ignore link this assemblies

```<code>SQLitePCLRaw.batteries_green;SQLite-net;
</code>```

for more details

https://developer.xamarin.com/guides/android/advanced_topics/linking/

ContentLicense: CC BY-SA 3.0

Body:
if you link all assemblies from Android build --> linker

Note make sure you choose Release mode from Configuration

you need yo ignore link this assemblies

SQLitePCLRaw.batteries_green;SQLite-net;

for more details

https://developer.xamarin.com/guides/android/advanced_topics/linking/


问:
Unable to bind observale collection to ItemsControl
I have an Observable Collection, which I am trying to bind to an ItemsControl. The following is the snippet from my code.

Class Sample.ViewModel:

```<code>//Observabale collection getter/setter property
public ObservableCollection<SQuestion> SList
{
    get
    {
        return _sList;
    }
    set
    {
        if (_sList == value)
            return;
        _sList = value;
        if(PropertyChanged!=null)
            PropertyChanged(this, new PropertyChangedEventArgs("ListOfSamples"));
    }
}
</code>```

.xaml code:

View/Mainwindow.xaml

```<code><ItemsControl Height="422" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="751" ItemsSource="{Binding SList}" ItemTemplate="{StaticResource perItemTemplate}"/>
</code>```

In the above code, I have the specified the ItemsSource Binding but on running my application, the list does not appear in the ItemsControl and everything appears blank.:

However, if I try to assign the source to Listbox from my .cs code-behind as listBox1.ItemsSource = SList, the list box gets populated and works as expected.

Can somebody point what's the problem in the above with Binding that I am doing so that I can bind from xaml directly and not using code-behind?

答: Your property name in VM is SList but you are rising PropertyChange with different name: PropertyChanged(this, new PropertyChangedEventArgs("ListOfSamples"));. Replace it with PropertyChanged(this, new PropertyChangedEventArgs("SList")); and should be good (assuming VM is wired correctly)

Body:
I have an Observable Collection, which I am trying to bind to an ItemsControl. The following is the snippet from my code.

Class Sample.ViewModel:

//Observabale collection getter/setter property
public ObservableCollection<SQuestion> SList
{
    get
    {
        return _sList;
    }
    set
    {
        if (_sList == value)
            return;
        _sList = value;
        if(PropertyChanged!=null)
            PropertyChanged(this, new PropertyChangedEventArgs("ListOfSamples"));
    }
}

.xaml code:

View/Mainwindow.xaml

<ItemsControl Height="422" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="751" ItemsSource="{Binding SList}" ItemTemplate="{StaticResource perItemTemplate}"/>

In the above code, I have the specified the ItemsSource Binding but on running my application, the list does not appear in the ItemsControl and everything appears blank.:

However, if I try to assign the source to Listbox from my .cs code-behind as listBox1.ItemsSource = SList, the list box gets populated and works as expected.

Can somebody point what's the problem in the above with Binding that I am doing so that I can bind from xaml directly and not using code-behind?


问:
Property 'addRule' and 'insertRule' does not exist on type 'StyleSheet'
I have typescript code like below :-

export function getRootWindow():Window {
    return window.top;
}

export function getRootDocument():HTMLDocument {
    return getRootWindow().document;
}

declare global {
    interface Document {
        documentMode?: any;
    }
}

export function isBrowserIE() {
    return getRootDocument().documentMode;
}

export function addCssRule(cssString:string, num:number) {
    let isIE = isBrowserIE();

    if(getRootDocument().styleSheets[0] == undefined) {
        let head  = getRootDocument().head || getRootDocument().getElementsByTagName('head')[0];
        let style = getRootDocument().createElement('style');

        head.appendChild(style);
    }

    if(isIE) {
        getRootDocument().styleSheets[0].addRule(cssString,num);
    }else {
        getRootDocument().styleSheets[0].insertRule(cssString,num);
    }
}```
</div>
</div>
</p>

<p>This code works fine in javascript :-</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>

</head>
<body style="color: #fff; font-family: arial, sans-sarif; background-color: #333; text-align: center;">

<h2>My mute speaker</h2>

  <span></span>

<script>

    if(document.styleSheets[0] == undefined) {
        var head  = document.head || document.getElementsByTagName('head')[0];
        var style = document.createElement('style');

        head.appendChild(style);
    }

    var datawrkz_speaker     = document.getElementsByClassName("datawrkz_speaker")[0];

    datawrkz_speaker.addEventListener("click", function() {
        this.classList.toggle("mute");
    });

    function addCssRule(cssString, num) {
        var isIE = /*@cc_on!@*/false || !!document.documentMode;

        if(isIE) {
            document.styleSheets[0].addRule(cssString, num);
        }else {
            document.styleSheets[0].insertRule(cssString,num);
        }

    }

    // set css rules as below for mute button

   addCssRule(".datawrkz_speaker {height: 30px; width: 30px; position: relative; overflow: hidden; display: inline-block; }", 0);

    addCssRule(".datawrkz_speaker span {display: block; width: 8px; height: 8px; background: #fff; margin: 11px 0 0 2px; }", 1);

    addCssRule(".datawrkz_speaker span:after {content: ''; position: absolute; width: 0; height: 0; border-style: solid; border-color: transparent #fff transparent transparent; border-width: 10px 14px 10px 15px; left: -13px; top: 5px;}", 2);

    addCssRule(".datawrkz_speaker span:before {transform: rotate(45deg); border-radius: 0 50px 0 0; content: ''; position: absolute; width: 5px; height: 5px; border-style: double; border-color: #fff; border-width: 7px 7px 0 0; left: 18px; top: 9px; transition: all 0.2s ease-out; }", 3);

    addCssRule(".datawrkz_speaker:hover span:before {transform: scale(0.8) translate(-3px, 0) rotate(42deg); }", 4);

    addCssRule(".datawrkz_speaker.mute span:before {transform: scale(0.5) translate(-15px, 0) rotate(36deg); opacity: 0; }", 5);

</script>

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

I am getting errors in Typescript (first code snippet above):-

a. Property 'addRule' does not exist on type 'StyleSheet'

b. Property 'insertRule' does not exist on type 'StyleSheet'

答:
It is because type StyleSheet is realy missing addRule and insertRule methods. These methods are defined on CSSStyleSheet type.

You can said typescript that you realy know that type is CSSStyleSheet instead of predicted StyleSheet  by forcing typings and adding .toString call on num in addRule call (because typings it requires).

Therea are 2 possible syntax how to do it.

```<code>if (isIE) {
    (getRootDocument().styleSheets[0] as CSSStyleSheet).addRule(cssString, num.toString());
} else {
    (getRootDocument().styleSheets[0] as CSSStyleSheet).insertRule(cssString, num);
}
</code>```

alternative syntax

```<code>if (isIE) {
    (<CSSStyleSheet>getRootDocument().styleSheets[0]).addRule(cssString, num.toString());
} else {
    (<CSSStyleSheet>getRootDocument().styleSheets[0]).insertRule(cssString);
}
</code>```

Body:
I have typescript code like below :-

export function getRootWindow():Window {
    return window.top;
}

export function getRootDocument():HTMLDocument {
    return getRootWindow().document;
}

declare global {
    interface Document {
        documentMode?: any;
    }
}

export function isBrowserIE() {
    return getRootDocument().documentMode;
}

export function addCssRule(cssString:string, num:number) {
    let isIE = isBrowserIE();

    if(getRootDocument().styleSheets[0] == undefined) {
        let head  = getRootDocument().head || getRootDocument().getElementsByTagName('head')[0];
        let style = getRootDocument().createElement('style');

        head.appendChild(style);
    }

    if(isIE) {
        getRootDocument().styleSheets[0].addRule(cssString,num);
    }else {
        getRootDocument().styleSheets[0].insertRule(cssString,num);
    }
}

This code works fine in javascript :-

<!DOCTYPE html>

My mute speaker

I am getting errors in Typescript (first code snippet above):-

a. Property 'addRule' does not exist on type 'StyleSheet'

b. Property 'insertRule' does not exist on type 'StyleSheet'

Body:
It is because type StyleSheet is realy missing addRule and insertRule methods. These methods are defined on CSSStyleSheet type.

You can said typescript that you realy know that type is CSSStyleSheet instead of predicted StyleSheet  by forcing typings and adding .toString call on num in addRule call (because typings it requires).

Therea are 2 possible syntax how to do it.

if (isIE) {
    (getRootDocument().styleSheets[0] as CSSStyleSheet).addRule(cssString, num.toString());
} else {
    (getRootDocument().styleSheets[0] as CSSStyleSheet).insertRule(cssString, num);
}

alternative syntax

if (isIE) {
    (<CSSStyleSheet>getRootDocument().styleSheets[0]).addRule(cssString, num.toString());
} else {
    (<CSSStyleSheet>getRootDocument().styleSheets[0]).insertRule(cssString);
}


问:
How to fade in - fade out three images with random place and random size?
I want to place a div which fade in/out randomly with random size and random place.

I could show up three images randomly with fade-in/out but I couldn't place them random place with random size.

http://jsfiddle.net/qq68m/139/

jquery:

```<code>jQuery(function(){
    function random(n) {
        return Math.floor(Math.random() * n);
    }
    var transition_time = 2500;
    var waiting_time = 100;
    var images = $('div#block img');
    var n = images.length;
    var current = random(n);
    images.hide();
    images.eq(current).show();

    var interval_id = setInterval(function () {
        images.eq(current).fadeOut(transition_time, function () {
            current = random(n);
            images.eq(current).fadeIn(transition_time);
        });
    }, 2 * transition_time + waiting_time);
})
</code>```

html:

```<code><div id="block">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand1.png">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand2.png">
        <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand3.png">

</div>
</code>```

答:
Here is my solution. It allows you to specify the range of image scale sizes, and insures that no matter the scale, the randomly chosen position will not clip outside of the container. I hope this meets your requirements.

EDIT: I've updated the code so that non-quadrilateral images will now keep their proportions as well (as shown by Phil Murray examples).

If setting the size by css height/width doesn't work for you, perhaps using the CSS3 scaleX/scaleY property might give you smoother image scaling results.

If you have any further questions please ask in this posts comment.

jQuery(function(){
    function random(n) {
        return Math.floor(Math.random() * n);
    }
    var transition_time = 200;
    var waiting_time = 100;
    var images = $('div#block img');
    var n = images.length;
    var current = random(n);
    images.hide();
    images.eq(current).show();

    //get the size of the container
    var boxHeight = document.getElementById('block').offsetHeight;
    var boxWidth = document.getElementById('block').offsetWidth;

    //range of possible image scales
    var objectMaxHeight = 60;
    var objectMinHeight = 20;

    var interval_id = setInterval(function () {
        images.eq(current).fadeOut(transition_time, function () {
            current = random(n);

            //gets reference to selected image
            var $domImage = images.eq(current);

            //generates random heights and widths for the image to be shown in
            var generatedHeight =
              Math.floor(
                 Math.random() * (objectMaxHeight - objectMinHeight)
                 ) + objectMinHeight;

      // assigns values to the image
            $domImage.css('height', generatedHeight);
            $domImage.css('width', "auto");

            var imageAutoWidth = $domImage.width();

            var generatedYLocation = Math.floor(
              Math.random() * (boxHeight - generatedHeight + 1)
            ) + 0;

            var generatedXLocation = Math.floor(
                Math.random() * (boxWidth - imageAutoWidth)
            ) + 0;

            $domImage.css('top', generatedYLocation);
            $domImage.css('left', generatedXLocation);
            $domImage.fadeIn(transition_time);
        });
    }, 2 * transition_time + waiting_time);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#block {
  position: fixed;
  width: 300px;
  height: 300px;
  border: 1px solid red;
  background: yellow;
  overflow: hidden;
}

img {
  position:relative;
  top: 0;
  left: 0;
  height: 100px;
  width: 100px;
}</code>```

```

Body:
I want to place a div which fade in/out randomly with random size and random place.

I could show up three images randomly with fade-in/out but I couldn't place them random place with random size.

http://jsfiddle.net/qq68m/139/

jquery:

jQuery(function(){
    function random(n) {
        return Math.floor(Math.random() * n);
    }
    var transition_time = 2500;
    var waiting_time = 100;
    var images = $('div#block img');
    var n = images.length;
    var current = random(n);
    images.hide();
    images.eq(current).show();

    var interval_id = setInterval(function () {
        images.eq(current).fadeOut(transition_time, function () {
            current = random(n);
            images.eq(current).fadeIn(transition_time);
        });
    }, 2 * transition_time + waiting_time);
})

html:

Body:
Here is my solution. It allows you to specify the range of image scale sizes, and insures that no matter the scale, the randomly chosen position will not clip outside of the container. I hope this meets your requirements.

EDIT: I've updated the code so that non-quadrilateral images will now keep their proportions as well (as shown by Phil Murray examples).

If setting the size by css height/width doesn't work for you, perhaps using the CSS3 scaleX/scaleY property might give you smoother image scaling results.

If you have any further questions please ask in this posts comment.

jQuery(function(){
    function random(n) {
        return Math.floor(Math.random() * n);
    }
    var transition_time = 200;
    var waiting_time = 100;
    var images = $('div#block img');
    var n = images.length;
    var current = random(n);
    images.hide();
    images.eq(current).show();

    //get the size of the container
    var boxHeight = document.getElementById('block').offsetHeight;
    var boxWidth = document.getElementById('block').offsetWidth;

    //range of possible image scales
    var objectMaxHeight = 60;
    var objectMinHeight = 20;

    var interval_id = setInterval(function () {
        images.eq(current).fadeOut(transition_time, function () {
            current = random(n);

            //gets reference to selected image
            var $domImage = images.eq(current);

            //generates random heights and widths for the image to be shown in
            var generatedHeight =
              Math.floor(
                 Math.random() * (objectMaxHeight - objectMinHeight)
                 ) + objectMinHeight;

      // assigns values to the image
            $domImage.css('height', generatedHeight);
            $domImage.css('width', "auto");

            var imageAutoWidth = $domImage.width();

            var generatedYLocation = Math.floor(
              Math.random() * (boxHeight - generatedHeight + 1)
            ) + 0;

            var generatedXLocation = Math.floor(
                Math.random() * (boxWidth - imageAutoWidth)
            ) + 0;

            $domImage.css('top', generatedYLocation);
            $domImage.css('left', generatedXLocation);
            $domImage.fadeIn(transition_time);
        });
    }, 2 * transition_time + waiting_time);
})

#block {
  position: fixed;
  width: 300px;
  height: 300px;
  border: 1px solid red;
  background: yellow;
  overflow: hidden;
}

img {
  position:relative;
  top: 0;
  left: 0;
  height: 100px;
  width: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand1.png">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand2.png">
    <img src="http://mobler.com.tr/wp-content/uploads/2017/07/rand3.png">
    <img src="https://www.fillmurray.com/g/200/500">
    <img src="https://www.fillmurray.com/g/500/200">
</div>


问:
Run action when iOS device is near some map point
I have the mobile app that uses user's location when the app is running to show some places on a map (now it is Google Map).

I want to add a new feature - App in the background should notify the user when the device is near some map point or entering the predefined area.

How can it be done? Are there different approaches?

Where to start from?

What if my points stored on the server - should I save them on the device first and what if can't do it and new map points can be added when the app is not in memory?

What will be the most challenging in creating such feature?

p.s. I know about Ray's geofencing tutorial but I want to know - are there any different approaches and also about pitfalls of such feature

答:
First of all you must enable location updates and remote notifications in background modes(Your Target->Capabilities), then you must write in your location update function some code to detect that user is close to some location exapmle: </p>

```<code>   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            if let userLocation = locations.first {
                if location.coordinate.langtitude <= <some value> ||
                   location.coordinate.langtitude >= <some value> || ... {
                      runAction()
                    }
              }
    }

    func runAction() {
      //show local notification here
    }
</code>```

Body:
First of all you must enable location updates and remote notifications in background modes(Your Target->Capabilities), then you must write in your location update function some code to detect that user is close to some location exapmle:

   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            if let userLocation = locations.first {
                if location.coordinate.langtitude <= <some value> ||
                   location.coordinate.langtitude >= <some value> || ... {
                      runAction()
                    }
              }
    }

    func runAction() {
      //show local notification here
    }


问:
Installing pgdb: pg_config tool is not available
So here is my goal: To get a .py file that imports pgdb, to run.

For this, as far as I have understood, I need PygreSql.

I have both postgresql 9.4.4 and python 2.7.9 installed (Postgresql with source code and python with the normal download form the website.). I found the file PyGreSQL.tar (version 4.1.1) and I ran the command python setup.py build in the directory of the extracted tar file. I get the message Exception: pg_config tool is not available.. What can I do to fix this?

Thanks in advance!

答:
Try running this:

```<code>sudo apt-get install libpq-dev
</code>```

and retry.

Body:
Try running this:

sudo apt-get install libpq-dev

and retry.


问:
How to select the same columns of a numpy array based on indices of a second array
I need to filter dataframes or numpy arrays based on selected columns in a previous one, i.e. filtering the same columns as those in the first array.

Here is my approach:

Excludes zero variables (filtering, selection of columns in the first df)

```<code>df_NN_70 = df_NN_70.loc[:, (df_NN_70 != df_NN_70.ix[0]).any()]
</code>```

Sampling (separate 70% of data to be used as train/test sets)

```<code>df_NN = df_NN_70.sample(frac=0.7, replace=False, weights=None, random_state=seed, axis=None)
</code>```

Transforming to array as in NN with keras (it needs arrays)

```<code>df_NN_array = df_NN.as_matrix(columns=None)
</code>```

Split data into input (X) and output (Y) variables

```<code>X = df_NN_array[:, 0:df_NN_array.shape[1]-1]
Y = df_NN_array[:, 427]

print(type(df_NN_70.columns))
index_list= list(df_NN_70.columns)

index_list = index_list[0:427]
print(index_list)
</code>```

Filtering the same columns on a second based on the column list obtained from df_NN_x

```<code>filter_columns = index_list
df_filtered = np.array(df_NN_x)[filter_columns]
new.shape
</code>```

This filtering, however, does not work because it considers the index_list as the index of rows in the second array df_NN_x, but not the columns!

答:
You need to filter in the second dimension of the array, e.g.:

```<code>df_filtered = np.array(df_NN_x).ix[:, filter_columns]
</code>```

or:

```<code>df_filtered = np.array(df_NN_x)
df_filtered = df_filtered[df_filtered.columns[filter_columns]]
</code>```

Note that the first version includes the last element of your filter_columns-list, the second one doesn't.

Edit: My answer was for a numpy array, updated it to pandas.

Body:
I need to filter dataframes or numpy arrays based on selected columns in a previous one, i.e. filtering the same columns as those in the first array.

Here is my approach:

Excludes zero variables (filtering, selection of columns in the first df)

df_NN_70 = df_NN_70.loc[:, (df_NN_70 != df_NN_70.ix[0]).any()]

Sampling (separate 70% of data to be used as train/test sets)

df_NN = df_NN_70.sample(frac=0.7, replace=False, weights=None, random_state=seed, axis=None)

Transforming to array as in NN with keras (it needs arrays)

df_NN_array = df_NN.as_matrix(columns=None)

Split data into input (X) and output (Y) variables

X = df_NN_array[:, 0:df_NN_array.shape[1]-1]
Y = df_NN_array[:, 427]

print(type(df_NN_70.columns))
index_list= list(df_NN_70.columns)

index_list = index_list[0:427]
print(index_list)

Filtering the same columns on a second based on the column list obtained from df_NN_x

filter_columns = index_list
df_filtered = np.array(df_NN_x)[filter_columns]
new.shape

This filtering, however, does not work because it considers the index_list as the index of rows in the second array df_NN_x, but not the columns!

Body:
You need to filter in the second dimension of the array, e.g.:

df_filtered = np.array(df_NN_x).ix[:, filter_columns]

or:

df_filtered = np.array(df_NN_x)
df_filtered = df_filtered[df_filtered.columns[filter_columns]]

Note that the first version includes the last element of your filter_columns-list, the second one doesn't.

Edit: My answer was for a numpy array, updated it to pandas.


问:
Writing a DSL like Thor gem in Ruby?
I'm trying to figure out how the Thor gem creates a DSL like this (first example from their README)

```<code>class App < Thor                                                 # [1]
  map "-L" => :list                                              # [2]

  desc "install APP_NAME", "install one of the available apps"   # [3]
  method_options :force => :boolean, :alias => :string           # [4]
  def install(name)
    user_alias = options[:alias]
    if options.force?
      # do something
    end
    # other code
  end

  desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
  def list(search="")
    # list everything
  end
end
</code>```

Specifically, how does it know which method to map the desc and method_options call to?

答:
desc is pretty easy to implement, the trick is to use Module.method_added:

```<code>class DescMethods
  def self.desc(m)
    @last_message = m
  end

  def self.method_added(m)
    puts "#{m} described as #{@last_message}"
  end
end
</code>```

any class that inherits from DescMethods will have a desc method like Thor. For each method a message will be printed with the method name and description. For example:

```<code>class Test < DescMethods
  desc 'Hello world'
  def test
  end
end
</code>```

when this class is defined the string "test described as Hello world" will be printed.

ContentLicense: CC BY-SA 2.5

Title: Writing a DSL like Thor gem in Ruby?

Body:
I'm trying to figure out how the Thor gem creates a DSL like this (first example from their README)

class App < Thor                                                 # [1]
  map "-L" => :list                                              # [2]

  desc "install APP_NAME", "install one of the available apps"   # [3]
  method_options :force => :boolean, :alias => :string           # [4]
  def install(name)
    user_alias = options[:alias]
    if options.force?
      # do something
    end
    # other code
  end

  desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
  def list(search="")
    # list everything
  end
end

Specifically, how does it know which method to map the desc and method_options call to?

Body:
desc is pretty easy to implement, the trick is to use Module.method_added:

class DescMethods
  def self.desc(m)
    @last_message = m
  end

  def self.method_added(m)
    puts "#{m} described as #{@last_message}"
  end
end

any class that inherits from DescMethods will have a desc method like Thor. For each method a message will be printed with the method name and description. For example:

class Test < DescMethods
  desc 'Hello world'
  def test
  end
end

when this class is defined the string "test described as Hello world" will be printed.


问:
Repeated writing in different XMLfiles
I need to write GPS-Data in different XMLfiles. The files need to have the following format:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx>
<metadata>
<time>YYYY-MM-DDTHH:MM:SSZ</time>
</metadata>
<trk>
<name>YYYY-MM-DDTHH:MM:SSZ</name>
<trkseg>
<trkpt lat="12.1795" lon="12.3456">
<ele>-46.97</ele>
<time>YYYY-MM-DDTHH:MM:SSZ</time>
</trkpt>
// more trkpt
</trkseg>
</trk>
</gpx>
</code>```

I tried to do it with an XMLwriter. At first it constructs the part till trkpt.That works. The XmlWriterSettings were included because the Error told me to use ConformanceLevel "Auto" or "fregmented" ,but that didn't solve my issue.

```<code>XmlWriterSettings setting = new XmlWriterSettings();
setting.ConformanceLevel = ConformanceLevel.Auto;
setting.Indent = true;

DateTime localDate = DateTime.Now;
xmlWriter[0] = XmlWriter.Create("testbase.xml", setting);
for (int i = 1; i < (numOfXMLWriter); i++)
{
    xmlWriter[i] = XmlWriter.Create(test[i].Text, setting);
}
int tmp = 0;
foreach (XmlWriter writer in xmlWriter)
{
writer.WriteStartDocument(true);
writer.WriteStartElement("gpx");
writer.WriteStartElement("metadata");
writer.WriteStartElement("time");
writer.WriteString(localDate.Year + "-" + localDate.Month + "-" + localDate.Day + "T" + localDate.Hour + ":" + localDate.Minute + ":" + localDate.Second);
writer.WriteEndElement();       //time
writer.WriteEndElement();       //metadata
                                //trk + name
writer.WriteStartElement("trkseg");

}
</code>```

Later the received GPS-Data is written as individual trkpt.

```<code>xmlWriter[id].WriteStartElement("trkpt");
xmlWriter[id].WriteAttributeString("lat", splitData[4]);
xmlWriter[id].WriteAttributeString("lon", splitData[6]);
xmlWriter[id].WriteStartAttribute("ele");
xmlWriter[id].WriteString("0");
xmlWriter[id].WriteEndElement();        //</ele>
xmlWriter[id].WriteStartElement("time");
xmlWriter[id].WriteString(splitData[10][4] + splitData[10][5] + "-" + splitData[10][2] + splitData[10][3] + "-" + splitData[10][0] + splitData[10][1] + "T" + splitData[2][0] + splitData[2][1] + ":" + splitData[2][2] + splitData[2][3] + ":" + splitData[2][4] + splitData[2][5] + "Z");
xmlWriter[id].WriteEndElement();        //</time>
xmlWriter[id].WriteEndElement();        //</trkpt>
</code>```

The Error says:

```<code>InvalidOperationException: "Token StartElement in state EndRootElement would result in an invalid XML document”
</code>```

I think this is because the XMLwriter Closes all the nodes atomatically and later i try to add another Node on root Level. Is there a possibility to stap the writer from ending the document on it's own?
Thanks for your help!
Jonas

答:
Using xml linq</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            string header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?><gpx></gpx>";

            XDocument doc = XDocument.Parse(header);
            XElement gpx = doc.Root;

            gpx.Add(new object[] {
                new XElement("metadata"), new XElement("time", DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
                new XElement("trk",  new object[] {
                    new XElement("name", DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
                    new XElement("trksseg", new object[] {
                        new XElement("trkpt", new object[] {
                            new XAttribute("lat", 12.1795),
                            new XAttribute("lon", 12.3456),
                            new XElement("ele", -46.97),
                            new XElement("time",DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
                        })
                    })
                })
            });

        }
    }
}
</code>```

Title: Repeated writing in different XMLfiles

Body:
I need to write GPS-Data in different XMLfiles. The files need to have the following format:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx>
<metadata>
<time>YYYY-MM-DDTHH:MM:SSZ</time>
</metadata>
<trk>
<name>YYYY-MM-DDTHH:MM:SSZ</name>
<trkseg>
<trkpt lat="12.1795" lon="12.3456">
<ele>-46.97</ele>
<time>YYYY-MM-DDTHH:MM:SSZ</time>
</trkpt>
// more trkpt
</trkseg>
</trk>
</gpx>

I tried to do it with an XMLwriter. At first it constructs the part till trkpt.That works. The XmlWriterSettings were included because the Error told me to use ConformanceLevel "Auto" or "fregmented" ,but that didn't solve my issue.

XmlWriterSettings setting = new XmlWriterSettings();
setting.ConformanceLevel = ConformanceLevel.Auto;
setting.Indent = true;

DateTime localDate = DateTime.Now;
xmlWriter[0] = XmlWriter.Create("testbase.xml", setting);
for (int i = 1; i < (numOfXMLWriter); i++)
{
    xmlWriter[i] = XmlWriter.Create(test[i].Text, setting);
}
int tmp = 0;
foreach (XmlWriter writer in xmlWriter)
{
writer.WriteStartDocument(true);
writer.WriteStartElement("gpx");
writer.WriteStartElement("metadata");
writer.WriteStartElement("time");
writer.WriteString(localDate.Year + "-" + localDate.Month + "-" + localDate.Day + "T" + localDate.Hour + ":" + localDate.Minute + ":" + localDate.Second);
writer.WriteEndElement();       //time
writer.WriteEndElement();       //metadata
                                //trk + name
writer.WriteStartElement("trkseg");

}

Later the received GPS-Data is written as individual trkpt.

xmlWriter[id].WriteStartElement("trkpt");
xmlWriter[id].WriteAttributeString("lat", splitData[4]);
xmlWriter[id].WriteAttributeString("lon", splitData[6]);
xmlWriter[id].WriteStartAttribute("ele");
xmlWriter[id].WriteString("0");
xmlWriter[id].WriteEndElement();        //</ele>
xmlWriter[id].WriteStartElement("time");
xmlWriter[id].WriteString(splitData[10][4] + splitData[10][5] + "-" + splitData[10][2] + splitData[10][3] + "-" + splitData[10][0] + splitData[10][1] + "T" + splitData[2][0] + splitData[2][1] + ":" + splitData[2][2] + splitData[2][3] + ":" + splitData[2][4] + splitData[2][5] + "Z");
xmlWriter[id].WriteEndElement();        //</time>
xmlWriter[id].WriteEndElement();        //</trkpt>

The Error says:

InvalidOperationException: "Token StartElement in state EndRootElement would result in an invalid XML document”

I think this is because the XMLwriter Closes all the nodes atomatically and later i try to add another Node on root Level. Is there a possibility to stap the writer from ending the document on it's own?
Thanks for your help!
Jonas

Body:
Using xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            string header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?><gpx></gpx>";

            XDocument doc = XDocument.Parse(header);
            XElement gpx = doc.Root;

            gpx.Add(new object[] {
                new XElement("metadata"), new XElement("time", DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
                new XElement("trk",  new object[] {
                    new XElement("name", DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
                    new XElement("trksseg", new object[] {
                        new XElement("trkpt", new object[] {
                            new XAttribute("lat", 12.1795),
                            new XAttribute("lon", 12.3456),
                            new XElement("ele", -46.97),
                            new XElement("time",DateTime.Now.ToString("yyyy-MM-ddthh:mm:ssz")),
                        })
                    })
                })
            });

        }
    }
}


问:
How to Setup Angular 2 Project Properly
I use the following sample project to learn Angular 2:

https://bitbucket.org/syncfusiontech/angular-2-succinctly/overview

I did the following things:

after git clone https://bitbucket.org/syncfusiontech/angular-2-succinctly/overview I executed the following commands:

cd AsBook

npm install

npm start

A new browser instance is opened, but remains with the message Loading....

In the browser debug mode, I see the following errors:

jquery.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
jquery.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
bootstrap.min.js:6 Uncaught ZoneAwareErrormessage: (...)name: (...)originalStack: (...)stack: (...)toSource: function ()toString: function ()zoneAwareStack: (...)__zone_symbol__error: Error: Bootstrap's JavaScript requires jQuery
    at http://localhost:3000/node_modules/bootstrap/dist/js/bootstrap.min.js:6:37 [<root>]get message: function ()set message: function (value)get name: function ()set name: function (value)arguments: (...)caller: (...)length: 1name: "set"prototype: Object__proto__: function ()[[FunctionLocation]]: zone.js:899[[Scopes]]: Scopes[4]get originalStack: function ()set originalStack: function (value)get stack: function ()set stack: function (value)get zoneAwareStack: function ()set zoneAwareStack: function (value)__proto__: Object
:3000/app/main.js Failed to load resource: the server responded with a status of 404 (Not Found)
localhost/:23 ZoneAwareError
(anonymous) @ localhost/:23

How do I have to correct the package.json file to set it up properly?

package.json:

{ "name": "helloworld",
  "version": "1.0.0",
  "description": "First Angular-2 application",
  "author":"Joe Booth",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",

    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "UNLICENSED",
  "private": true,
  "dependencies": {
    "@angular/common": "~2.3.0",
    "@angular/compiler": "~2.3.0",
    "@angular/core": "~2.3.0",
    "@angular/forms": "~2.3.0",
    "@angular/http": "~2.3.0",
    "@angular/platform-browser": "~2.3.0",
    "@angular/platform-browser-dynamic": "~2.3.0",
    "@angular/router": "~3.3.0",
    "bootstrap": "^3.3.6",
    "systemjs": "0.19.39",

    "angular-in-memory-web-api": "~0.1.16",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-rc.4",
    "zone.js": "^0.7.2"
  },
  "devDependencies": {
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.3",

    "typings": "^1.4.0"

  }
}

答:
In index.html i see

```<code><script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
</code>```

Try execute

npm i jquery --save

Title: How to Setup Angular 2 Project Properly

Body:
In index.html i see

<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Try execute

npm i jquery --save


问:
vue.js How to call a function inside a for loop and pass the current item?
Using vue.js 2, inside a for loop, I need to render a row only if the current iterated item passes some test.

The test is complex so a simple v-if="item.value == x" wont do.

I've written a function named testIssue that accepts the item and returns true or false and tried to use that is av-if like this:

```<code><template v-for="issue in search_results.issues">
  <tr v-if="testIssue(issue)">
     ....
  </tr>
</template>

var releaseApp = new Vue({
  el: '#release-app',
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});
</code>```

However, testIssue is never called.

If I change the line to
, the function is called but then I dont have the issue variable that I need to test.

I also tried

How can I call a function in a v-if declaration inside a for loop and pass the current item?

答:
You can also try creating a computed item that makes use of the filter method so that you have an array where all elements pass the test function before actually rendering (in this case, just returning odd numbers):

https://codepen.io/aprouja1/pen/BZxejL

```<code>computed:{
    compIssues(){
      return this.search_results.issues.filter(el => el%2===1)
    }
  },
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using vue.js 2, inside a for loop, I need to render a row only if the current iterated item passes some test.

The test is complex so a simple v-if="item.value == x" wont do.

I've written a function named testIssue that accepts the item and returns true or false and tried to use that is av-if like this:

<template v-for="issue in search_results.issues">

     ....

</template>

var releaseApp = new Vue({
  el: '#release-app',
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});

However, testIssue is never called.

If I change the line to
, the function is called but then I dont have the issue variable that I need to test.

I also tried

How can I call a function in a v-if declaration inside a for loop and pass the current item?

Body:
You can also try creating a computed item that makes use of the filter method so that you have an array where all elements pass the test function before actually rendering (in this case, just returning odd numbers):

https://codepen.io/aprouja1/pen/BZxejL

computed:{
    compIssues(){
      return this.search_results.issues.filter(el => el%2===1)
    }
  },


问:
How to provide external url to docker image
I am working on Docker Image, I am a beginner on Docker.
I have one Docker Image, but what I want to update my Docker Image as that my Docker Image should accept the one external URL like:- and
start the further processing on it.

I do not have any clue how to do this, I am totally new on Docker and have only basic understanding of Docker.

答:
With docker-compose you can provide environment variables like this:

```<code>version: "3"
services:
  myapp:
    image: your-image
    environment:
      - FOO=http://example.com
      - BAR=456
</code>```

And depending on your application language, you can access to them. I.e for python:

```<code>import os
foo = os.environ.get("FOO")
bar = os.environ.get("BAR")
</code>```

Q. if I want to put it as dynamic whats need to be done , - FOO=<dynamic value>

You can do something like this:

```<code>version: "3"
services:
  myapp:
    image: your-image
    environment:
      - FOO
      - BAR
</code>```

Use as this:

```<code>$ export FOO=http://example.com
$ export BAR=456
$ docker-compose up
</code>```

Body:
With docker-compose you can provide environment variables like this:

version: "3"
services:
  myapp:
    image: your-image
    environment:
      - FOO=http://example.com
      - BAR=456

And depending on your application language, you can access to them. I.e for python:

import os
foo = os.environ.get("FOO")
bar = os.environ.get("BAR")

Q. if I want to put it as dynamic whats need to be done , - FOO=<dynamic value>

You can do something like this:

version: "3"
services:
  myapp:
    image: your-image
    environment:
      - FOO
      - BAR

Use as this:

$ export FOO=http://example.com
$ export BAR=456
$ docker-compose up


问:
Why can't I start a transaction while looping a result set?
I have the following PDO code (PHP 5.6, Microsoft SQL Server 2014):

```<code>$st = $db->prepare('SELECT TOP 5 * FROM table');
$st->execute();
while ($st->fetch()) {
    var_dump($db->beginTransaction());
    //$db->rollback();
}
</code>```

The result is as follows:

```<code>bool(false)
bool(false)
bool(false)
bool(false)
bool(true)
</code>```

I was expecting all true results, but the transaction is not started until the last record was retrieved. Why can't I start a transaction while looping through a result set?

Switching MARS on or off does not seem to have any effect.

答:
As long as the cursor is open, you cannot start a new transaction when using MSSQL. Calling closeCursor() on the result set or retrieving consuming all the results returned by the query frees that cursor and allows transactions once again.

Also; beginTransaction() returning false will also yield an error that can be retrieved using errorInfo(); saying:

New transaction is not allowed because there are other threads running in the session.

Body:
I have the following PDO code (PHP 5.6, Microsoft SQL Server 2014):

$st = $db->prepare('SELECT TOP 5 * FROM table');
$st->execute();
while ($st->fetch()) {
    var_dump($db->beginTransaction());
    //$db->rollback();
}

The result is as follows:

bool(false)
bool(false)
bool(false)
bool(false)
bool(true)

I was expecting all true results, but the transaction is not started until the last record was retrieved. Why can't I start a transaction while looping through a result set?

Switching MARS on or off does not seem to have any effect.


问:
Is there a way to get the path of a photo using the Flickr api?
When I upload a photo using the Flickr API it returns the photo id. I can then use that to find out what server the photo is on but i also need to know what farm that server is on.

Is there a way to get the farm id or some easier way to get the full path to an uploaded photo using the API, with C#.

Example:

http://farm5.static.flickr.com/4086/5198724006_3cb5f9b00c_m.jpg

Where farm5 is the farm, and 4086 is the server id in that farm.

Thanks, Scott.

答: Use the flickr.photos.getInfo API method, which includes all of the information you need to build the URL of the photo.


问:
Load Windows form after complete combobox data load in c#
I have a form for employees called frmEmployees where I need to load couple of combo box with data like country, category, nationality, such others.

Now when user click on to open frmEmployees, window is stuck for bit and then open. I assume that this is because of data loading and initializing the combo box.
Now! what I want is, just after click on button to open frmEmployees run a progress bar till data loading complete and then open form.

```<code>public frmEmployee()
    {
        InitializeComponent();
        con = new Connection();

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

I have tried also

```<code>private void FrmEmployee_Load(object sender, EventArgs e)
    {
        LoadComboboxDS();
    }

private void LoadComboboxDS()
    {
        //company
        var _companies = con.Companies.Where(x => x.IsDeleted == false).ToList();
        _companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
        cbCompany.DataSource = _companies;
        cbCompany.DisplayMember = "Name";
        cbCompany.ValueMember = "ID";

        //gender
        cbGender.DataSource = Enum.GetValues(typeof(Gender));

        //merital status
        cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));

        //citizenship
        var _citizenships = con.Countries.Select(x => x.Citizenship).Distinct().ToList();
        _citizenships.Insert(0, "--Select--");
        cbCitizenship.DataSource = _citizenships;
        cbCitizenship.DisplayMember = "Citizenship";

        //nationality
        var _nations = con.Countries.Select(x => x.Name).Distinct().ToList();
        _nations.Insert(0, "--Select--");
        cbNationality.DataSource = _nations;
        cbNationality.DisplayMember = "Name";

        //domicile
        var _domiciles = con.Countries.Select(x => x.Name).Distinct().ToList();
        _domiciles.Insert(0, "--Select--");
        cbDomicile.DataSource = _domiciles;
        cbDomicile.DisplayMember = "Name";

        //cast category
        var _casts = con.CastCategories.Select(x => new {x.ShortText, x.Description}).Distinct().ToList();
        _casts.Insert(0, new { ShortText = "", Description = "--Select--" });
        cbCategory.DataSource = _casts;
        cbCategory.DisplayMember = "Description";
        cbCategory.ValueMember = "ShortText";

        //religion
        cbReligion.DataSource = Enum.GetValues(typeof(Religion));

    }
</code>```

答:
You can use Async extension methods of Entity Framework 6 to make your code asynchronous.

Separate your data access and presentation layer, at first:

```<code>public static class MyRepository // consider not static, just an example
{
    public static async Task<List<Company>> GetCompanies()
    {
        using (var connection = new Connection()) // consider factory
        {
            return await con.Companies.Where(x => x.IsDeleted == false).ToListAsync();
        }
    }

    public async Task<List<Citizenship>> GetCitizenships()
    {
        using (var connection = new Connection()) // factory?
        {
            return await con.Countries.Select(x => x.Citizenship).Distinct().ToList();
        }
    }
}
</code>```

Then, you can run all these tasks at once and wait for them to complete:

```<code>// Wherever you are going to open frmEmployee
public async Task openFrmEmployee_OnClick(object sender, EventArgs e)
{
    var getCompaniesTask = MyRepository.GetCompanies();
    var getCitizenshipsTask = MyRepository.GetCitizenships();

    await Task.WhenAll(getCompaniesTask, getCitizenshipsTask); // UI thread is not blocked

    var form = new FrmEmployee(getCompaniesTask.Result, getCitizenshipsTask.Result); // form is created with data
}
</code>```

Now, you only need to make your form accept complete data in constructor instead of making your form load this data which breaks abstraction:

```<code>public class FrmEmployees
{
    public FrmEmployees(List<Company> companies, List<Citizenship> citizenships)
    {
        companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
        cbCompany.DataSource = companies;
        cbCompany.DisplayMember = "Name";
        cbCompany.ValueMember = "ID";

        citizenships.Insert(0, "--Select--");
        cbCitizenship.DataSource = _citizenships;
        cbCitizenship.DisplayMember = "Citizenship";

        // etc.
    }
}
</code>```

One important thing: you can get many tasks and many data passed to a form constructor. If all this data is going to be used often togetther, then you would probably want to encapsulate this "get all these things" logic into a single place to remove possible code duplication.

Body:
I have a form for employees called frmEmployees where I need to load couple of combo box with data like country, category, nationality, such others.

Now when user click on to open frmEmployees, window is stuck for bit and then open. I assume that this is because of data loading and initializing the combo box.
Now! what I want is, just after click on button to open frmEmployees run a progress bar till data loading complete and then open form.

public frmEmployee()
    {
        InitializeComponent();
        con = new Connection();

        LoadComboboxDS();
    }

I have tried also

private void FrmEmployee_Load(object sender, EventArgs e)
    {
        LoadComboboxDS();
    }

private void LoadComboboxDS()
    {
        //company
        var _companies = con.Companies.Where(x => x.IsDeleted == false).ToList();
        _companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
        cbCompany.DataSource = _companies;
        cbCompany.DisplayMember = "Name";
        cbCompany.ValueMember = "ID";

        //gender
        cbGender.DataSource = Enum.GetValues(typeof(Gender));

        //merital status
        cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));

        //citizenship
        var _citizenships = con.Countries.Select(x => x.Citizenship).Distinct().ToList();
        _citizenships.Insert(0, "--Select--");
        cbCitizenship.DataSource = _citizenships;
        cbCitizenship.DisplayMember = "Citizenship";

        //nationality
        var _nations = con.Countries.Select(x => x.Name).Distinct().ToList();
        _nations.Insert(0, "--Select--");
        cbNationality.DataSource = _nations;
        cbNationality.DisplayMember = "Name";

        //domicile
        var _domiciles = con.Countries.Select(x => x.Name).Distinct().ToList();
        _domiciles.Insert(0, "--Select--");
        cbDomicile.DataSource = _domiciles;
        cbDomicile.DisplayMember = "Name";

        //cast category
        var _casts = con.CastCategories.Select(x => new {x.ShortText, x.Description}).Distinct().ToList();
        _casts.Insert(0, new { ShortText = "", Description = "--Select--" });
        cbCategory.DataSource = _casts;
        cbCategory.DisplayMember = "Description";
        cbCategory.ValueMember = "ShortText";

        //religion
        cbReligion.DataSource = Enum.GetValues(typeof(Religion));

    }

Body:
You can use Async extension methods of Entity Framework 6 to make your code asynchronous.

Separate your data access and presentation layer, at first:

public static class MyRepository // consider not static, just an example
{
    public static async Task<List<Company>> GetCompanies()
    {
        using (var connection = new Connection()) // consider factory
        {
            return await con.Companies.Where(x => x.IsDeleted == false).ToListAsync();
        }
    }

    public async Task<List<Citizenship>> GetCitizenships()
    {
        using (var connection = new Connection()) // factory?
        {
            return await con.Countries.Select(x => x.Citizenship).Distinct().ToList();
        }
    }
}

Then, you can run all these tasks at once and wait for them to complete:

// Wherever you are going to open frmEmployee
public async Task openFrmEmployee_OnClick(object sender, EventArgs e)
{
    var getCompaniesTask = MyRepository.GetCompanies();
    var getCitizenshipsTask = MyRepository.GetCitizenships();

    await Task.WhenAll(getCompaniesTask, getCitizenshipsTask); // UI thread is not blocked

    var form = new FrmEmployee(getCompaniesTask.Result, getCitizenshipsTask.Result); // form is created with data
}

Now, you only need to make your form accept complete data in constructor instead of making your form load this data which breaks abstraction:

public class FrmEmployees
{
    public FrmEmployees(List<Company> companies, List<Citizenship> citizenships)
    {
        companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
        cbCompany.DataSource = companies;
        cbCompany.DisplayMember = "Name";
        cbCompany.ValueMember = "ID";

        citizenships.Insert(0, "--Select--");
        cbCitizenship.DataSource = _citizenships;
        cbCitizenship.DisplayMember = "Citizenship";

        // etc.
    }
}

One important thing: you can get many tasks and many data passed to a form constructor. If all this data is going to be used often togetther, then you would probably want to encapsulate this "get all these things" logic into a single place to remove possible code duplication.


问:
postfix (prefix) increment, L-value and R-value (in C and C++)
I just learned the following facts:

The result of a prefix increment (++var_name) is an R-value in C (at least, I am
    sure that it is not a L-value in C), but it is an L-value in C++.

The result of a postfix increment (var_name++) is an R-value in C (at least, I am
    sure that it is not a L-value in C). This is also true in C++ (It says the result
    is a prvalue).

I checked these in VS2010 (.cpp and .c) and Ubuntu (gcc and g++).

In p.109 (5.3.2) of C++ Standard http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf, it is written

The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The
  operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to
  a completely-defined object type. The result is the updated operand; it is an lvalue, and...

and in p.101, (5.2.6)

The value of a postfix ++ expression is the value of its operand. ... The result is a
  prvalue. The type of the result is the cv-unqualified version of the type of the operand. See also 5.7 and 5.17.

(I don't know the difference between R-value and prvalue though).

As to C standard http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf,
prefix ++ is described in 6.5.3.1 and postfix is in 6.5.2.4, but from the description, I can't get a clear, definite answer.

I would like to know the reasons that make them being R-value or L-value. All I know is that

We can assign a value to a (modifiable) L-value, for example, a variable name. R-value is a value of an expression.

But I don't know the details why postfix ++ is not a L-value in C and C++, and why prefix ++ is not in C. (I saw something like "postfix ++...store...in a temporary address, then...", but I still don't get it).

And another question is that why prefix ++ is different in C and C++? Making prefix ++ a L-value (in C++) has many advantages? If so, why C doesn't change this? (Other reasons than backward compatibility, or at least why changing it will cause a lot of problems).

答:
It is true that

pre increment/decrement operator (++var or --var) yields an lvalue (i.e a modifiable object)

post increment/decrement operator (var++ or var--) yields an rvalue (i.e a temporary object).

Consider following code with pre increment/decrement operator

```<code>{

int i = 0;

int* pi = &(++i);

}
</code>```

It´s OK because in fact its pseudo code is

```<code>i = i+1; // pre increment i

int* pi = &i; // then evaluate its address and assign it to pi
</code>```

Now consider the same code but with post increment/decrement operator and the consequences if this invalid code is accepted by the compiler

```<code>{

int i = 0;

int* pi = &(i++); // Not OK !! because it is a temporary variable

}
</code>```

Its pseudo code would be

```<code>int i = 0;

int tmp = i; // compiler creates a temporary variable to save value of i

int* pi = &tmp; // then would take the address of a temporary variable

i = i + 1;
</code>```

Body:
It is true that

pre increment/decrement operator (++var or --var) yields an lvalue (i.e a modifiable object)

post increment/decrement operator (var++ or var--) yields an rvalue (i.e a temporary object).

Consider following code with pre increment/decrement operator

{

int i = 0;

int* pi = &(++i);

}

It´s OK because in fact its pseudo code is

i = i+1; // pre increment i

int* pi = &i; // then evaluate its address and assign it to pi

Now consider the same code but with post increment/decrement operator and the consequences if this invalid code is accepted by the compiler

{

int i = 0;

int* pi = &(i++); // Not OK !! because it is a temporary variable

}

Its pseudo code would be

int i = 0;

int tmp = i; // compiler creates a temporary variable to save value of i

int* pi = &tmp; // then would take the address of a temporary variable

i = i + 1;


问:
Selenium returns unknownProtocolFound error
I'm trying to download an APK file from [this GooglePlay direct link generator][1] using Firefox Webdriver, Selenium and Python.

The problem is that, when Selenium is trying to get the home page, it crashes with the following error message:

```<code>/usr/bin/python2.7 /home/ghasemi/PycharmProjects/phorcys_watcher/main.py
http://apps.evozi.com/apk-downloader/?id=com.instagram.android
Traceback (most recent call last):
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/main.py", line 7, in <module>
    content = google_play_download("com.instagram.android")
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/collector.py", line 20, in google_play_download
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 268, in get
    self.execute(Command.GET, {'url': url})
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=unknownProtocolFound&u=httpss%3A//www.adnetworkperformance.com/script/java.php%3Foption%3Drotateur%26r%3D411313%26treqn%3D1025813717%26runauction%3D1%26crr%3D168ce9d76b1a6695b12e%2CwcwHrNzGnshFns2PnM3bbcwGW8xLz-mNycwuvZjurZja3MzJfMxG_9xMX4wYns7a2YxHvshBL9xe3shbjN2J7umN6umNm-mNuN2czNw723956800778f24b2db6%26rtid%3D595b6ecb8ac19%26cbrandom%3D0.7519066097934798%26cbtitle%3DAPK%2520Downloader%2520%255BLatest%255D%2520Download%2520Directly%2520%257C%2520Chrome%2520Extension%2520v3%2520%28Evozi%2520Official%29%26cbiframe%3D0%26cbWidth%3D1280%26cbHeight%3D717%26cbdescription%3DDownload%2520APKs%2520Directly%2520From%2520Google%2520Play%2520To%2520Your%2520Computer%2520With%2520APK%2520Downloader%2520Extension%2520For%2520Google%2520Chrome%26cbkeywords%3D%26cbref%3D&c=&f=regular&d=Firefox%20doesn%E2%80%99t%20know%20how%20to%20open%20this%20address%2C%20because%20one%20of%20the%20following%20protocols%20%28httpss%29%20isn%E2%80%99t%20associated%20with%20any%20program%20or%20is%20not%20allowed%20in%20this%20context.
</code>```

The exception throws on this line:
    browser.get("https://apps.evozi.com/apk-downloader/?id=com.instagram.android")

As you see above, the origin of this error is a wrong link in the page that selenium is trying to download it. I found the frame that cause this error:

```<code><iframe width="468" height="60" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" allowfullscreen="true" style="border: medium none; padding: 0; margin: 0;" sandbox="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-pointer-lock allow-same-origin" id="595b6e88086f8" frameborder="0" src="httpss://www.adnetworkperformance.com/script/java.php?option=rotateur&r=411313&treqn=501505383&runauction=1&crr=fc25086f39dc3c58bbdbGJTJyVGZh9Gbud3bk1yawFmRyUSbvNmLpp3b2VmLzBHchZkMlYkMlE0MlMHc0RHa2dfe473f7c304fd8fb65&rtid=595b6e88086f8&cbrandom=0.6676681852413189&cbtitle=APK%20Downloader%20%5BLatest%5D%20Download%20Directly%20%7C%20Chrome%20Extension%20v3%20(Evozi%20Official)&cbiframe=0&cbWidth=1522&cbHeight=741&cbdescription=Download%20APKs%20Directly%20From%20Google%20Play%20To%20Your%20Computer%20With%20APK%20Downloader%20Extension%20For%20Google%20Chrome&cbkeywords=&cbref=" scrolling="no"></iframe>
</code>```

As you can see, the webpage developer put httpss instead of https wrongly (twice!).

How can I handle this problem?

Update:

My scraper:

```<code>import requests
from lxml import html
from pyvirtualdisplay import Display
from selenium import webdriver

def google_play_download(app_page_id):
    browser = webdriver.Firefox()
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
    browser.find_element_by_css_selector(".btn.btn-primary.btn-lg.btn-block").click()
    apk_link = browser.find_element_by_css_selector(".btn.btn-success.btn-block").get_attribute('href')
    browser.quit()
    for rnd in range(5):
        resp = requests.get(apk_link)
        if resp.headers['Content-Length'] == str(len(resp.content)):
            return resp.content

if __name__ == "__main__":
    content = google_play_download("com.instagram.android")
    f = open('./file', 'wb')
    f.write(content)
    f.close()

  [1]: https://apps.evozi.com/apk-downloader/
</code>```

答:
One solution would be a url-parsing funktion, that you call on each url before driver.get(url)

```<code>def url_parser(url):
    if 'httpss' in url:
        url = url.replace('httpss','https')
    return url
</code>```

You'd then use it like so

```<code>url = url_parser(url)
driver.get(url)
</code>```

Body:
I'm trying to download an APK file from [this GooglePlay direct link generator][1] using Firefox Webdriver, Selenium and Python.

The problem is that, when Selenium is trying to get the home page, it crashes with the following error message:

/usr/bin/python2.7 /home/ghasemi/PycharmProjects/phorcys_watcher/main.py
http://apps.evozi.com/apk-downloader/?id=com.instagram.android
Traceback (most recent call last):
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/main.py", line 7, in <module>
    content = google_play_download("com.instagram.android")
  File "/home/ghasemi/PycharmProjects/phorcys_watcher/collector.py", line 20, in google_play_download
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 268, in get
    self.execute(Command.GET, {'url': url})
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=unknownProtocolFound&u=httpss%3A//www.adnetworkperformance.com/script/java.php%3Foption%3Drotateur%26r%3D411313%26treqn%3D1025813717%26runauction%3D1%26crr%3D168ce9d76b1a6695b12e%2CwcwHrNzGnshFns2PnM3bbcwGW8xLz-mNycwuvZjurZja3MzJfMxG_9xMX4wYns7a2YxHvshBL9xe3shbjN2J7umN6umNm-mNuN2czNw723956800778f24b2db6%26rtid%3D595b6ecb8ac19%26cbrandom%3D0.7519066097934798%26cbtitle%3DAPK%2520Downloader%2520%255BLatest%255D%2520Download%2520Directly%2520%257C%2520Chrome%2520Extension%2520v3%2520%28Evozi%2520Official%29%26cbiframe%3D0%26cbWidth%3D1280%26cbHeight%3D717%26cbdescription%3DDownload%2520APKs%2520Directly%2520From%2520Google%2520Play%2520To%2520Your%2520Computer%2520With%2520APK%2520Downloader%2520Extension%2520For%2520Google%2520Chrome%26cbkeywords%3D%26cbref%3D&c=&f=regular&d=Firefox%20doesn%E2%80%99t%20know%20how%20to%20open%20this%20address%2C%20because%20one%20of%20the%20following%20protocols%20%28httpss%29%20isn%E2%80%99t%20associated%20with%20any%20program%20or%20is%20not%20allowed%20in%20this%20context.

The exception throws on this line:
    browser.get("https://apps.evozi.com/apk-downloader/?id=com.instagram.android")

As you see above, the origin of this error is a wrong link in the page that selenium is trying to download it. I found the frame that cause this error:

<iframe width="468" height="60" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" allowfullscreen="true" style="border: medium none; padding: 0; margin: 0;" sandbox="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-pointer-lock allow-same-origin" id="595b6e88086f8" frameborder="0" src="httpss://www.adnetworkperformance.com/script/java.php?option=rotateur&r=411313&treqn=501505383&runauction=1&crr=fc25086f39dc3c58bbdbGJTJyVGZh9Gbud3bk1yawFmRyUSbvNmLpp3b2VmLzBHchZkMlYkMlE0MlMHc0RHa2dfe473f7c304fd8fb65&rtid=595b6e88086f8&cbrandom=0.6676681852413189&cbtitle=APK%20Downloader%20%5BLatest%5D%20Download%20Directly%20%7C%20Chrome%20Extension%20v3%20(Evozi%20Official)&cbiframe=0&cbWidth=1522&cbHeight=741&cbdescription=Download%20APKs%20Directly%20From%20Google%20Play%20To%20Your%20Computer%20With%20APK%20Downloader%20Extension%20For%20Google%20Chrome&cbkeywords=&cbref=" scrolling="no">

As you can see, the webpage developer put httpss instead of https wrongly (twice!).

How can I handle this problem?

Update:

My scraper:

import requests
from lxml import html
from pyvirtualdisplay import Display
from selenium import webdriver

def google_play_download(app_page_id):
    browser = webdriver.Firefox()
    browser.get("https://apps.evozi.com/apk-downloader/?id=" + app_page_id)
    browser.find_element_by_css_selector(".btn.btn-primary.btn-lg.btn-block").click()
    apk_link = browser.find_element_by_css_selector(".btn.btn-success.btn-block").get_attribute('href')
    browser.quit()
    for rnd in range(5):
        resp = requests.get(apk_link)
        if resp.headers['Content-Length'] == str(len(resp.content)):
            return resp.content

if __name__ == "__main__":
    content = google_play_download("com.instagram.android")
    f = open('./file', 'wb')
    f.write(content)
    f.close()

  [1]: https://apps.evozi.com/apk-downloader/

Body:
One solution would be a url-parsing funktion, that you call on each url before driver.get(url)

def url_parser(url):
    if 'httpss' in url:
        url = url.replace('httpss','https')
    return url

You'd then use it like so

url = url_parser(url)
driver.get(url)


问:
Can I have captcha in google apps script?
I'm deploying an aplicattion in Google Apps Script, and I need the implementation of a captcha on it, how can I include captcha in Google App Script?</p>

答:
Yes, you can.
Here is a tutorial I posted today on my website.

reCAPCHA with Google Apps Script

The tricky thing is the domain name when you register for a Website to use reCAPTCHA. Since Apps Script webapps are hosted in an iFrame, you need to use domain of iFrame. If you do an analysis of Apps Script Webapp, you will find that all the apps have an iFrame on a temporary domain like xsdsdfjsdfks.googleusercontent.com. So you need to resgister domain  googleusercontent.com in order to get a site-key and secret-key pair.


问:
nested loops avoiding self and reciprocal comparisons
Since this must be quite a common scenario I'm wondering whether there are any pre-existing solutions to the following.

Lets say I have a set of N strings, and I am computing distances the distances between them. In this case it's a Hamming distance, but that's not really important.

If I wanted to make this as quick as possible, I would avoid self comparisons like so:

```<code> def hamming_distance(string1, string2):
     """Return the Hamming distance between equal-length sequences"""
     if len(string1) != len(string2):
         raise ValueError("Undefined for sequences of unequal length")
     return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

ratios=[]
 for a, i in enumerate(string_list):
     for b, j in enumerate(string_list):
         if a == b: # Avoid self comparisons for speed
             break
     ratios.append(hamming_distance(string_list[i], string_list[j]))
 return ratios
</code>```

But since this is 'symmetric', I could also throw away any reciprocal comparisons which would increase the speed if the strings were numerous and/or large.

Is there a generally accepted/elegant way of doing this in the above set up?

I'm also aware that in general it's advised to avoid nested loops as they can be slow - so if there is a better way of achieving this pairwise iteration over lists (maybe something in collections?) and incorporating the avoidance of self and reciprocal comparisons, I'm all ears.

答:
What you are looking for is implemented by itertools.combinations().

```<code>>>> import itertools
>>> a = [1,2,3]
>>> list(itertools.combinations(a, 2))
[(1, 2), (1, 3), (2, 3)]
</code>```

So in your case it will look like:

```<code>for a, b in itertools.combinations(string_list, 2):
    ratios.append(hamming_distance(a, b))
</code>```

Body:
Since this must be quite a common scenario I'm wondering whether there are any pre-existing solutions to the following.

Lets say I have a set of N strings, and I am computing distances the distances between them. In this case it's a Hamming distance, but that's not really important.

If I wanted to make this as quick as possible, I would avoid self comparisons like so:

 def hamming_distance(string1, string2):
     """Return the Hamming distance between equal-length sequences"""
     if len(string1) != len(string2):
         raise ValueError("Undefined for sequences of unequal length")
     return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

ratios=[]
 for a, i in enumerate(string_list):
     for b, j in enumerate(string_list):
         if a == b: # Avoid self comparisons for speed
             break
     ratios.append(hamming_distance(string_list[i], string_list[j]))
 return ratios

But since this is 'symmetric', I could also throw away any reciprocal comparisons which would increase the speed if the strings were numerous and/or large.

Is there a generally accepted/elegant way of doing this in the above set up?

I'm also aware that in general it's advised to avoid nested loops as they can be slow - so if there is a better way of achieving this pairwise iteration over lists (maybe something in collections?) and incorporating the avoidance of self and reciprocal comparisons, I'm all ears.

Body:
What you are looking for is implemented by itertools.combinations().

>>> import itertools
>>> a = [1,2,3]
>>> list(itertools.combinations(a, 2))
[(1, 2), (1, 3), (2, 3)]

So in your case it will look like:

for a, b in itertools.combinations(string_list, 2):
    ratios.append(hamming_distance(a, b))


问:
Wordpress: Call to undefined function wp_verify_nonce() in custom plugin
I cannot use the wp_verify_nonce method in wordpress plugin.

I get the fatal error: Call to undefined function wp_verify_nonce().

I did try to render public the method private function submit_form() without success

```<code><?php

/*
 * Frontend class.
 *
 * Method and property for frontend section.
 *
 * @since 1.0
 *
 */

namespace Simplestform;

class Frontend extends \Simplestform\Base {

    /**
     * Our constructor.
     *
     *
     */

    public function __construct( $base_dir = null ) {

        parent::__construct();

        if ( !is_null ( $base_dir ) ) {

            /*
             * Call Base function to set the base dir
             */

            $this->set_base_dir($base_dir);

        }

        /*
         *
         * Register shortcode
         *
         */
        $this->add_shortcode();
        $this->submit_form();

    }

    /**
     * Register the shortcode
     *
     * @since 1.0
     */

    private function add_shortcode() {

        add_shortcode( $this->get_shortcode_tag() , array ( $this , 'render_contact_form' ) );

    }

    public function render_contact_form() {

        include_once ( $this->get_base_dir().'/views/frontend/basic-form.php' );

    }

    private function submit_form() {

        if ( isset ( $_POST['_wpnonce'] ) ) {

            $nonce = $_POST['_wpnonce'];

            wp_verify_nonce ( $nonce , 'test_nonce_field' );

            echo '```';
            var_dump ( $_POST );
            echo '```';

        }

    }

}
</code>```

答:
wp_verify_nonce() is a Wordpress core function. Many WP functions are just not accessible at any moment.

Looking a bit into how Wordpress works my guess is that you may have to hook your function into the Wordpress sequence. Try hooking your plugin function into admin_init.

```<code>add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );
</code>```

Some good necesary reading: Wordpress - Plugin API

Body:
I cannot use the wp_verify_nonce method in wordpress plugin.

I get the fatal error: Call to undefined function wp_verify_nonce().

I did try to render public the method private function submit_form() without success

<?php

/*
 * Frontend class.
 *
 * Method and property for frontend section.
 *
 * @since 1.0
 *
 */

namespace Simplestform;

class Frontend extends \Simplestform\Base {

    /**
     * Our constructor.
     *
     *
     */

    public function __construct( $base_dir = null ) {

        parent::__construct();

        if ( !is_null ( $base_dir ) ) {

            /*
             * Call Base function to set the base dir
             */

            $this->set_base_dir($base_dir);

        }

        /*
         *
         * Register shortcode
         *
         */
        $this->add_shortcode();
        $this->submit_form();

    }

    /**
     * Register the shortcode
     *
     * @since 1.0
     */

    private function add_shortcode() {

        add_shortcode( $this->get_shortcode_tag() , array ( $this , 'render_contact_form' ) );

    }

    public function render_contact_form() {

        include_once ( $this->get_base_dir().'/views/frontend/basic-form.php' );

    }

    private function submit_form() {

        if ( isset ( $_POST['_wpnonce'] ) ) {

            $nonce = $_POST['_wpnonce'];

            wp_verify_nonce ( $nonce , 'test_nonce_field' );

            echo '
';
            var_dump ( $_POST );
            echo '
';

        }

    }

}

Body:
wp_verify_nonce() is a Wordpress core function. Many WP functions are just not accessible at any moment.

Looking a bit into how Wordpress works my guess is that you may have to hook your function into the Wordpress sequence. Try hooking your plugin function into admin_init.

add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );

Some good necesary reading: Wordpress - Plugin API


问:
Why isn't Python fexlibe when it comes data-types of function arguments?
This is probably a bad title but what I mean by it is the following:

Since Python is dynamically-typed, why do certain functions insist on being used with certain data types only and do not handle the conversion themselves internally if necessary? What problems could that lead to?

Examples:

startswith(): Takes both strings and tuples as arguments.

Why not lists
too? And if there is a good reason for that (which is probably the
case), why does it not simply convert them internally?

join(): Only accepts containers of string items.

Why does it not simply do a [str(x) for x in whatever]?

From the design of the language, I have the impression so far that it values flexibility more than purity and therefore the above behavior seems kind of non-typical..

Another example comes from @VPfB

"IPv4 address (host, port) must be tuple - not a list - in socket library.".

Can it be that tuples are prefered due to their immutability? Is there a case where a tuple is denied and only a list accepted? Preferably part from the standard Python distribution and its modules.

答:
From the design of the language, I have the impression so far that it values flexibility more than purity and therefore the above behavior seems kind of non-typical.

Your impression is wrong. Python is dynamically-typed, but also strongly-typed, meaning that the type of an object is always fixed. If you need a different type of object, you have to compare it one way or the other.

The second question is legitimate, though – it would have been possible. But explicit is better than implicit.


问:
flight connections using gremlin
I am newbie to gremlin. I have a graph with airports as nodes and flights as edges with arrival time and departure time as edge properties.  Now I am trying to use tinkerpop 3.1 to get the list of connections with 1 layovers, 2 layovers, 3 layovers given a origin airport, destination airport and departure time . I got it to work for 1 layover using below query.
I am having tough time trying to generalize this query to find n connections using repeat and match. Any help is appreciated.

Sample graph script

```<code>graph = TinkerFactory.createModern()
g = graph.traversal()
g.addV('airport').property('name','PDX').as('PDX').
  addV('airport').property('name','JFK').as('JFK').
  addV('airport').property('name','PHX').as('PHX').
  addV('airport').property('name','ORD').as('ORD').
  addV('airport').property('name','IAD').as('IAD').
  addE('flight').property('depTime',9).property('arrTime',10).from('PDX').to('JFK').
  addE('flight').property('depTime',10).property('arrTime',11).from('PDX').to('PHX').
  addE('flight').property('depTime',12).property('arrTime',13).from('PDX').to('ORD').
  addE('flight').property('depTime',13).property('arrTime',14).from('PDX').to('IAD').
  addE('flight').property('depTime',11).property('arrTime',14).from('JFK').to('IAD').
  addE('flight').property('depTime',10).property('arrTime',12).from('PHX').to('IAD').
  addE('flight').property('depTime',14).property('arrTime',15).from('ORD').to('IAD').iterate()

Gremlin query

g.V().has("airport","name","PDX").outE().has("depTime",gt(6)).
match(
__.as('e1').values('arrTime').as('e1Arr'),
__.as('e1').outV().as('v1'),
__.as('e1').inV().as('v2'),
__.as('v2').outE().as('e2'),
__.as('e2').values('depTime').as('e2Dep')).
where('e2Dep',gt('e1Arr')).select('e2').inV().as("v3").has("airport","name","IAD").
select("v1","e1","v2","e2","v3").by("name").by(valueMap()).by("name").by(valueMap()).by("name");
</code>```

答:
I don't have a graph to test it, but this query should do the trick:

```<code>g.V().has("airport","name","PDX").outE().has("depTime", gt("09:30")).as("e").inV().
 emit().
   repeat(outE().filter(project("a","b").by("depTime").by(select(last, "e").by("arrTime")).
            where("a", gt("b"))).as("e").inV()).times(2).
 has("name", "IAD").path().by("name").by(valueMap())
</code>```

If the dataset is relatively static, I would suggest to create shortcuts, e.g. pre-compute route vertices, that have a connection to all stops. For example:

```<code>g.V().has("airport","name","PDX").as("a0").
  V().has("airport","name","JFK").as("a1").
  V().has("airport","name","IAD").as("a2").
  addV("route").property("from", "PDX").
                property("to", "IAD").
                property("stops", 2).
                property("depTime", 9).
                property("arrTime", 14).as("r").
  addE("stop").from("r").to("a0").property("n", 0).
  addE("stop").from("r").to("a1").property("n", 1).
  addE("stop").from("r").to("a2").property("n", 2).iterate()
</code>```

These route vertices will allow you to find routes of any length very quickly. The result of the first query can be used to create the route vertices; however, since it's timing out, you'll either have to increase timeouts + memory or run it as an OLAP query. The latter is preferred, but requires a few tweaks in the query:

```<code>gremlin> g.V().has("airport","name","PDX").outE("flight").has("depTime", gt(9)).as("e").
           values("depTime").as("d").select("e").inV().
           emit().
             repeat(outE("flight").filter(project("a","b").by("depTime").by(select(last, "d")).
                      where("a", gt("b"))).as("e").
                      values("depTime").as("d").select(last, "e").inV()).times(2).
           has("name", "IAD").path()
==>[v[0],e[13][0-flight->8],13,e[13][0-flight->8],v[8]]
==>[v[0],e[12][0-flight->6],12,e[12][0-flight->6],v[6],e[16][6-flight->8],14,e[16][6-flight->8],v[8]]
</code>```

Title: flight connections using gremlin

Body:
I am newbie to gremlin. I have a graph with airports as nodes and flights as edges with arrival time and departure time as edge properties.  Now I am trying to use tinkerpop 3.1 to get the list of connections with 1 layovers, 2 layovers, 3 layovers given a origin airport, destination airport and departure time . I got it to work for 1 layover using below query.
I am having tough time trying to generalize this query to find n connections using repeat and match. Any help is appreciated.

Sample graph script

graph = TinkerFactory.createModern()
g = graph.traversal()
g.addV('airport').property('name','PDX').as('PDX').
  addV('airport').property('name','JFK').as('JFK').
  addV('airport').property('name','PHX').as('PHX').
  addV('airport').property('name','ORD').as('ORD').
  addV('airport').property('name','IAD').as('IAD').
  addE('flight').property('depTime',9).property('arrTime',10).from('PDX').to('JFK').
  addE('flight').property('depTime',10).property('arrTime',11).from('PDX').to('PHX').
  addE('flight').property('depTime',12).property('arrTime',13).from('PDX').to('ORD').
  addE('flight').property('depTime',13).property('arrTime',14).from('PDX').to('IAD').
  addE('flight').property('depTime',11).property('arrTime',14).from('JFK').to('IAD').
  addE('flight').property('depTime',10).property('arrTime',12).from('PHX').to('IAD').
  addE('flight').property('depTime',14).property('arrTime',15).from('ORD').to('IAD').iterate()

Gremlin query

g.V().has("airport","name","PDX").outE().has("depTime",gt(6)).
match(
__.as('e1').values('arrTime').as('e1Arr'),
__.as('e1').outV().as('v1'),
__.as('e1').inV().as('v2'),
__.as('v2').outE().as('e2'),
__.as('e2').values('depTime').as('e2Dep')).
where('e2Dep',gt('e1Arr')).select('e2').inV().as("v3").has("airport","name","IAD").
select("v1","e1","v2","e2","v3").by("name").by(valueMap()).by("name").by(valueMap()).by("name");

Body:
I don't have a graph to test it, but this query should do the trick:

g.V().has("airport","name","PDX").outE().has("depTime", gt("09:30")).as("e").inV().
 emit().
   repeat(outE().filter(project("a","b").by("depTime").by(select(last, "e").by("arrTime")).
            where("a", gt("b"))).as("e").inV()).times(2).
 has("name", "IAD").path().by("name").by(valueMap())

If the dataset is relatively static, I would suggest to create shortcuts, e.g. pre-compute route vertices, that have a connection to all stops. For example:

g.V().has("airport","name","PDX").as("a0").
  V().has("airport","name","JFK").as("a1").
  V().has("airport","name","IAD").as("a2").
  addV("route").property("from", "PDX").
                property("to", "IAD").
                property("stops", 2).
                property("depTime", 9).
                property("arrTime", 14).as("r").
  addE("stop").from("r").to("a0").property("n", 0).
  addE("stop").from("r").to("a1").property("n", 1).
  addE("stop").from("r").to("a2").property("n", 2).iterate()

These route vertices will allow you to find routes of any length very quickly. The result of the first query can be used to create the route vertices; however, since it's timing out, you'll either have to increase timeouts + memory or run it as an OLAP query. The latter is preferred, but requires a few tweaks in the query:

gremlin> g.V().has("airport","name","PDX").outE("flight").has("depTime", gt(9)).as("e").
           values("depTime").as("d").select("e").inV().
           emit().
             repeat(outE("flight").filter(project("a","b").by("depTime").by(select(last, "d")).
                      where("a", gt("b"))).as("e").
                      values("depTime").as("d").select(last, "e").inV()).times(2).
           has("name", "IAD").path()
==>[v[0],e[13][0-flight->8],13,e[13][0-flight->8],v[8]]
==>[v[0],e[12][0-flight->6],12,e[12][0-flight->6],v[6],e[16][6-flight->8],14,e[16][6-flight->8],v[8]]


问:
Does RabbitMq do round-robin from the exchange to the queues
I am currently evaluating message queue systems and RabbitMq seems like a good candidate, so I'm digging a little more into it.

To give a little context I'm looking to have something like one exchange load balancing the message publishing to multiple queues. I don't want to replicate the messages, so a fanout exchange is not an option.

Also the reason I'm thinking of having multiple queues vs one queue handling the round-robin w/ the consumers, is that I don't want our single point of failure to be at the queue level.

Sounds like I could add some logic on the publisher side to simulate that behavior by editing the routing key and having the appropriate bindings in place. But that's kind of a passive approach that wouldn't take the pace of the message consumption on each queue into account, potentially leading to fill up one queue if the consumer applications for that queue are dead.

I was looking for a more pro-active way from the exchange entity side, that would decide where to send the next message based on each queue size or something of that nature.

I read about Alice and the available RESTful APIs but that seems kind of a heavy duty solution to implement fast routing decisions.

Anyone knows if round-robin between the exchange the queues is feasible w/ RabbitMQ then? Thanks.

答:
One built in way you can do a form of sharing a form exchange to queues, but not exactly round robin, is Consistent Hashing. rabbitmq_consistent_hash_exchange

How too
https://medium.com/@eranda/rabbitmq-x-consistent-hashing-with-wso2-esb-27479b8d1d21

Paper to explain, it puts queues at a weighted distribution on a circle and then by sending random routing key it will send to the closest queue.
http://www8.org/w8-papers/2a-webserver/caching/paper2.html