问:
UIWebView is not shown
WebView in Mainstoryboard is not shown anything. I wanna show yahoo page in my app.When I run my app in an emulator(that is not my real iPhone), it is like only　black screen.

Any error does not happen in that time, but
warning

In this part, I got a warning

"signal SIGABRT"

My code is like

```<code>import Foundation
import Alamofire
import UIKit

class webViewController: UIViewController {

    @IBOutlet var webBrowser: UIWebView! = nil

    var targetURL = "https://www.yahoo.co.jp"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //loadAddressURL()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL)
        let req = NSURLRequest(url: requestURL as! URL)
        webBrowser.loadRequest(req as URLRequest)
    }

}
</code>```

I think a connection of WebView & WebViewController is ok. I tried to do Add Exception Breakpoint,and find a point of this error.
The result is
result

My app dropped in

"Thread1:breakpoint4.1".

What is wrong with my app?

答:
```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var webBrowser: UIWebView!
    var targetURL = "https://www.yahoo.co.jp"
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.loadAddressURL()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL)
        let req = NSURLRequest(url: requestURL! as URL)
        webBrowser.loadRequest(req as URLRequest)
    }
}
</code>```

Use this.

Title: UIWebView is not shown

Body:
WebView in Mainstoryboard is not shown anything. I wanna show yahoo page in my app.When I run my app in an emulator(that is not my real iPhone), it is like only　black screen.

Any error does not happen in that time, but
warning

In this part, I got a warning

"signal SIGABRT"

My code is like

import Foundation
import Alamofire
import UIKit

class webViewController: UIViewController {

    @IBOutlet var webBrowser: UIWebView! = nil

    var targetURL = "https://www.yahoo.co.jp"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //loadAddressURL()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL)
        let req = NSURLRequest(url: requestURL as! URL)
        webBrowser.loadRequest(req as URLRequest)
    }

}

I think a connection of WebView & WebViewController is ok. I tried to do Add Exception Breakpoint,and find a point of this error.
The result is
result

My app dropped in

"Thread1:breakpoint4.1".

What is wrong with my app?

Body:
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var webBrowser: UIWebView!
    var targetURL = "https://www.yahoo.co.jp"
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.loadAddressURL()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL)
        let req = NSURLRequest(url: requestURL! as URL)
        webBrowser.loadRequest(req as URLRequest)
    }
}

Use this.


来源: stackexchange

问:
How to replace string with another string and keep case in php and mysql?
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.

Example:

```<code>Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.
</code>```

I want to replace word 'place' with 'garden'.

```<code>Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.
</code>```

It should also work with phrases.

答:
```<code>Use "stripos" php function

$str = 'Potato is jumping all over the pLAcEs.';
$str_new = "garden";

$str1 = str_split($str_new);
$pos    = stripos($str,'places');
$string = substr($str,$pos,6);

 $extrct = str_split($string);

$var = '';

foreach ($extrct as $key => $value) {
    if(ctype_upper($value))
    {
        $var .= strtoupper($str1[$key]);
    }else{
        $var .= strtolower($str1[$key]);
    }
}

$new_string = str_replace($string, $var, $str);

echo $new_string; //Potato is jumping all over the gARdEn.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.

Example:

Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.

I want to replace word 'place' with 'garden'.

Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.

It should also work with phrases.


问:
Location.subscribe() is leaking
I use Location.subscribe() to detect "back" button.
https://angular.io/docs/ts/latest/api/common/index/Location-class.html

```<code>export class PathLocationComponent {
  location: Location;
  constructor(location: Location) {
     location.subscribe(val => console.log(val))//output popstate
  }
}
</code>```

However, The number of logs increases when I repeat pushing "back"&"forward" button.
I think Locaion.subscribe() is leaking.
but I don't know how to release it because Location class doesn't have unsubscribe().

How to release Location.subscribe() or prevent leak?

I thought of using PlatformLocation.onPopState().
https://angular.io/docs/ts/latest/api/common/index/PlatformLocation-class.html

But,documentation says below

```<code>This class should not be used directly by an application developer. Instead, use Location.
</code>```

答:
You can try this:

```<code>import {Subscription} from 'rxjs/Subscription';

export class PathLocationComponent implements OnDestroy {
location: Location;
private subscription: Subscription;

      constructor(location: Location) {
        this.subscription = location.subscribe(val => console.log(val))//output popstate
      }

     ngOnDestroy(): void {
        this.subscription.unsubscribe();
     }
}
</code>```

Title: Location.subscribe() is leaking

Body:
I use Location.subscribe() to detect "back" button.
https://angular.io/docs/ts/latest/api/common/index/Location-class.html

export class PathLocationComponent {
  location: Location;
  constructor(location: Location) {
     location.subscribe(val => console.log(val))//output popstate
  }
}

However, The number of logs increases when I repeat pushing "back"&"forward" button.
I think Locaion.subscribe() is leaking.
but I don't know how to release it because Location class doesn't have unsubscribe().

How to release Location.subscribe() or prevent leak?

I thought of using PlatformLocation.onPopState().
https://angular.io/docs/ts/latest/api/common/index/PlatformLocation-class.html

But,documentation says below

This class should not be used directly by an application developer. Instead, use Location.

Body:
You can try this:

import {Subscription} from 'rxjs/Subscription';

export class PathLocationComponent implements OnDestroy {
location: Location;
private subscription: Subscription;

      constructor(location: Location) {
        this.subscription = location.subscribe(val => console.log(val))//output popstate
      }

     ngOnDestroy(): void {
        this.subscription.unsubscribe();
     }
}


问:
Refresh one-to-many relationship after child was added
So I have two entities:

Person.java

```<code>@Entity
@Table(name = "persons")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @OneToMany(mappedBy="person", cascade = CascadeType.REMOVE)
    @JsonIgnoreProperties("person")
    private Set<Address> addresses;

    //getters and setters

}
</code>```

Address.java

```<code>@Entity
@Table(name = "addresses")
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotNull
    @ManyToOne
    @JoinColumn(name = "person_id", nullable = false)
    @JsonIgnoreProperties("addresses")
    private Person person;
    //getters and setters
}
</code>```

And later on in my code I have a personDb object (already saved in database) and then I add Address:

```<code>Address address = new Address();
address.setPerson(personDb);
address = addressRepository.save(address);
</code>```

and now I have address object with person object attached to it but my personDb still doesn't have any addresses attached to it. Even if I try to get it from database once more:

personRepository.findOne(personDb.getId());

I have null where should be set of addresses. I also tried changing my annotation in Person class to something like this:

```<code>@OneToMany(mappedBy="person", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
</code>```

or changing CascadeType to ALL but nothing helps. What can I do to load addresses to my personDb object after they were added to database?

答:
Make sure the person is persisted.

For that make an integration test for it. If you are using Spring, I also suggest you use in-memory db for your tests.

```<code>@Transactional
@Test
public void testFindOneAddress(){

// persist the person
Person person = new Person();
...
personRepository.save(person);

// persist the address
Address address = new Address();
address.setPerson(person);
addressRepository.save(address);

// find the persisted person and addresses
Person queryResult= personRepository.findOne(person.getId());
assertNotNull(queryResult);
assertNotNull(queryResult.getAddresses());
assertEquals(1, queryResult.getAddresses().size());
assertEquals(address.getId(), queryResult.getAddresses().get(0).getId());

}
</code>```

Also make sure you person id column is called "person_id"

```<code>public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "person_id")
    private Integer id;
</code>```

take it from there

Body:
So I have two entities:

Person.java

@Entity
@Table(name = "persons")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @OneToMany(mappedBy="person", cascade = CascadeType.REMOVE)
    @JsonIgnoreProperties("person")
    private Set<Address> addresses;

    //getters and setters

}

Address.java

@Entity
@Table(name = "addresses")
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotNull
    @ManyToOne
    @JoinColumn(name = "person_id", nullable = false)
    @JsonIgnoreProperties("addresses")
    private Person person;
    //getters and setters
}

And later on in my code I have a personDb object (already saved in database) and then I add Address:

Address address = new Address();
address.setPerson(personDb);
address = addressRepository.save(address);

and now I have address object with person object attached to it but my personDb still doesn't have any addresses attached to it. Even if I try to get it from database once more:

personRepository.findOne(personDb.getId());

I have null where should be set of addresses. I also tried changing my annotation in Person class to something like this:

@OneToMany(mappedBy="person", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)

or changing CascadeType to ALL but nothing helps. What can I do to load addresses to my personDb object after they were added to database?

Body:
Make sure the person is persisted.

For that make an integration test for it. If you are using Spring, I also suggest you use in-memory db for your tests.

@Transactional
@Test
public void testFindOneAddress(){

// persist the person
Person person = new Person();
...
personRepository.save(person);

// persist the address
Address address = new Address();
address.setPerson(person);
addressRepository.save(address);

// find the persisted person and addresses
Person queryResult= personRepository.findOne(person.getId());
assertNotNull(queryResult);
assertNotNull(queryResult.getAddresses());
assertEquals(1, queryResult.getAddresses().size());
assertEquals(address.getId(), queryResult.getAddresses().get(0).getId());

}

Also make sure you person id column is called "person_id"

public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "person_id")
    private Integer id;

take it from there


问:
Cannot find entry file index.ios.js in any of the roots
my react-native version:0.24.0

index.ios.js:

```<code>require('./entry');
</code>```

entry.js:

```<code>AppRegistry.registerComponent('movieView', () => require('./pages/movie'));
</code>```

all of my business documents in the pages directory. when i run the project,error appear like this:

答:
On the assumption of path of your project, I guess you have initialized the project with AwesomeProject name, haven't you? Then why do you register component by movieView name? Replace it by AwesomeProject string. Or change in your ios project AppDelegate.m file.
There must be such command

```<code>RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"AwesomeProject"
                                             initialProperties:nil
                                             launchOptions:launchOptions];
</code>```

Replace moduleName:@"AwesomeProject" by moduleName:@"movieView".

And don't forget to relaunch dev server.

P.S. It seems like the question isn't actual anymore, hah?

Body:
my react-native version:0.24.0

index.ios.js:

require('./entry');

entry.js:

AppRegistry.registerComponent('movieView', () => require('./pages/movie'));

all of my business documents in the pages directory. when i run the project,error appear like this:

Body:
On the assumption of path of your project, I guess you have initialized the project with AwesomeProject name, haven't you? Then why do you register component by movieView name? Replace it by AwesomeProject string. Or change in your ios project AppDelegate.m file.
There must be such command

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"AwesomeProject"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

Replace moduleName:@"AwesomeProject" by moduleName:@"movieView".

And don't forget to relaunch dev server.

P.S. It seems like the question isn't actual anymore, hah?


问:
uib-progressbar text as center align
Is there a way we can centre aligned text of uib-progressbar. I have tried doing position:absolute. But I wanted to show list of progress bar in a UI grid viz. is a scrollable content. While scrolling text remain at its place but progress bar get scroll properly.

Template

```<code><uib-progressbar animate="false" value="30">
    <span class="content">30% (3/10)</span>
</uib-progressbar>
</code>```

Style

```<code>.progress-bar .content {
   white-space: nowrap;
   position: absolute;
   left: 23vh; /* will vary according to alignment */
}
</code>```

答:
Can you provide your css class 'content' here?

However, assuming that you wanted the text "30% (3/10)" to be centered on progress-bar irrespective of the value.

Add css class to your progress-bar like below:

```<code>.progress {
       position: relative;
    }

.progress span {
    position: absolute;
    display: block;
    width: 100%;
    color: black;
 }
</code>```

and your code should be like this:

```<code><uib-progressbar animate="false" value="30" class="progress">
    <span class="content">30% (3/10)</span>
</uib-progressbar>
</code>```

I have created a JSBin for same.
This should work.

Title: uib-progressbar text as center align

Body:
Is there a way we can centre aligned text of uib-progressbar. I have tried doing position:absolute. But I wanted to show list of progress bar in a UI grid viz. is a scrollable content. While scrolling text remain at its place but progress bar get scroll properly.

Template

<uib-progressbar animate="false" value="30">
    30% (3/10)
</uib-progressbar>

Style

.progress-bar .content {
   white-space: nowrap;
   position: absolute;
   left: 23vh; /* will vary according to alignment */
}

Body:
Can you provide your css class 'content' here?

However, assuming that you wanted the text "30% (3/10)" to be centered on progress-bar irrespective of the value.

Add css class to your progress-bar like below:

.progress {
       position: relative;
    }

.progress span {
    position: absolute;
    display: block;
    width: 100%;
    color: black;
 }

and your code should be like this:

<uib-progressbar animate="false" value="30" class="progress">
    <span class="content">30% (3/10)</span>
</uib-progressbar>

I have created a JSBin for same.
This should work.


问:
maximum number of parameters are used in particular procedure in pl sql oracle
How many maximum number of parameters are passed to pl/sql procedure. This is my last interview question. I searched lot of sites but all are different answers.</p>

答:
" I searched lot of sites but all are different answers."

The first place to look for such things is the Oracle documentation. PL/SQL Limits are in Appendix C of the PL/SQL Language Reference.

Where we find that

number of formal parameters in an explicit cursor, function, or procedure: 65536

That is, approximately 65500 more parameters than any sensible design would have.


问:
Augmenting a Rails Model with virtual attributes on runtime
I have a Rails Model with attributes X,Y,Z

I want to dynamically add attributes P,Q to this model during the data fetch. The attributes P,Q do not need any persistence and is only for front-end manipulation.

Is this possible at all? I could achieve this by storing P,Q in another object and manipulating that along with the original model but thought of asking here what could be best way.

[rails 2.3.5, ruby 1.8,7]

答:
Try something like this in your model

```<code>def p
  @p || @p = fetch_p
end
</code>```

This will allow you to call your_model.p. On the first call, it will call the fetch_p function and store it as a class attribute. On any subsequent call, it will simply returned the cached value.

ContentLicense: CC BY-SA 2.5

Body:
Try something like this in your model

def p
  @p || @p = fetch_p
end

This will allow you to call your_model.p. On the first call, it will call the fetch_p function and store it as a class attribute. On any subsequent call, it will simply returned the cached value.


问:
Default imports groovy

groovy defualt imports

Is it possible to have our own package in default imports? Is there any way to tell the groovy runtime to use my own package as default import?

答:
Since Groovy 1.8 there is an easier way with ImportCustomizer:

```<code>def importCustomizer = new ImportCustomizer()
importCustomizer.addImports('com.looneytunes.Coyote', 'com.looneytunes.RoadRunner')
importCustomizer.addStarImports('com.acme')
importCustomizer.addStaticStars('com.looneytunes.Physics')
def configuration = new CompilerConfiguration()
configuration.addCompilationCustomizers(importCustomizer)
def shell = new GroovyShell(configuration)
shell.evaluate """
    new Coyote().startPlanToCatch(new RoadRunner())  // no need for explicit imports
        .useContraption(new PortableHole())          // from com.acme
        .withPhysicsViolation({ forgetGravity(it) }) // method from com.looneytunes.Physics
        .start()
"""
</code>```

Title: Default imports groovy

Body:
Since Groovy 1.8 there is an easier way with ImportCustomizer:

def importCustomizer = new ImportCustomizer()
importCustomizer.addImports('com.looneytunes.Coyote', 'com.looneytunes.RoadRunner')
importCustomizer.addStarImports('com.acme')
importCustomizer.addStaticStars('com.looneytunes.Physics')
def configuration = new CompilerConfiguration()
configuration.addCompilationCustomizers(importCustomizer)
def shell = new GroovyShell(configuration)
shell.evaluate """
    new Coyote().startPlanToCatch(new RoadRunner())  // no need for explicit imports
        .useContraption(new PortableHole())          // from com.acme
        .withPhysicsViolation({ forgetGravity(it) }) // method from com.looneytunes.Physics
        .start()
"""


问:
Android Studio use native executable and ship them inside the apk
I'm trying to use some executables inside my app. This executable is C++ based (with images and logs as output), there may be other ways to use C++ code, but in this specific context, it might be the best to use it as an executable which only needs arguments. (NDK f.e. will be too much changing of the used library and I'm hoping there may be a way to parallelize this process some days)

My research showed that some other people were looking for similar problems. It seems that the best way was to add these external programs inside the assets folder (app/src/main/assets). That is what I did, but now I'm not quite sure how to get my data inside the assets folder. Some posting said that these files have to be extracted in another folder to get them work.

So I tried this method:
How to copy files from 'assets' folder to sdcard? (result: app shutdown)

I would like to add some code, but there isn't much for now. As I already told my executable should be inside assets and its name is f.e. exec, I also named it libexec.so, because I read somewhere that you have to name these files like lib"...".so to get them extracted. In general, my aim is to use this executable like:
data/exec

Now to my questions:

How can I get access my assets files?

Or should I use another folder instead of assets, will it be easier to use? How could I add an external executable there?

答:
After some time I managed to get it work through:
https://github.com/flipagram/android-assetcopier

I just had to change something:
Example was:
File destDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

I've changed it to: File destDir = (MainActivity.this).getFilesDir(); - so there is no problem with permissions (I guess).

But be aware: Copying is successful, but I did not manage to run the program successfully. Maybe the whole process will get killed through a security manager or something else won't work.


问:
How do I shuffle an array in Swift?
.shuffle() and .shuffled() are part of Swift

Original historic question:

How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in order to shuffle the deck.

答:
This is a version of Nate's implementation of the Fisher-Yates shuffle for Swift 4
(Xcode 9).

```<code>extension MutableCollection {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffle() {
        for i in indices.dropLast() {
            let diff = distance(from: i, to: endIndex)
            let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
            swapAt(i, j)
        }
    }
}

extension Collection {
    /// Return a copy of `self` with its elements shuffled
    func shuffled() -> [Element] {
        var list = Array(self)
        list.shuffle()
        return list
    }
}
</code>```

The changes are:

The constraint Indices.Iterator.Element == Index is now part
of the Collection protocol, and need not be imposed on the
extension anymore.

Exchanging elements must done by calling swapAt() on the collection,
compare SE-0173 Add MutableCollection.swapAt(_:_:).

Element is an alias for Iterator.Element.

ContentLicense: CC BY-SA 4.0

Title: How do I shuffle an array in Swift?

Body:
This is a version of Nate's implementation of the Fisher-Yates shuffle for Swift 4
(Xcode 9).

extension MutableCollection {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffle() {
        for i in indices.dropLast() {
            let diff = distance(from: i, to: endIndex)
            let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
            swapAt(i, j)
        }
    }
}

extension Collection {
    /// Return a copy of `self` with its elements shuffled
    func shuffled() -> [Element] {
        var list = Array(self)
        list.shuffle()
        return list
    }
}

The changes are:

The constraint Indices.Iterator.Element == Index is now part
of the Collection protocol, and need not be imposed on the
extension anymore.

Exchanging elements must done by calling swapAt() on the collection,
compare SE-0173 Add MutableCollection.swapAt(_:_:).

Element is an alias for Iterator.Element.


问:
Is there a JIra query which will return all stories without an EPIC?
I'm trying to tidy up our Jira board and create an accurate story map.

To do that I need to come up with a query that will return open user stories within a certain project that don't have any issue links (preferably 'related to (primary)')- the last part does not seem to be supported.

I've had a look around an post of the Q&As are a few years old, so i'm wondering if it was been updated recently?

I'm using version 5.1

Thanks!

答:
Just to throw another answer into the bowl.

You can use your normal workboard (Scrum, Kanban, etc) and add a swimlane with the JQL:

```<code>"Epic Link" is EMPTY
</code>```

Just did this for our board after looking exactly for this.

Body:
Just to throw another answer into the bowl.

You can use your normal workboard (Scrum, Kanban, etc) and add a swimlane with the JQL:

"Epic Link" is EMPTY

Just did this for our board after looking exactly for this.


问:
how to get max usage of mem and cpu usage of pod on kubernetes
I defined my deployment resources

```<code>    resources:
      limits:
        cpu: 900m
        memory: 2500Mi
</code>```

now on http://localhost:8001/api

how can I get the max usage of memory and cpu (in order to handle and define usages and resources well)?

答:
By default the pods run with unbounded CPU and memory limits. This means that any pod in the system will be able to consume as much CPU and memory as is on the node that executes the pod.

Reference:
https://kubernetes.io/docs/tasks/administer-cluster/cpu-memory-limit/

Body:
I defined my deployment resources

    resources:
      limits:
        cpu: 900m
        memory: 2500Mi

now on http://localhost:8001/api

how can I get the max usage of memory and cpu (in order to handle and define usages and resources well)?


问:
Testing RxJava2 doOnComplete()
As you can see from the code below, I am attempting to test the behavior of the doOnComplete() call occurring within my repository. However, when I mock the injected dependency of my client where I return items using Observable.just(), the doOnComplete() is no longer invoked. I believe this is intentional as per RxJava2. I'm unsure as to how to work around this.

```<code>@Singleton
public class Repository {
    private SomeNetworkClient client;
    private SomeCache cache;

    @Inject
    public Repository(SomeNetworkClient client, SomeCache cache) {
        this.client = client;
        this.cache = cache;
    }

    public Observable<SomeItem> getSomeItem() {
        return client.getSomeItem()
                .doOnComplete(() -> cache.doThisOnComplete())
                .doOnError(throwable -> someError);
    }
}

public class RepositoryTest {
    private Repository testedRepository;
    @Mock
    SomeNetworkClient client;
    @Mock
    SomeCache cache;
    @Mock
    SomeItem someItem;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        testedRepository = new Repository(client, cache);
        when(client.getSomeItem())
            .thenReturn(Observable.just(someItem));
    }

    @Test
    public void thisTestFails() {
        testedRepository.getSomeItem().blockingFirst();
        // This fails because it appears that mocking with
        // Observable.just() makes doOnComplete() not be invoked.
        verify(cache.doThisOnComplete());
    }
}
</code>```

答:
The problem in you code is, that blockingFirst() won't care to listen for complete event to happen. It will immediately return the first item from the stream and dispose from observable.

Instead, you may perform assertion this way:

```
<code>
    testedRepository
            .getSomeItem()
            .test()
            .assertComplete()
</code>
```

Title: Testing RxJava2 doOnComplete()

Body:
As you can see from the code below, I am attempting to test the behavior of the doOnComplete() call occurring within my repository. However, when I mock the injected dependency of my client where I return items using Observable.just(), the doOnComplete() is no longer invoked. I believe this is intentional as per RxJava2. I'm unsure as to how to work around this.

@Singleton
public class Repository {
    private SomeNetworkClient client;
    private SomeCache cache;

    @Inject
    public Repository(SomeNetworkClient client, SomeCache cache) {
        this.client = client;
        this.cache = cache;
    }

    public Observable<SomeItem> getSomeItem() {
        return client.getSomeItem()
                .doOnComplete(() -> cache.doThisOnComplete())
                .doOnError(throwable -> someError);
    }
}

public class RepositoryTest {
    private Repository testedRepository;
    @Mock
    SomeNetworkClient client;
    @Mock
    SomeCache cache;
    @Mock
    SomeItem someItem;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        testedRepository = new Repository(client, cache);
        when(client.getSomeItem())
            .thenReturn(Observable.just(someItem));
    }

    @Test
    public void thisTestFails() {
        testedRepository.getSomeItem().blockingFirst();
        // This fails because it appears that mocking with
        // Observable.just() makes doOnComplete() not be invoked.
        verify(cache.doThisOnComplete());
    }
}

Body:
The problem in you code is, that blockingFirst() won't care to listen for complete event to happen. It will immediately return the first item from the stream and dispose from observable.

Instead, you may perform assertion this way:

    testedRepository
            .getSomeItem()
            .test()
            .assertComplete()


问:
How to handle null or empty value in multi layer project
I am working in Xamarin.android mobile application. I got some problem of crashing the app due to null value set to TextView.Text and ImageView from api call value. I wonder is there any better way to handle null value in any layer of application i.e. DataLayer or UI. As I have setup this structure in my project.
MyApplication.DA (for data access layer) and all my getters and setters are set under here. In this case, I have DA_WebSchoolNews.cs as

```<code> public class NewsServiceRootObject
{
    public List<DA_NewsServiceResult> NewsServiceResult { get; set; }
}

public class DA_NewsServiceResult
{
    public string CreatedDate { get; set; }
    public string Description { get; set; }
    public string Id { get; set; }
    public string Image { get; set; }
    public string PublishDate { get; set; }
    public string ShortDescription { get; set; }
    public string Title { get; set; }
    public string UserName { get; set; }
}
</code>```

In MyApplication.Core, which is shared project I have called webapi service to update data:

```<code> public async void downloadJsonFeedAsync(string url)
    {
        var httpClient = new HttpClient();

        Task<string> contentTask = httpClient.GetStringAsync(url);

        // await! control returns to the caller and the task continues to run on another thread
        string content = await contentTask;
        Console.Out.WriteLine("Response Body: \r\n {0}", content);

        //Convert string to JSON object
        rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<NewsServiceRootObject>(content);

    }
</code>```

In MyApplication.UI, an UI layer in which I have created activities and fragments views. In my adapter class, I tried to handle null values so that view would not set any null values during run time, which I have done as follows

```<code> DA_NewsServiceResult item = this[position];
        if (string.IsNullOrEmpty(item.Title)|| string.IsNullOrEmpty(item.Description))
        {
            item.Title = "";
            item.Description = "";
        }

            var txtTitle = view.FindViewById<TextView>(Resource.Id.Title).Text = Android.Text.Html.FromHtml(item.Title).ToString();
            var txtDescription = view.FindViewById<TextView>(Resource.Id.Description).Text = Android.Text.Html.FromHtml(item.ShortDescription).ToString();
            var txtDate = view.FindViewById<TextView>(Resource.Id.news_date).Text = GetCustomDateTime(ConvertToDate(item.PublishDate));
</code>```

what is the best way to handle null or empty for string, date time , int or float type data and how. I will appreciate with sample lines of code if applicable. Thank you.

答:
In your Data Transfer Object (DA_NewsServiceResult in your case) you could make all Value Type properties nullable (e.g. int? / Nullable<int>, DateTime?, etc.).

In your view layer you could then always handle everything as an object and check for null and then do what's best for the view (maybe hide the view element that would usually display the value)

That could be handled in a pretty generic and reusable method to which you pass the properties value and maybe a callback for what to do with a valid value (and an optional callback for what do execute when a null value is encountered)

(as a side note - it's always a good idea to use DateTimeOffset instead of DateTime on DTOs (or basically anywhere) since it includes the offset from the UTC and could more easily be converted into local time / time zone specific time)

Alternative approach:

Make a generic extension method and check whether the given value is the default value. E.g. like so.

```<code>public static class ObjectExtensions
{
    public static bool IsDefaultValue<TObject>(this TObject @object)
    {
        return EqualityComparer<TObject>.Default.Equals(@object, default(TObject));
    }
}
</code>```

With that you could check every property for whether it is the default (has not been set for structs / value types and null for class objects) and act accordingly.

Addition for string check

If you were to encounter a null string but wanted to use an empty string on your view you could to the following.

```<code>var txtTitle = view.FindViewById<TextView>(Resource.Id.Title).Text = Android.Text.Html.FromHtml(item.Title ?? "").ToString();
</code>```

Body:
I am working in Xamarin.android mobile application. I got some problem of crashing the app due to null value set to TextView.Text and ImageView from api call value. I wonder is there any better way to handle null value in any layer of application i.e. DataLayer or UI. As I have setup this structure in my project.
MyApplication.DA (for data access layer) and all my getters and setters are set under here. In this case, I have DA_WebSchoolNews.cs as

 public class NewsServiceRootObject
{
    public List<DA_NewsServiceResult> NewsServiceResult { get; set; }
}

public class DA_NewsServiceResult
{
    public string CreatedDate { get; set; }
    public string Description { get; set; }
    public string Id { get; set; }
    public string Image { get; set; }
    public string PublishDate { get; set; }
    public string ShortDescription { get; set; }
    public string Title { get; set; }
    public string UserName { get; set; }
}

In MyApplication.Core, which is shared project I have called webapi service to update data:

 public async void downloadJsonFeedAsync(string url)
    {
        var httpClient = new HttpClient();

        Task<string> contentTask = httpClient.GetStringAsync(url);

        // await! control returns to the caller and the task continues to run on another thread
        string content = await contentTask;
        Console.Out.WriteLine("Response Body: \r\n {0}", content);

        //Convert string to JSON object
        rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<NewsServiceRootObject>(content);

    }

In MyApplication.UI, an UI layer in which I have created activities and fragments views. In my adapter class, I tried to handle null values so that view would not set any null values during run time, which I have done as follows

 DA_NewsServiceResult item = this[position];
        if (string.IsNullOrEmpty(item.Title)|| string.IsNullOrEmpty(item.Description))
        {
            item.Title = "";
            item.Description = "";
        }

            var txtTitle = view.FindViewById<TextView>(Resource.Id.Title).Text = Android.Text.Html.FromHtml(item.Title).ToString();
            var txtDescription = view.FindViewById<TextView>(Resource.Id.Description).Text = Android.Text.Html.FromHtml(item.ShortDescription).ToString();
            var txtDate = view.FindViewById<TextView>(Resource.Id.news_date).Text = GetCustomDateTime(ConvertToDate(item.PublishDate));

what is the best way to handle null or empty for string, date time , int or float type data and how. I will appreciate with sample lines of code if applicable. Thank you.

Body:
In your Data Transfer Object (DA_NewsServiceResult in your case) you could make all Value Type properties nullable (e.g. int? / Nullable<int>, DateTime?, etc.).

In your view layer you could then always handle everything as an object and check for null and then do what's best for the view (maybe hide the view element that would usually display the value)

That could be handled in a pretty generic and reusable method to which you pass the properties value and maybe a callback for what to do with a valid value (and an optional callback for what do execute when a null value is encountered)

(as a side note - it's always a good idea to use DateTimeOffset instead of DateTime on DTOs (or basically anywhere) since it includes the offset from the UTC and could more easily be converted into local time / time zone specific time)

Alternative approach:

Make a generic extension method and check whether the given value is the default value. E.g. like so.

public static class ObjectExtensions
{
    public static bool IsDefaultValue<TObject>(this TObject @object)
    {
        return EqualityComparer<TObject>.Default.Equals(@object, default(TObject));
    }
}

With that you could check every property for whether it is the default (has not been set for structs / value types and null for class objects) and act accordingly.

Addition for string check

If you were to encounter a null string but wanted to use an empty string on your view you could to the following.

var txtTitle = view.FindViewById<TextView>(Resource.Id.Title).Text = Android.Text.Html.FromHtml(item.Title ?? "").ToString();


答:
This will work with python 3:</p>

```<code>d = {'a': 1, 'b': 2, 'c': [3, 4, 5]}
def f(**d):
    return [{**d, 'c': i} for i in d.pop('c')]
</code>```

Title: How does python achieve the following data format conversion?

Body:
I would like to achieve a function that deals with the following data：'d' and generate 'L'. How to achieve?

def func(**d):
   'do something'
    return [....]

source:

   d = {'a': 1, 'b': 2, 'c': [3, 4, 5]}

or

   d = {'a': 1, 'b': 2, 'c': [3, 4, 5], 'd': [6, 7]}

TO:

  L=[{'a':1,'b':2,'c':3},
   {'a':1,'b':2,'c':4},
   {'a':1,'b':2,'c':5}]

or

  L=[{'a': 1, 'b': 2, 'c': 3, 'd': 6},
    {'a': 1, 'b': 2, 'c': 3, 'd': 7},
    {'a': 1, 'b': 2, 'c': 4, 'd': 6},
    {'a': 1, 'b': 2, 'c': 4, 'd': 7},
    {'a': 1, 'b': 2, 'c': 5, 'd': 6},
    {'a': 1, 'b': 2, 'c': 5, 'd': 7}]

Body:
This will work with python 3:

d = {'a': 1, 'b': 2, 'c': [3, 4, 5]}
def f(**d):
    return [{**d, 'c': i} for i in d.pop('c')]


问:
Automatically focusing on javascript dialog in safari?
Right, I've edited this post a bit following some further tests I've been doing, my original post is below, however, this is now the crux of the issue.

I have 3 images on a page, when one is clicked a javascript window.confirm dialog is displayed asking the user to confirm their selection. However, due to the positioning of the images on the page, the dialog appears over an image, when trying to click OK or Cancel, nothing appears to happen. However, what actually does happen is that another confirmation appears over the top of the original one, and this continues. However, if I click somewhere on the button that doesn't have the image behind, then it works, but only after double clicking.

What I've found is that when a dialog is displayed, it doesn't automatically get focus, so you have to click it to focus, before clicking the button again to close the dialog. If on the first click you click the part of a button (or the dialog itself) that has an image behind, that image is actually clicked as the dialog doesn't have focus. However, if you click anywhere in the dialog which doesn't have an image behind (therefore focusing on the dialog), then click OK or Cancel, it works (even where the OK or Cancel button has an image behind).

So what I need to know is, is there a way of automatically focussing on the dialog when it opens, therefore preventing the need for double-clicking? Or is this just a safari bug that I'll have to find another way around.

--------original post---------

I have a website with a series of images and links. When an image or link is clicked, a window.confirm dialog is displayed asking the user if they are sure they want to carry out the action.

In IE, Opera and Firefox this works fine.

However, in Safari, when I click the OK or Cancel buttons on the dialog, whatever is on the page behind the button is actually clicked, rather than the button in the dialog itself. The dialog actually says "Are you sure you want to vote for xyz", where xyz is based on the clicked image or link - when I click OK or cancel in the dialog the text changes to whatever image/link is behind that OK/Cancel button.

Has anyone seen this bug, and/or knows a way around it?

UPDATE

I've been managing to narrow it down a bit, and have just found where the issue seems to lie.

I found that if I clicked the part of a button that didn't have an image behind it (each image is actually a .NET ImageButton), then it would work (though it requires a double-click). If I click part of a button that does have an image behind it then it would open up a further alert/confirm dialog. I've put some JQuery in which adds a click event to each image, on clicking it hides the image, then displays the dialog, and the dialog works fine.

Obviously this isn't what I require (don't really want the images disappearing), but it has narrowed it down. Any ideas how this can be solved?

Another update: I think that actually the alert/confirm dialog isn't initially getting focus, hence the need to double click. If I click the dialog (anywhere where an image isn't behind) then click OK (even if there is an image behind that button) then it works. So, how do I get it to focus automatically on the dialog once its opened?

答:
I just ran into this myself and haven't found an answer yet, but I thought I would post things I have observed to see if they're the same for you.

You say you have to click the dialog to give it focus before it will work.  I have found that you simply have to click anywhere in Safari, even not on the dialog, and the dialog will start working.  Furthermore, it doesn't seem to be exactly a focus issue as keyboard control of the dialog still works, Space to select OK, or Tab and Space to select Cancel.  Can you confirm this?

What version of Safari are you running and what version of Windows?  I am running Windows 7, Safari 5.0.3 (7533.19.4).  I will try to test this on Mac as well or you could if it's convenient for you.

In Windows 7 buttons highlight on mouse over even if they are in a window without focus.  This issue in Safari causes some interesting reactions in the buttons.  When the dialog first pops up buttons on the page still highlight on mouse over, but the buttons in the dialog do not.  After a click in Safari the Cancel button in the dialog highlights on mouse over, but the buttons on the page do not and the OK button in the dialog does not.  However, if, instead of clicking in Safari, some other application is given focus by a click both buttons in the dialog highlight while the buttons on the page do not.  There is even more inconsistent behaviour when Safari regains focus.  If it regained focus by a click in the dialog both the buttons in the dialog highlight.  If it regained focus by a click not in the dialog only the Cancel button highlights, not the OK button.

That was all if focus was transferred with the mouse.  When focus is transferred by Alt-Tabbing there is different bahaviour.  In that case when a different application is first given focus the buttons remain as they were with the buttons on the page highlighting and the buttons in the dialog not.  If Safari is Alt-Tabbed back to it's as if nothing has happened and you still have to click to get the dialog working.  If Safari is clicked on anywhere, in the dialog or not, both buttons in the dialog highlight and the buttons on the page do not.

Inconsistent behaviour of buttons can be found elsewhere in Safari.  The Print and Save menu items bring up Windows default dialogs so buttons in those behave consistently with Windows.  Safari specific dialogs, like the Javascript confirm, Customize Toolbar..., and Report Bugs to Apple... have different sized buttons.  Furthermore, the Done button in Customize Toolbar is the default button, but will not highlight until the dialog has been clicked on.  The Submit button in Report Bugs is the default button and will highlight on mouse over without clicking on the dialog, but does not show the blue ring to indicate it is default until it has been moused over.

All of this is, of course, what I experienced so it may not be the same for you.  At this point, because the behaviour is so inconsistent I think it is a bug in Safari, but I will investigate further.


问:
Is n ≠ Θ(logn)?
Question is asked with an intent to get/let understand how to verify Asymptotic Θ notation. A Homework question. I am to show that n ≠ Θ(logn)

Solution: Yes, n ≠ Θ(logn).

```<code>c1logn ≤ n ≤ c2logn => c2≥n/logn, Ɐ n≥n0 - Impossible
</code>```

Why c2≥n/logn is not possible?

答:
Well,

```<code> f(n) = Θ(g(n))
</code>```

if and only if there's a finite limit value

```<code> lim f(n)/g(n) = c > 0
   n -> +inf
</code>```

which means that for any constants c1 < c < c2 we can find n0 such that f(n)/g(n) will be in the [c1..c2] range for all n > n0 (put it differently c1*g(n) < f(n) < c2*g(n) when n > n0).
In your case

```<code> f(n) = n
 g(n) = log(n)
</code>```

The limit is (let's use L'Hôpital's rule)

```<code>lim n/log(n) = lim 1/(1/n) = lim n = +inf
  n -> +inf      n -> +inf     n -> +inf
</code>```

there's no such a finite constant c (and we can't select any c2 constant such that c < c2).

Title: Is n ≠ Θ(logn)?

Body:
Question is asked with an intent to get/let understand how to verify Asymptotic Θ notation. A Homework question. I am to show that n ≠ Θ(logn)

Solution: Yes, n ≠ Θ(logn).

c1logn ≤ n ≤ c2logn => c2≥n/logn, Ɐ n≥n0 - Impossible

Why c2≥n/logn is not possible?

Body:
Well,

 f(n) = Θ(g(n))

if and only if there's a finite limit value

 lim f(n)/g(n) = c > 0
   n -> +inf

which means that for any constants c1 < c < c2 we can find n0 such that f(n)/g(n) will be in the [c1..c2] range for all n > n0 (put it differently c1*g(n) < f(n) < c2*g(n) when n > n0).
In your case

 f(n) = n
 g(n) = log(n)

The limit is (let's use L'Hôpital's rule)

lim n/log(n) = lim 1/(1/n) = lim n = +inf
  n -> +inf      n -> +inf     n -> +inf

there's no such a finite constant c (and we can't select any c2 constant such that c < c2).


问:
Bootstrap 4 Cards of same height in columns
I'm currently working on Cards from Bootstrap.

Depending on the text title I will get the different height for the cards and would like to have the same height as the tallest one.

I don't mind using JS I actually think is probably the best way to approach the problem.

I have tried using different solutions from the CSS like using flexbox.

The rendered HTML as it is rendered dynamically here's a simple example:

.card {
  float: left;
  width: 100%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 0;
  box-shadow: 0px 0px 8px 0.3px rgba(0, 0, 0, 1);
}

.card>img {
  margin-bottom: .75rem;
  display: block;
  width: 80%;
  height: auto;
  margin-left: auto;
  margin-right: auto;
}

.card-text {
  font-size: 85%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SMITE FR</title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/album.css" rel="stylesheet">
  <link href="css/ie10-viewport-bug-workaround.min.css" rel="stylesheet">
  <script src="https://www.w3schools.com/lib/w3data.js"></script>
  <link rel="import" href="navigation.html">
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="card-deck">
        <div class="col-md-4 col-sm-6 col-12">
          <div class="card">
            <img src="images/dieux/Agni.jpg" alt="BeatsX">
            <h1 class="card-title">BeatsX</h1>
            <div class="text-center">
              <p>1188.0000</p>
              <p>2017-06-09 10:00:00</p>
              Voir la Fiche
            </div>
          </div>
        </div>
        <div class="col-md-4 col-sm-6 col-12">
          <div class="card">
            <img src="images/dieux/Agni.jpg" alt="Nitendo Switch">
            <h1 class="card-title">Nitendo Switch</h1>
            <div class="text-center">
              <p>2899.0000</p>
              <p>2017-06-10 10:00:00</p>
              Voir la Fiche
            </div>
          </div>
        </div>
        <div class="col-md-4 col-sm-6 col-12">
          <div class="card">
            <img src="images/dieux/Agni.jpg" alt="iPhone 7 128GB (Jet Blakc)">
            <h1 class="card-title">iPhone 7 128GB (Jet Blakc)</h1>
            <div class="text-center">
              <p>6388.0000</p>
              <p>2017-06-06 10:00:00</p>
              Voir la Fiche
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html></code>```

答:
Using Flexbox you got the equal height of the card

.card-deck {
  display:flex;
  flex-wrap: wrap;
}
.card {
    float: left;
    width: 100%;
    height:100%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 0;
    box-shadow: 0px 0px 8px 0.3px rgba(0,0,0,1);
}

.card > img {
    margin-bottom: .75rem;
    display: block;
    width: 80%;
    height: auto;
    margin-left: auto;
    margin-right: auto;
}

.card-text {
    font-size: 85%;
}

@media (max-width:767px){
  .card-deck {
    display:block;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="card-deck">
      <div class="col-md-4 col-sm-6 col-12">
        <div class="card">
          <img src="images/dieux/Agni.jpg" alt="BeatsX">
          <h1 class="card-title">BeatsX</h1>
          <div class="text-center">
            <p>1188.0000</p>
            <p>2017-06-09 10:00:00</p>
            Voir la Fiche
          </div>
        </div>
      </div>
      <div class="col-md-4 col-sm-6 col-12">
        <div class="card">
          <img src="images/dieux/Agni.jpg" alt="Nitendo Switch">
          <h1 class="card-title">Nitendo Switch</h1>
          <div class="text-center">
            <p>2899.0000</p>
            <p>2017-06-10 10:00:00</p>
            Voir la Fiche
          </div>
        </div>
      </div>
      <div class="col-md-4 col-sm-6 col-12">
        <div class="card">
          <img src="images/dieux/Agni.jpg" alt="iPhone 7 128GB (Jet Blakc)">
          <h1 class="card-title">iPhone 7 128GB (Jet Blakc)</h1>
          <div class="text-center">
            <p>6388.0000</p>
            <p>2017-06-06 10:00:00</p>
            Voir la Fiche
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
I'm currently working on Cards from Bootstrap.

Depending on the text title I will get the different height for the cards and would like to have the same height as the tallest one.

I don't mind using JS I actually think is probably the best way to approach the problem.

I have tried using different solutions from the CSS like using flexbox.

The rendered HTML as it is rendered dynamically here's a simple example:

.card {
  float: left;
  width: 100%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 0;
  box-shadow: 0px 0px 8px 0.3px rgba(0, 0, 0, 1);
}

.card>img {
  margin-bottom: .75rem;
  display: block;
  width: 80%;
  height: auto;
  margin-left: auto;
  margin-right: auto;
}

.card-text {
  font-size: 85%;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SMITE FR</title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/album.css" rel="stylesheet">
  <link href="css/ie10-viewport-bug-workaround.min.css" rel="stylesheet">

  <link rel="import" href="navigation.html">

BeatsX

1188.0000

2017-06-09 10:00:00

              Voir la Fiche

Nitendo Switch

2899.0000

2017-06-10 10:00:00

              Voir la Fiche

iPhone 7 128GB (Jet Blakc)

6388.0000

2017-06-06 10:00:00

              Voir la Fiche

Body:
Using Flexbox you got the equal height of the card

.card-deck {
  display:flex;
  flex-wrap: wrap;
}
.card {
    float: left;
    width: 100%;
    height:100%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 0;
    box-shadow: 0px 0px 8px 0.3px rgba(0,0,0,1);
}

.card > img {
    margin-bottom: .75rem;
    display: block;
    width: 80%;
    height: auto;
    margin-left: auto;
    margin-right: auto;
}

.card-text {
    font-size: 85%;
}

@media (max-width:767px){
  .card-deck {
    display:block;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="card-deck">
      <div class="col-md-4 col-sm-6 col-12">
        <div class="card">
          <img src="images/dieux/Agni.jpg" alt="BeatsX">
          <h1 class="card-title">BeatsX</h1>
          <div class="text-center">
            <p>1188.0000</p>
            <p>2017-06-09 10:00:00</p>
            <a href="god.php?ID=2" target="_blank" class="btn btn-primary">Voir la Fiche</a>
          </div>
        </div>
      </div>
      <div class="col-md-4 col-sm-6 col-12">
        <div class="card">
          <img src="images/dieux/Agni.jpg" alt="Nitendo Switch">
          <h1 class="card-title">Nitendo Switch</h1>
          <div class="text-center">
            <p>2899.0000</p>
            <p>2017-06-10 10:00:00</p>
            <a href="god.php?ID=3" target="_blank" class="btn btn-primary">Voir la Fiche</a>
          </div>
        </div>
      </div>
      <div class="col-md-4 col-sm-6 col-12">
        <div class="card">
          <img src="images/dieux/Agni.jpg" alt="iPhone 7 128GB (Jet Blakc)">
          <h1 class="card-title">iPhone 7 128GB (Jet Blakc)</h1>
          <div class="text-center">
            <p>6388.0000</p>
            <p>2017-06-06 10:00:00</p>
            <a href="god.php?ID=1" target="_blank" class="btn btn-primary">Voir la Fiche</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
how to add array object values in javascript
hi all i am using javascript working with array i have a set of data to do add array values object here i attached my code help how to solve this

data

```<code>var data=[{one:1,two:2},{one:1,two:2},{one:1,two:2},{one:1,two:2}]
</code>```

expected output

```<code>var sumdata=[{one:4,two:8}]
</code>```

NOTE:one two column name is not static

答:
You could use an object as result and iterate the keys of the object and sum the values.

var data = [{ one: 1, two: 2 }, { one: 1, two: 2 }, { one: 1, two: 2 }, { one: 1, two: 2 }],
    result = data.reduce(function (r, o) {    // iterate array
        Object.keys(o).forEach(function (k) { // iterate the keys of the object
            r[k] = (r[k] || 0) + o[k];        // check if a property exists or take zero
        });                                   // and add the actual value
        return r;                             // return the object
    }, Object.create(null));                  // start with an empty object without
                                              // some prototypes
console.log(result);```

Body:
hi all i am using javascript working with array i have a set of data to do add array values object here i attached my code help how to solve this

data

var data=[{one:1,two:2},{one:1,two:2},{one:1,two:2},{one:1,two:2}]

expected output

var sumdata=[{one:4,two:8}]

NOTE:one two column name is not static


问:
How to properly handle a null variable perspective in kotlin?
My old java version method looks like:

```<code>@Override
public void closeSimpleAlertDialog() {
    if (mAlertDialog != null && mAlertDialog.isShowing()) {
        mAlertDialog.dismiss();
    }
}
</code>```

As you can tell it is checked whether the null reference link to a dialog mAlertDialog and if not null check call method isShowing(), and only then caused a method of close - dismiss(). Very simple

I faced a problem - how is still in "Kotlin-style" to perform the same operation?

My first version looks here:

```<code>if (mAlertDialog != null && mAlertDialog?.isShowing) {
        mAlertDialog?.dismiss()
}
</code>```

Next step change mAlertDialog != null && mAlertDialog?.isShowing to mAlertDialog?.isShowing ?: false and last version looks like:

```<code>if (mAlertDialog?.isShowing ?: false)
            mAlertDialog?.dismiss()
</code>```

But I don't understand. Why do I need "?" if the null checking already happened before (here: mAlertDialog?.)?

答:
Because another thread might make the property null after the null check, and before the call to dismiss. It won't happen if you use a local variable, or let.

BTW, if you omit the question mark and hover on the red squiggly, IntelliJ tells you

Smart cast to Dialog is impossible, because mAlertDialog is a mutable property that could have been changed by this time

The canonical way (AFAIK) to do that with Kotlin would be

```<code>fun close() {
    mAlertDialog?.let {
        if (it.isShowing) {
            it.dismiss()
        }
    }
}
</code>```

Body:
My old java version method looks like:

@Override
public void closeSimpleAlertDialog() {
    if (mAlertDialog != null && mAlertDialog.isShowing()) {
        mAlertDialog.dismiss();
    }
}

As you can tell it is checked whether the null reference link to a dialog mAlertDialog and if not null check call method isShowing(), and only then caused a method of close - dismiss(). Very simple

I faced a problem - how is still in "Kotlin-style" to perform the same operation?

My first version looks here:

if (mAlertDialog != null && mAlertDialog?.isShowing) {
        mAlertDialog?.dismiss()
}

Next step change mAlertDialog != null && mAlertDialog?.isShowing to mAlertDialog?.isShowing ?: false and last version looks like:

if (mAlertDialog?.isShowing ?: false)
            mAlertDialog?.dismiss()

But I don't understand. Why do I need "?" if the null checking already happened before (here: mAlertDialog?.)?

Body:
Because another thread might make the property null after the null check, and before the call to dismiss. It won't happen if you use a local variable, or let.

BTW, if you omit the question mark and hover on the red squiggly, IntelliJ tells you

Smart cast to Dialog is impossible, because mAlertDialog is a mutable property that could have been changed by this time

The canonical way (AFAIK) to do that with Kotlin would be

fun close() {
    mAlertDialog?.let {
        if (it.isShowing) {
            it.dismiss()
        }
    }
}


问:
ScrollView not scrolling at all
I can't make a ScrollView properly scrolling. It always cut off the content on the bottom, as if it were a normal LinearLayout.

My code

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true" >

    <LinearLayout android:id="@+id/scroll_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:isScrollContainer="true"
        android:orientation="vertical" >
</code>```

Of course, I already tried to add / remove the "fillViewport" and "isScrollContainer" properties, and  it did not change anything at all.

This is for ScrollView (VERTICAL ONLY)

HorizontalScrollView must be used for horizontal scrolling.

答:
Try this solution, just delay your scroll using post delayed method.

fragment_test.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:fresco="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="40dp"
        android:fillViewport="true"
        android:scrollbars="none">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            ...
        </RelativeLayout>

    </ScrollView>

</RelativeLayout>
</code>```

TestFragment.java

```<code>...
private ScrollView mScrollView;
...
mScrollView = (ScrollView) mView.findViewById(R.id.scrollView);
mScrollView.setSmoothScrollingEnabled(true);
...
new Handler().postDelayed(new Runnable() {
    @Override
     public void run() {
         if(isAdded()) {
             // Scroll 1000px down
             mScrollView.smoothScrollTo(0, 1000);
         }
     }
}, 150);
</code>```

This worked for me, hope this helps.

Title: ScrollView not scrolling at all

Body:
I can't make a ScrollView properly scrolling. It always cut off the content on the bottom, as if it were a normal LinearLayout.

My code

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true" >

    <LinearLayout android:id="@+id/scroll_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:isScrollContainer="true"
        android:orientation="vertical" >

Of course, I already tried to add / remove the "fillViewport" and "isScrollContainer" properties, and  it did not change anything at all.

This is for ScrollView (VERTICAL ONLY)

HorizontalScrollView must be used for horizontal scrolling.

Body:
Try this solution, just delay your scroll using post delayed method.

fragment_test.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:fresco="http://schemas.android.com/apk/res-auto">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="40dp"
        android:fillViewport="true"
        android:scrollbars="none">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            ...
        </RelativeLayout>

    </ScrollView>

</RelativeLayout>

TestFragment.java

...
private ScrollView mScrollView;
...
mScrollView = (ScrollView) mView.findViewById(R.id.scrollView);
mScrollView.setSmoothScrollingEnabled(true);
...
new Handler().postDelayed(new Runnable() {
    @Override
     public void run() {
         if(isAdded()) {
             // Scroll 1000px down
             mScrollView.smoothScrollTo(0, 1000);
         }
     }
}, 150);

This worked for me, hope this helps.


问:
Finding the next element value of a particular index in a Python list
I have a simple python program to find whether a sentence is a question or not.

```<code>from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer

a = ["what are you doing","are you mad?","how sad"]
question =["what","why","how","are","am","should","do","can","have","could","when","whose","shall","is","would","may","whoever","does"];
word_list =["i","me","he","she","you","it","that","this","many","someone","everybody","her","they","them","his","we","am","is","are","was","were","should","did","would","does","do"];

def f(paragraph):
  sentences = paragraph.split(".")
  result = []

  for i in range(len(sentences)):

    token = word_tokenize(sentences[i])
    change_tense = [WordNetLemmatizer().lemmatize(word, 'v') for word in token]
    input_sentences = [item.lower() for item in change_tense]

    if input_sentences[-1]=='?':
        result.append("question")

    elif input_sentences[0] in question:
        find_question = [input_sentences.index(qestion) for qestion in input_sentences if qestion in question]
        if len(find_question) > 0:
            for a in find_question:
                if input_sentences[a + 1] in word_list:
                    result.append("question")
                else:
                    result.append("not a question")
    else:
        result.append("not a quetion")

return result
my_result = [f(paragraph) for paragraph in a]
print my_result
</code>```

But it makes following error.

```<code>if input_sentences[a + 1] in word_list:
IndexError: list index out of range
</code>```

I think problem cause in finding the next element value of the a. Can any one help me to solve this issue.

答:
The problem is that input_sentences.index(qestion) can return the last index of input_sentences, which means that a + 1 will be one larger than there are elements in input_sentences, this then causes the IndexError as you are trying to access an element of the list in if input_sentences[a + 1] in word_list: which does not exist.

You're logic for checking the "next element" therefore is incorrect, the last element in a list does not have a "next element". Looking at your wordlists a question like What should I do will fail as do will be picked up as a question word but there is nothing after it (assuming you strip punctuation). So you need to rethink the way in which you detect a question.

Body:
I have a simple python program to find whether a sentence is a question or not.

from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer

a = ["what are you doing","are you mad?","how sad"]
question =["what","why","how","are","am","should","do","can","have","could","when","whose","shall","is","would","may","whoever","does"];
word_list =["i","me","he","she","you","it","that","this","many","someone","everybody","her","they","them","his","we","am","is","are","was","were","should","did","would","does","do"];

def f(paragraph):
  sentences = paragraph.split(".")
  result = []

  for i in range(len(sentences)):

    token = word_tokenize(sentences[i])
    change_tense = [WordNetLemmatizer().lemmatize(word, 'v') for word in token]
    input_sentences = [item.lower() for item in change_tense]

    if input_sentences[-1]=='?':
        result.append("question")

    elif input_sentences[0] in question:
        find_question = [input_sentences.index(qestion) for qestion in input_sentences if qestion in question]
        if len(find_question) > 0:
            for a in find_question:
                if input_sentences[a + 1] in word_list:
                    result.append("question")
                else:
                    result.append("not a question")
    else:
        result.append("not a quetion")

return result
my_result = [f(paragraph) for paragraph in a]
print my_result

But it makes following error.

if input_sentences[a + 1] in word_list:
IndexError: list index out of range

I think problem cause in finding the next element value of the a. Can any one help me to solve this issue.


问:
column selection for over 10,000 lines in sublime windows
I was trying to do a column (or vertical) selection in sublime but for over a 10,000 lines.

What happens with ctrl + shift and right click is that it takes to long to reach 10,000 lines. The same happens with ctrl+alt [up or down arrows].

I have found many topics on column selection but they are not efficient for a lot of lines.

Do you know how to select a column of more than 10,000 lines, in a fast way?

答:
I think you're looking for the Split Selection Into Lines feature. Which is Ctrl+Shift+L.

First select all lines with Ctrl+A. Then use the above shortcut to split your selection.


问:
uploading file from android app into desired folder
I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever</p>

```<code> $response = array();

    if($_SERVER['REQUEST_METHOD']=='POST'){

        //checking the required parameters from the request
        if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name'])  ){

                //connecting to the database
            $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');

            $resume_name = $_POST['exp'];
            $employee_id = $_POST['employee_id'];
            $file_data = $_FILES['pdf']['name'];

            $upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';

              //getting file info from the request
            $fileinfo = pathinfo($_FILES['pdf']['name']);

             //getting the file extension
            $extension = $fileinfo['extension'];

            //file url to store in the database
            $file_url = $upload_path . getFileName($employee_id). '.'. $extension;

            //file path to upload in the server
            $file_path = $upload_path . getFileName($employee_id);

         try{

            if(file_exists($upload_path))
            {
               $existing_file = glob($upload_path."/*.*");
               $empty_file = implode(" ",$existing_file);

              move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

    $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

               //adding the path and name to database
               if(mysqli_query($con,$sql)){

                    //filling response array with values

                    $response['Success'] = "File Uploaded Successfully...!";
                    echo json_encode($response);

                }
                else
                {
                  $response['Error'] = "File Uploading Error...!";
                  echo json_encode($response);
                }

            }
                else
                {
                      mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
                      move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

        $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

                            //adding the path and name to database
                            if(mysqli_query($con,$sql))
                            {

                             //filling response array with values

                                 $response['Success'] = "File Uploaded Successfully...!";
                                 echo json_encode($response);

                            }
                        else
                            {
                                $response['Error'] = "File Uploading Error...!";
                                echo json_encode($response);
                            }

                }
            }catch(Exception $e){
                $response['error']=true;
                $response['message']=$e->getMessage();
            }
    }

    }

      //here is my method getFileName

function getFileName($employee_id)
 {

   //mysql query to fetch data
   $sql = mysql_query("SELECT resume_path from employee_registration where
     employee_id = '$employee_id'") or die(mysql_error());
   while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
   {
     $response=$row['resume_path'];
   }
    $resume_name = explode("/", $response);
   echo $resume_name[4];
   return $resume_name;
  }
</code>```

答:
if this doenst work move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;

kindly use this file_put_contents($upload_path,$_FILES['pdf']['tmp_name']);

Body:
I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever

 $response = array();

    if($_SERVER['REQUEST_METHOD']=='POST'){

        //checking the required parameters from the request
        if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name'])  ){

                //connecting to the database
            $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');

            $resume_name = $_POST['exp'];
            $employee_id = $_POST['employee_id'];
            $file_data = $_FILES['pdf']['name'];

            $upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';

              //getting file info from the request
            $fileinfo = pathinfo($_FILES['pdf']['name']);

             //getting the file extension
            $extension = $fileinfo['extension'];

            //file url to store in the database
            $file_url = $upload_path . getFileName($employee_id). '.'. $extension;

            //file path to upload in the server
            $file_path = $upload_path . getFileName($employee_id);

         try{

            if(file_exists($upload_path))
            {
               $existing_file = glob($upload_path."/*.*");
               $empty_file = implode(" ",$existing_file);

              move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

    $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

               //adding the path and name to database
               if(mysqli_query($con,$sql)){

                    //filling response array with values

                    $response['Success'] = "File Uploaded Successfully...!";
                    echo json_encode($response);

                }
                else
                {
                  $response['Error'] = "File Uploading Error...!";
                  echo json_encode($response);
                }

            }
                else
                {
                      mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
                      move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

        $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

                            //adding the path and name to database
                            if(mysqli_query($con,$sql))
                            {

                             //filling response array with values

                                 $response['Success'] = "File Uploaded Successfully...!";
                                 echo json_encode($response);

                            }
                        else
                            {
                                $response['Error'] = "File Uploading Error...!";
                                echo json_encode($response);
                            }

                }
            }catch(Exception $e){
                $response['error']=true;
                $response['message']=$e->getMessage();
            }
    }

    }

      //here is my method getFileName

function getFileName($employee_id)
 {

   //mysql query to fetch data
   $sql = mysql_query("SELECT resume_path from employee_registration where
     employee_id = '$employee_id'") or die(mysql_error());
   while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
   {
     $response=$row['resume_path'];
   }
    $resume_name = explode("/", $response);
   echo $resume_name[4];
   return $resume_name;
  }


问:
How to take specific number of input in python
How do I take a specific number of input in python. Say, if I only want to insert 5 elements in a list then how can I do that?
I tried to do it but couldn't figure out how.

In the first line I want to take an integer which will be the size of the list.
Second line will consist 5 elements separated by a space like this:

5

1 2 3 4 5

Thanks in advance.

答:
Input :-

```<code>5

1 2 3 4 5
</code>```

then, use the below code :

```<code>n = int(input())    # Number of elements

List = list ( map ( int, input().split(" ") ) )
</code>```

Takes the space separated input as list of integers. Number of elements count is not necessary here.
You can get the size of the List by len(List) .
Here list is a keyword for generating a List.

Or you may use an alternative :

```<code>n = int(input())    # Number of elements

List = [ int(elem) for elem in input().split(" ")  ]
</code>```

If you want it as List of strings, then use :

```<code>List = list( input().split(" ") )
</code>```

or

```<code>s = input()   # default input is string by using input() function in python 2.7+

List = list( s.split(" ") )
</code>```

Or

```<code>List = [ elem for elem in input().split(" ")  ]
</code>```

Number of elements count is necessary while using a loop for receiving input in a new line ,then

```<code>Let the Input be like :

5

1

2

3

4

5
</code>```

The modified code will be:-

```<code>n = int(input())

List = [ ]  #declare an Empty list

for i in range(n):

    elem = int(input())

    List.append ( elem )
</code>```

For Earlier version of python , use raw_input ( ) instead of input ( ), which receives default input as String.

Body:
Input :-

5

1 2 3 4 5

then, use the below code :

n = int(input())    # Number of elements

List = list ( map ( int, input().split(" ") ) )

Takes the space separated input as list of integers. Number of elements count is not necessary here.
You can get the size of the List by len(List) .
Here list is a keyword for generating a List.

Or you may use an alternative :

n = int(input())    # Number of elements

List = [ int(elem) for elem in input().split(" ")  ]

If you want it as List of strings, then use :

List = list( input().split(" ") )

or

s = input()   # default input is string by using input() function in python 2.7+

List = list( s.split(" ") )

Or

List = [ elem for elem in input().split(" ")  ]

Number of elements count is necessary while using a loop for receiving input in a new line ,then

Let the Input be like :

5

1

2

3

4

5

The modified code will be:-

n = int(input())

List = [ ]  #declare an Empty list

for i in range(n):

    elem = int(input())

    List.append ( elem )

For Earlier version of python , use raw_input ( ) instead of input ( ), which receives default input as String.


问:
Form Submitting without captcha
I'm trying to implement google captcha v2 on a website that gets a lot of spam mail. The captcha is showing and working, but the form can be submitted without pressing the captcha. I had a look for similar questions but couldn't find any that would help me.

It is google's captcha V2

Form:

```<code><form action="mailer.php" method="post" onsubmit="return FrontPage_Form1_Validator(this)" language="JavaScript" name="FrontPage_Form1" enctype="multipart/form-data">
<input type="text" class="col-md-13 col-xs-12 name" name='name' placeholder='Name *'/>
<input type="text" class="col-md-13 col-xs-12 Email" name='Email' placeholder='Email *'/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' placeholder='Subject'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" name='Message' placeholder='Message *'></textarea>
<br>

<div class="captcha_wrapper col-md-12" style="margin-bottom: 10px;">

    <div class="g-recaptcha" data-sitekey="6Ld-ryQUAAAAAJSKzJubdxYjigpiTfhk11e1P7o9">
    </div>

</div>
</code>```

mailer.php:

```<code>if ($_SERVER['REQUEST_METHOD'] == "POST") {
foreach ($_POST as $key => $value) {
    $msg .= ucfirst ($key) ." : ". $value . "\n";
}
}
else {

foreach ($_GET as $key => $value) {

    $msg .= ucfirst ($key) ." : ". $value . "\n";

}
}

//captcha section

$response = $_POST["g-recaptcha-response"];

$url = 'https://www.google.com/recaptcha/api/siteverify';

$data = array(
    'secret' => '6Ld-ryQUAAAAALpIkTPN82doQhCFmiWrC14_UbYk',
    'response' => $_POST['g-recaptcha-response'];
);
$options = array(
    'http' => array (
        'method' => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);

//end of captcha section

mail($to, $subject, $msg, $headers);

if ($forward == 1) {
header ("Location:$location");
}
else {
include("index.html");
header( 'Location: ' ) ;
}
</code>```

`

Thank you. Any help is appreciated

I feel like I need to put the captcha code inside in if(isset())

答:
Print the $captcha_success values in order to check what's inside $captcha_success and understand how to manage the response. Then you can redirect the navigation properly.

var_dump($captcha_success); // to dump the values to web page
  error_log(print_r($captcha_success, true),0); // to dump to the php
  apache error_log

Title: Form Submitting without captcha

Body:
I'm trying to implement google captcha v2 on a website that gets a lot of spam mail. The captcha is showing and working, but the form can be submitted without pressing the captcha. I had a look for similar questions but couldn't find any that would help me.

It is google's captcha V2

Form:

<form action="mailer.php" method="post" onsubmit="return FrontPage_Form1_Validator(this)" language="JavaScript" name="FrontPage_Form1" enctype="multipart/form-data">
<input type="text" class="col-md-13 col-xs-12 name" name='name' placeholder='Name *'/>
<input type="text" class="col-md-13 col-xs-12 Email" name='Email' placeholder='Email *'/>
<input type="text" class="col-md-12 col-xs-12 Subject" name='Subject' placeholder='Subject'/>
<textarea type="text" class="col-md-12 col-xs-12 Message" name='Message' placeholder='Message *'></textarea>

mailer.php:

if ($_SERVER['REQUEST_METHOD'] == "POST") {
foreach ($_POST as $key => $value) {
    $msg .= ucfirst ($key) ." : ". $value . "\n";
}
}
else {

foreach ($_GET as $key => $value) {

    $msg .= ucfirst ($key) ." : ". $value . "\n";

}
}

//captcha section

$response = $_POST["g-recaptcha-response"];

$url = 'https://www.google.com/recaptcha/api/siteverify';

$data = array(
    'secret' => '6Ld-ryQUAAAAALpIkTPN82doQhCFmiWrC14_UbYk',
    'response' => $_POST['g-recaptcha-response'];
);
$options = array(
    'http' => array (
        'method' => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);

//end of captcha section

mail($to, $subject, $msg, $headers);

if ($forward == 1) {
header ("Location:$location");
}
else {
include("index.html");
header( 'Location: ' ) ;
}

`

Thank you. Any help is appreciated

I feel like I need to put the captcha code inside in if(isset())


问:
Celery: Task Singleton?
I have a task that I need to run asynchronously from the web page that triggered it.  This task runs rather long, and as the web page could be getting a lot of these requests, I'd like celery to only run one instance of this task at a given time.

Is there any way I can do this in Celery natively?  I'm tempted to create a database table that holds this state for all the tasks to communicate with, but it feels hacky.

答:
You can use memcache/redis for that.
There is an example on the celery official site - http://docs.celeryproject.org/en/latest/tutorials/task-cookbook.html

And if you prefer redis (This is a Django realization, but you can also easily modify it for your needs):

```<code>from django.core.cache import cache
from celery.utils.log import get_task_logger

logger = get_task_logger(__name__)

class SingletonTask(Task):
    def __call__(self, *args, **kwargs):
        lock = cache.lock(self.name)

        if not lock.acquire(blocking=False):
            logger.info("{} failed to lock".format(self.name))
            return

        try:
            super(SingletonTask, self).__call__(*args, **kwargs)
        except Exception as e:
            lock.release()
            raise e
        lock.release()
</code>```

And then use it as a base task:

```<code>@shared_task(base=SingletonTask)
def test_task():
    from time import sleep
    sleep(10)
</code>```

This realization is nonblocking. If you want next task to wait for the previous task change blocking=False to blocking=True and add timeout

Title: Celery: Task Singleton?

Body:
You can use memcache/redis for that.
There is an example on the celery official site - http://docs.celeryproject.org/en/latest/tutorials/task-cookbook.html

And if you prefer redis (This is a Django realization, but you can also easily modify it for your needs):

from django.core.cache import cache
from celery.utils.log import get_task_logger

logger = get_task_logger(__name__)

class SingletonTask(Task):
    def __call__(self, *args, **kwargs):
        lock = cache.lock(self.name)

        if not lock.acquire(blocking=False):
            logger.info("{} failed to lock".format(self.name))
            return

        try:
            super(SingletonTask, self).__call__(*args, **kwargs)
        except Exception as e:
            lock.release()
            raise e
        lock.release()

And then use it as a base task:

@shared_task(base=SingletonTask)
def test_task():
    from time import sleep
    sleep(10)

This realization is nonblocking. If you want next task to wait for the previous task change blocking=False to blocking=True and add timeout