问:
Name clash from implementing interface
I have spent a few hours reading Java documentation/Stackoverflow answers on generics and type erasure but I still don't understand the topic fully.
The problem is implementing the following simple interface:

```<code>public interface Stack {
void push(Object element); }
</code>```

I have implemented this in a simple generic class:

```<code>public class NodeStack<T> implements Stack {
private Node<T> top;
private int size;

public void push(T value) {
    if(this.size == 0) {
        this.top = new Node<>(value, null);
    } else {
        this.top = new Node<>(value, this.top);
    }
    this.size++;}
}
</code>```

When I attempt to compile this I get the compiler error messages:

```<code>NodeStack.java:10: error: NodeStack is not abstract and does not override abstract method push(Object) in Stack
public class NodeStack<T> implements Stack {
   ^
NodeStack.java:63: error: name clash: push(T) in NodeStack and push(Object) in Stack have the same erasure, yet neither overrides the other

    public void push(T value) {
                ^
where T is a type-variable:
    T extends Object declared in class NodeStack
2 errors
</code>```

I think this problem occurs because of type erasure - the push method in the class and the push method in the interface have the same signature after type erasure. What I don't understand is why this would be a problem. The push method implementation should have the same signature as the interface method, right? What am I missing here? Any help is greatly appreciated.

答:
You are trying to use method signature which has object and generic T, both are different does not match.

```<code>public interface Stack<T>
{
    void push(T element);
}
</code>```

And now your NodeStack class will be

```<code>public class NodeStack<T> implements Stack<T> {
</code>```

Title: Name clash from implementing interface

Body:
I have spent a few hours reading Java documentation/Stackoverflow answers on generics and type erasure but I still don't understand the topic fully.
The problem is implementing the following simple interface:

public interface Stack {
void push(Object element); }

I have implemented this in a simple generic class:

public class NodeStack<T> implements Stack {
private Node<T> top;
private int size;

public void push(T value) {
    if(this.size == 0) {
        this.top = new Node<>(value, null);
    } else {
        this.top = new Node<>(value, this.top);
    }
    this.size++;}
}

When I attempt to compile this I get the compiler error messages:

NodeStack.java:10: error: NodeStack is not abstract and does not override abstract method push(Object) in Stack
public class NodeStack<T> implements Stack {
   ^
NodeStack.java:63: error: name clash: push(T) in NodeStack and push(Object) in Stack have the same erasure, yet neither overrides the other

    public void push(T value) {
                ^
where T is a type-variable:
    T extends Object declared in class NodeStack
2 errors

I think this problem occurs because of type erasure - the push method in the class and the push method in the interface have the same signature after type erasure. What I don't understand is why this would be a problem. The push method implementation should have the same signature as the interface method, right? What am I missing here? Any help is greatly appreciated.

Body:
You are trying to use method signature which has object and generic T, both are different does not match.

public interface Stack<T>
{
    void push(T element);
}

And now your NodeStack class will be

public class NodeStack<T> implements Stack<T> {


来源: stackexchange

问:
python: why does random.shuffle change the array
I'm using random.shuffle to shuffle a 2D numpy array. I met with the following problem:

```<code>import numpy as np
from random import shuffle as sf

b = np.array([1,2,3,4,5])
print b
# [1 2 3 4 5]
sf(b)
print b
# [1 4 5 3 2]

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print a
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
sf(a)
print a
# [[1 2 3]
#  [4 5 6]
#  [1 2 3]]
</code>```

The result shows that when shuffling 1D array, everything is correct. But while shuffling 2D array, the result becomes strange.

Why is the third row of the original array thrown away and the first row duplicated by twice?

I know there could be solutions to solve this problem, such as firstly shuffle a 1D array indicating the row ids and then extract the 2D array in the order of the shuffled ids. But I do want to make clear what happens to the implementation of random.shuffle, or what's wrong with my code.

答:
Shuffle from the random module isn’t made to deal with numpy arrays since it’s not exactly the same as nested python lists. You should use the numpy.random module’s shuffle instead.

```<code>import numpy as np
from numpy.random import shuffle

arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
shuffle(arr)
print(arr)
# output:
# [[4 5 6]
# [1 2 3]
# [7 8 9]]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using random.shuffle to shuffle a 2D numpy array. I met with the following problem:

import numpy as np
from random import shuffle as sf

b = np.array([1,2,3,4,5])
print b
# [1 2 3 4 5]
sf(b)
print b
# [1 4 5 3 2]

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print a
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
sf(a)
print a
# [[1 2 3]
#  [4 5 6]
#  [1 2 3]]

The result shows that when shuffling 1D array, everything is correct. But while shuffling 2D array, the result becomes strange.

Why is the third row of the original array thrown away and the first row duplicated by twice?

I know there could be solutions to solve this problem, such as firstly shuffle a 1D array indicating the row ids and then extract the 2D array in the order of the shuffled ids. But I do want to make clear what happens to the implementation of random.shuffle, or what's wrong with my code.

Body:
Shuffle from the random module isn’t made to deal with numpy arrays since it’s not exactly the same as nested python lists. You should use the numpy.random module’s shuffle instead.

import numpy as np
from numpy.random import shuffle

arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
shuffle(arr)
print(arr)
# output:
# [[4 5 6]
# [1 2 3]
# [7 8 9]]


问:
disable swipe between tabs in android tablayout
I'm developing an android app that has a page with a tablayout including 2 tabs, a list page and a map (both are fragments). The list elements are viewpagers holding images, but when the user reaches the last image in the viewpager, the tablayout gets the next swipe event and it switches to the map. This also happens if the user tries to swipe the images starting at the very right side of the screen.

I'd like to switch of the swipe functionality between the tabs completely, but didn't find a way to do it so.

This is how I setup my tabs:

```<code>ViewPager fragmentPager = (ViewPager) findViewById(R.id.viewpager);
fragmentPager.setAdapter(new MyPagerAdapter);//extends FragmentPagerAdapter
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(fragmentPager);
</code>```

答:
you can do this with custom view pager.

Make a class Name Custom_viewpager and extends it in your XML also.

```<code>public class Custom_viewpager extends ViewPager {

private boolean enabled;

public Custom_viewpager(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.enabled = true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return enabled ? super.onTouchEvent(event) : false;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return enabled ? super.onInterceptTouchEvent(event) : false;
}

public void setPagingEnabled(boolean enabled) {
    this.enabled = enabled;
}

public boolean isPagingEnabled() {
    return enabled;
}
</code>```

when you want to disable swipe just add this two lines.

```<code>viewPager.setPagingEnabled(false);
viewPager.beginFakeDrag();
</code>```

Let me know if it helps. :)

Body:
I'm developing an android app that has a page with a tablayout including 2 tabs, a list page and a map (both are fragments). The list elements are viewpagers holding images, but when the user reaches the last image in the viewpager, the tablayout gets the next swipe event and it switches to the map. This also happens if the user tries to swipe the images starting at the very right side of the screen.

I'd like to switch of the swipe functionality between the tabs completely, but didn't find a way to do it so.

This is how I setup my tabs:

ViewPager fragmentPager = (ViewPager) findViewById(R.id.viewpager);
fragmentPager.setAdapter(new MyPagerAdapter);//extends FragmentPagerAdapter
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(fragmentPager);

Body:
you can do this with custom view pager.

Make a class Name Custom_viewpager and extends it in your XML also.

public class Custom_viewpager extends ViewPager {

private boolean enabled;

public Custom_viewpager(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.enabled = true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return enabled ? super.onTouchEvent(event) : false;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return enabled ? super.onInterceptTouchEvent(event) : false;
}

public void setPagingEnabled(boolean enabled) {
    this.enabled = enabled;
}

public boolean isPagingEnabled() {
    return enabled;
}

when you want to disable swipe just add this two lines.

viewPager.setPagingEnabled(false);
viewPager.beginFakeDrag();

Let me know if it helps. :)


问:
Extending interface with generic no longer assignable to parent
I recently upgraded to typescript 2.4 and I got several errors complaining that my types were no longer assignable.

Here is the scenario where I am encountering the error:

```<code>interface Parent {
    prop: any
}

interface Child extends Parent {
    childProp: any
}

type Foo<T> = <P extends Parent>(parent: P) => T

function createFooFunction<T>(arg: T): Foo<T> {
    // Error here!
    return (child: Child): T => {
        return arg;
    }
}
</code>```

In typescript 2.3 this is acceptable, but typescript 2.4 produces this error

```<code>Type '(child: Child) => T' is not assignable to type 'Foo<T>'.
Types of parameters 'child' and 'parent' are incompatible.
    Type 'P' is not assignable to type 'Child'.
    Type 'Parent' is not assignable to type 'Child'.
        Property 'childProp' is missing in type 'Parent'.
</code>```

In regards to the last line of the error, I noticed that if I make the Child's properties optional, then typescript will be satisfied, i.e. if I make this change

```<code>interface Child extends Parent {
    childProp?: any
}
</code>```

Although that is not an ideal fix, since in my case, childProp is required.

I also noticed that changing the Foo's argument type directly to Parent will also satisfy typescript, i.e. making this change

```<code>type Foo<T> = (parent: Parent) => T
</code>```

This isn't a fix either though, since I do not control the Foo type, nor the Parent. They both come from vendor .d files, so I cannot modify them.

But either way, I'm not sure I understand why this is an error. The Foo type is saying that it requires something that extends Parent, and Child is such an object, so why would typescript think its not assignable?

Edit: I've marked this as answered since adding the --noStrictGenericChecks flag will suppress the errors (accepted answer here). However, I would still like to know why this is an error in the first place since I'd rather keep the strict checks and refactor my code if its wrong, rather than just short circuiting it.

So to re-iterate the heart of the question, since Child extends Parent, why does typescript no longer think that Child is assignable to Parent, and in terms of OOP generics, why is that more correct than it was before?

答:
Version 2.4 introduces stricter checking for generics

Read this https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/ and look for the heading Stricter checking for generics

From the article:

As a temporary workaround for any breakage, you may be able to suppress some of these errors using the new --noStrictGenericChecks flag.

It also introduces strict contravariance for callbacks.

Body:
I recently upgraded to typescript 2.4 and I got several errors complaining that my types were no longer assignable.

Here is the scenario where I am encountering the error:

interface Parent {
    prop: any
}

interface Child extends Parent {
    childProp: any
}

type Foo<T> =
(parent: P) => T

function createFooFunction<T>(arg: T): Foo<T> {
    // Error here!
    return (child: Child): T => {
        return arg;
    }
}

In typescript 2.3 this is acceptable, but typescript 2.4 produces this error

Type '(child: Child) => T' is not assignable to type 'Foo<T>'.
Types of parameters 'child' and 'parent' are incompatible.
    Type 'P' is not assignable to type 'Child'.
    Type 'Parent' is not assignable to type 'Child'.
        Property 'childProp' is missing in type 'Parent'.

In regards to the last line of the error, I noticed that if I make the Child's properties optional, then typescript will be satisfied, i.e. if I make this change

interface Child extends Parent {
    childProp?: any
}

Although that is not an ideal fix, since in my case, childProp is required.

I also noticed that changing the Foo's argument type directly to Parent will also satisfy typescript, i.e. making this change

type Foo<T> = (parent: Parent) => T

This isn't a fix either though, since I do not control the Foo type, nor the Parent. They both come from vendor .d files, so I cannot modify them.

But either way, I'm not sure I understand why this is an error. The Foo type is saying that it requires something that extends Parent, and Child is such an object, so why would typescript think its not assignable?

Edit: I've marked this as answered since adding the --noStrictGenericChecks flag will suppress the errors (accepted answer here). However, I would still like to know why this is an error in the first place since I'd rather keep the strict checks and refactor my code if its wrong, rather than just short circuiting it.

So to re-iterate the heart of the question, since Child extends Parent, why does typescript no longer think that Child is assignable to Parent, and in terms of OOP generics, why is that more correct than it was before?


问:
How to delete column name
I want to delete to just column name (x,y,z), and use only data.

```<code>In [68]: df
Out[68]:
   x  y  z
0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0
</code>```

I want to print result to same as below.

```<code>Out[68]:

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

Is it possible? How can I do this?

答:
In pandas by default need column names.

But if really want 'remove' columns what is strongly not recommended, because get duplicated column names is possible assign empty strings:

```<code>df.columns = [''] * len(df.columns)
</code>```

But if need write df to file without columns and index add parameter header=False and index=False to to_csv or to_excel.

```<code>df.to_csv('file.csv', header=False, index=False)

df.to_excel('file.xlsx', header=False, index=False)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to delete column name

Body:
I want to delete to just column name (x,y,z), and use only data.

In [68]: df
Out[68]:
   x  y  z
0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0

I want to print result to same as below.

Out[68]:

0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0

Is it possible? How can I do this?

Body:
In pandas by default need column names.

But if really want 'remove' columns what is strongly not recommended, because get duplicated column names is possible assign empty strings:

df.columns = [''] * len(df.columns)

But if need write df to file without columns and index add parameter header=False and index=False to to_csv or to_excel.

df.to_csv('file.csv', header=False, index=False)

df.to_excel('file.xlsx', header=False, index=False)


问:
Bootstrap datepicker inside modal scrolling with parent page, not with modal
I have got a bootstrap template wherein I gotta use datepicker inside a modal. The content of modal is scrollable. When I click on datepicker field and scroll the page, the datepicker scrolls with the parent page reference while modal content are not at all scrolled. Also, when modal is scrolled, datepicker stays on "fixed" position (as parent page is not scrolled). Any idea on how to make modal popup as a parent reference for the datepicker in bootstrap?</p>

答:
Use the datepicker('place') option:</p>

```<code>$( "#model" ).scroll(function() {
    $('.datepicker').datepicker('place');
});
</code>```

Body:
Use the datepicker('place') option:

$( "#model" ).scroll(function() {
    $('.datepicker').datepicker('place');
});


问:
Detect undefined symbols in C header file
Suposse I coded a C library which provides a bunch of "public" functions, declared in a mylib.h header file. Those functions are supposedly implemented in (say) a mylib.c file which is compiled to a (say) static lib mylib.c -> mylib.o -> mylib.a.

Is there some way to detect that I forgot to provide the implementation of some declared function in mylib.h? (Yes, I know about unit testing, good practices, etc - and, yes, I understand the meaning of a plain function declaration in C).

Suppose mylib.h declares a void func1(); and this function was not coded in the provided library. This will trigger an error only  if the linker needs to use that function. Otherwise, it will compile ok and even without warnings - AFAIK. Is there a way (perhaps compiler dependent) to trigger a warning for declared but not implemented functions, or there is any other way to deal with this issue?

BTW: nm -u lists not all undefined declared functions, but only those "used" by the library, i.e., those functions that will trigger an error in the linking phase if not declared somewhere. (Which makes sense, the library object file does not know about header files, of course.)

答:
Is there some way to detect that I forgot to provide the implementation of some declared function in mylib.h?

Write the implementation first, then worry about header contents -- because that way, it can be flagged.

ContentLicense: CC BY-SA 2.5


问:
Duplicate files copied in APK META-INF/LICENSE
Error:Execution failed for task ':openpayandroid:transformResourcesWithMergeJavaResForRelease'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE
      File1: /Users/ederpadilla/Downloads/driveappuble-drive-android-484430cd00e7/openpayandroid/libs/jackson-core-2.8.2.jar
      File2: /Users/ederpadilla/Downloads/driveappuble-drive-android-484430cd00e7/openpayandroid/libs/jackson-core-asl-1.9.11.jar

答:
Add this code in your app gradle file

```<code>android {
    ...
    packagingOptions {
        exclude 'META-INF/LICENSE'
    }
}
</code>```

Body:
Add this code in your app gradle file

android {
    ...
    packagingOptions {
        exclude 'META-INF/LICENSE'
    }
}


问:
Change pdf file name in report definition Odoo 10
Given this report definition, how can I change the file name used in the PDF so it uses names such as "SO-001.pdf".

```<code><report
        id = "report_custom_sale_order"
        string = "Quotation / Order"
        model = "sale.order"
        report_type = "qweb-pdf"
        file = "custom_saleorder.report_saleorder"
        name = "custom_saleorder.report_saleorder"
        paperformat = "custom_saleorder.paperformat_a4"
/>
</code>```

Odoo 10.

Thanks

答:
Use attribute string.

```<code> <report id="action_report_followup"
   model="account_followup.followup"
    string="Follow-up Report"
    report_type="qweb-pdf"
    name="payment_followup.report_followup"
    file="payment_followup.report_followup"
     menu="True"/>
</code>```

Hope it will help you.

Body:
Given this report definition, how can I change the file name used in the PDF so it uses names such as "SO-001.pdf".

<report
        id = "report_custom_sale_order"
        string = "Quotation / Order"
        model = "sale.order"
        report_type = "qweb-pdf"
        file = "custom_saleorder.report_saleorder"
        name = "custom_saleorder.report_saleorder"
        paperformat = "custom_saleorder.paperformat_a4"
/>

Odoo 10.

Thanks

Body:
Use attribute string.

 <report id="action_report_followup"
   model="account_followup.followup"
    string="Follow-up Report"
    report_type="qweb-pdf"
    name="payment_followup.report_followup"
    file="payment_followup.report_followup"
     menu="True"/>

Hope it will help you.


问:
Can you run multiple app on 1 LAMP?
I'm newer at this and I was wondering if one LAMP instance or physical machine  (either or) can run multiple app such as NextCloud and Nagios for say.

Or if I have to deploy multiple LAMPs which at that point I'll be looking to use Docker containers.

Thanks.

答:
Simply Add another virtual host entry if in case you want to assign different domain name later :

```<code><VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/folder2
    <Directory /var/www/folder2>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        <IfModule mod_rewrite.c>
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ /index.php [QSA,L]
        </IfModule>
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

OR

if you just want access it just like example.com/folder than just add a folder inside the directory /var/www/folder1/ named folder2.

Title: Can you run multiple app on 1 LAMP?

Body:
Simply Add another virtual host entry if in case you want to assign different domain name later :

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/folder2
    <Directory /var/www/folder2>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        <IfModule mod_rewrite.c>
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ /index.php [QSA,L]
        </IfModule>
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

OR

if you just want access it just like example.com/folder than just add a folder inside the directory /var/www/folder1/ named folder2.


问:
Create swift closure and pass it to objective-c class as completion block
Now I'm adding Swift code on objective-C based iOS application.

But I have a problem in calling the objective-C method from Swift side.

I'd like to get and draw image on UIImageView in View or ViewController which is written with Swift.
On the other hand my wrapper class of Photos Library is written with objective-C.

My wrapper class of Photos Library is below.

・MyPhotoLibraryMgr.h

```<code>typedef void (^AppPhotoLibraryGetImageCompletion)(UIImage *image, NSError *error);

- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:(AppPhotoLibraryGetImageCompletion)completion;
</code>```

・MyPhotoLibraryMgr.m

```<code>- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:
(AppPhotoLibraryGetImageCompletion)completion
{
    PHAsset *asset = _myAsetsList[index];

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;

    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:targetSize
                                              contentMode:PHImageContentModeAspectFill
                                                  options:options
                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                NSError *error = [info objectForKey:PHImageErrorKey];
                                                if (error) {
                                                    NSLog(@"error=%@", error);
                                                }
                                                completion(result, error);
                                            }];
}
</code>```

I can get and draw image in View or ViewController written by objective-C like below,

・MyViewController.m

```<code>AppPhotoLibraryMgr *photoLibMgr = [AppPhotoLibraryMgr sharedInstance];
AppPhotoLibraryGetImageCompletion completion = ^(UIImage *image, NSError *error) {
                imageView.image = image;
};

[[AppPhotoLibraryMgr sharedInstance] getImageWithTarget:index
                                             targetSize:imageView.frame.size
                                             completion:completion];
</code>```

But I can't get image in View or ViewController written in Swift.

・MySwiftViewController.swift

```<code>let completion = {(image: UIImage, error: NSError) -> AppPhotoLibraryGetImageCompletion in
    let imageView = UIImageView(image: image)
}

photoLibMgr?.getImageWithTarget(index, targetSize: size, completion: completion)
</code>```

Error message from Xcode is

Cannot convert value of type 'UIImage, NSError ->
  AppPhotoLibraryGetImageCompletion" to expected argument type
  'AppPhotoLibraryGetImageCompletion'

答:
It should be typedef instead of Typedef. Move typedef on top of interface declare and don't declare it again:

```<code>typedef void (^AppPhotoLibraryGetImageCompletion)(UIImage *image, NSError *error);

@interface MyPhotoLibraryMgr....
</code>```

After the changes it should work similar in Swift, auto complete will change your AppPhotoLibraryGetImageCompletion to (image, error) {..}

Body:
Now I'm adding Swift code on objective-C based iOS application.

But I have a problem in calling the objective-C method from Swift side.

I'd like to get and draw image on UIImageView in View or ViewController which is written with Swift.
On the other hand my wrapper class of Photos Library is written with objective-C.

My wrapper class of Photos Library is below.

・MyPhotoLibraryMgr.h

typedef void (^AppPhotoLibraryGetImageCompletion)(UIImage *image, NSError *error);

- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:(AppPhotoLibraryGetImageCompletion)completion;

・MyPhotoLibraryMgr.m

- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:
(AppPhotoLibraryGetImageCompletion)completion
{
    PHAsset *asset = _myAsetsList[index];

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;

    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:targetSize
                                              contentMode:PHImageContentModeAspectFill
                                                  options:options
                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                NSError *error = [info objectForKey:PHImageErrorKey];
                                                if (error) {
                                                    NSLog(@"error=%@", error);
                                                }
                                                completion(result, error);
                                            }];
}

I can get and draw image in View or ViewController written by objective-C like below,

・MyViewController.m

AppPhotoLibraryMgr *photoLibMgr = [AppPhotoLibraryMgr sharedInstance];
AppPhotoLibraryGetImageCompletion completion = ^(UIImage *image, NSError *error) {
                imageView.image = image;
};

[[AppPhotoLibraryMgr sharedInstance] getImageWithTarget:index
                                             targetSize:imageView.frame.size
                                             completion:completion];

But I can't get image in View or ViewController written in Swift.

・MySwiftViewController.swift

let completion = {(image: UIImage, error: NSError) -> AppPhotoLibraryGetImageCompletion in
    let imageView = UIImageView(image: image)
}

photoLibMgr?.getImageWithTarget(index, targetSize: size, completion: completion)

Error message from Xcode is

Cannot convert value of type 'UIImage, NSError ->
  AppPhotoLibraryGetImageCompletion" to expected argument type
  'AppPhotoLibraryGetImageCompletion'

Body:
It should be typedef instead of Typedef. Move typedef on top of interface declare and don't declare it again:

typedef void (^AppPhotoLibraryGetImageCompletion)(UIImage *image, NSError *error);

@interface MyPhotoLibraryMgr....

After the changes it should work similar in Swift, auto complete will change your AppPhotoLibraryGetImageCompletion to (image, error) {..}


问:
What is the point of this line of code?
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php</p>

```<code>eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

答:
It is evaluating the string as PHP code.

But it seems to be making a variable equal itself? Weird.

OwnerDisplayName: mk

Title: What is the point of this line of code?

Body:
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php

eval ("\$text_including_tax = \"$text_including_tax\";");

OwnerDisplayName: alex


问:
Convert Date string in NodeIS
I have a TranDate "2017/07/05 12:12:22", i want to convert it to this style : 20170705121222, can you help me what function of nodejs can I use to do this issue ? Thank you !</p>

答:
Or you can use a module to handle it also:</p>

```<code>> var df = require('date-format')
> df('yyyyMMddhhmmss', new Date('2017 07 05 12:12:22'))
'20170705121222'
</code>```

Title: Convert Date string in NodeIS

Body:
Or you can use a module to handle it also:

> var df = require('date-format')
> df('yyyyMMddhhmmss', new Date('2017 07 05 12:12:22'))
'20170705121222'


问:
Cannot find the declaration of element 'company
I am trying to write XSD for the following XML, but it shows the error:-
Exception: cvc-elt.1.a: Cannot find the declaration of element 'company

company.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
    <Companies
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation = "http://www.w3schools.org companyxsd.xsd">

    <Company>
        <Companyname></Companyname>
        <address></address>
    </Company>

    <Department>
        <dname></dname>
        <deptphoneno></deptphoneno>
        <deptfaxno></deptfaxno>
        <deptemail></deptemail>
    </Department>

    <Employee>
        <empid></empid>
        <ename></ename>
        <emailid></emailid>
        <phoneno></phoneno>
    </Employee>

    <ContractEmployee>
        <name></name>
        <phoneno></phoneno>
    </ContractEmployee>

    </Companies>
</code>```

And following is my XSD file
companyxsd.xsd

```<code><?xml version = "1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
           elementFormDefault = "qualified">

<xs:element name = "Companies">
<xs:complexType>
    <xs:sequence>
        <xs:element maxOccurs = "unbounded" minOccurs = "1" name = "Comp"/>
    </xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name = "Company">
    <xs:sequence>
        <xs:element name = "Companyname" type = "xs:string"/>
        <xs:element name = "address" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "Department">
    <xs:sequence>
        <xs:element name = "dname" type = "xs:string"/>
        <xs:element name = "deptphoneno" type = "xs:string"/>
        <xs:element name = "deptfaxno" type = "xs:string"/>
        <xs:element name = "deptemail" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "Employee">
    <xs:sequence>
        <xs:element name = "empid" type = "xs:string"/>
        <xs:element name = "ename" type = "xs:string"/>
        <xs:element name = "emailid" type = "xs:string"/>
        <xs:element name = "phoneno" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "ContractEmployee">
    <xs:sequence>
        <xs:element name = "name" type = "xs:string"/>
        <xs:element name = "phoneno" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

</xs:schema>
</code>```

Please tell me, where I am wrong.. I have been trying to solve this from last few days and I am really stuck here.This ER diagram is used for the XML

答:
change schema as listed below you did mistake in companies element</p>

```<code>        <?xml version="1.0" encoding="UTF-8"?>
    <company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="companyxsd.xsd">
    <companyname>capgemini</companyname>
    <address>chalapathischool</address>
    <department>
    <dname>cse</dname>
    <deptphoneno>995674314</deptphoneno>
    <deptfaxno>08776</deptfaxno>
    <deptemail>gvn@gmail.com</deptemail>
    <employee>
    <empid>1</empid>
    <ename>tarun</ename>
    <emailid>tar@gmail.com</emailid>
    <phoneno>1234567890</phoneno>
    </employee>
    <contractemployee>
    <name>gvn</name>
    <phoneno>9989956882</phoneno>
    </contractemployee>
    </department>
    </company>

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="department" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"/>
<xs:element name="deptphoneno" type="xs:integer"/>
<xs:element name="deptfaxno" type="xs:long"/>
<xs:element name="deptemail" type="xs:string"/>
<xs:element name="employee" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:integer"/>
<xs:element name="ename" type="xs:string"/>
<xs:element name="emailid" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="contractemployee" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</code>```

Body:
I am trying to write XSD for the following XML, but it shows the error:-
Exception: cvc-elt.1.a: Cannot find the declaration of element 'company

company.xml

<?xml version="1.0" encoding="UTF-8"?>
    <Companies
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation = "http://www.w3schools.org companyxsd.xsd">

    <Company>
        <Companyname></Companyname>
        <address></address>
    </Company>

    <Department>
        <dname></dname>
        <deptphoneno></deptphoneno>
        <deptfaxno></deptfaxno>
        <deptemail></deptemail>
    </Department>

    <Employee>
        <empid></empid>
        <ename></ename>
        <emailid></emailid>
        <phoneno></phoneno>
    </Employee>

    <ContractEmployee>
        <name></name>
        <phoneno></phoneno>
    </ContractEmployee>

    </Companies>

And following is my XSD file
companyxsd.xsd

<?xml version = "1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
           elementFormDefault = "qualified">

<xs:element name = "Companies">
<xs:complexType>
    <xs:sequence>
        <xs:element maxOccurs = "unbounded" minOccurs = "1" name = "Comp"/>
    </xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name = "Company">
    <xs:sequence>
        <xs:element name = "Companyname" type = "xs:string"/>
        <xs:element name = "address" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "Department">
    <xs:sequence>
        <xs:element name = "dname" type = "xs:string"/>
        <xs:element name = "deptphoneno" type = "xs:string"/>
        <xs:element name = "deptfaxno" type = "xs:string"/>
        <xs:element name = "deptemail" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "Employee">
    <xs:sequence>
        <xs:element name = "empid" type = "xs:string"/>
        <xs:element name = "ename" type = "xs:string"/>
        <xs:element name = "emailid" type = "xs:string"/>
        <xs:element name = "phoneno" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name = "ContractEmployee">
    <xs:sequence>
        <xs:element name = "name" type = "xs:string"/>
        <xs:element name = "phoneno" type = "xs:string"/>
    </xs:sequence>
</xs:complexType>

</xs:schema>

Please tell me, where I am wrong.. I have been trying to solve this from last few days and I am really stuck here.This ER diagram is used for the XML

Body:
change schema as listed below you did mistake in companies element

        <?xml version="1.0" encoding="UTF-8"?>
    <company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="companyxsd.xsd">
    <companyname>capgemini</companyname>
    <address>chalapathischool</address>
    <department>
    <dname>cse</dname>
    <deptphoneno>995674314</deptphoneno>
    <deptfaxno>08776</deptfaxno>
    <deptemail>gvn@gmail.com</deptemail>
    <employee>
    <empid>1</empid>
    <ename>tarun</ename>
    <emailid>tar@gmail.com</emailid>
    <phoneno>1234567890</phoneno>
    </employee>
    <contractemployee>
    <name>gvn</name>
    <phoneno>9989956882</phoneno>
    </contractemployee>
    </department>
    </company>

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="department" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"/>
<xs:element name="deptphoneno" type="xs:integer"/>
<xs:element name="deptfaxno" type="xs:long"/>
<xs:element name="deptemail" type="xs:string"/>
<xs:element name="employee" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:integer"/>
<xs:element name="ename" type="xs:string"/>
<xs:element name="emailid" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="contractemployee" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>


问:
How to generate Request & Response templates from WSDL in python
I am trying to generate a request and response template from a WSDL.

I know SOAP UI can do this, but I need to use Python in my case.

I have seen that there is a python lib called zeep, but it seems to be targeted more towards setting up a soap client and performing calls.

How can I get the request from the WSDL?

Here is an example I have been using:

https://www.tutorialspoint.com/wsdl/wsdl_example.htm

答: You can create the request XML documents with zeep, see http://docs.python-zeep.org/en/master/client.html#creating-the-raw-xml-documents</p>


问:
SQL server Assertion failed error while sending mail with Excel or PDF attachments
I used to send mails from SQL server using the sp_send_dbmail with attachments.
But for the past 10 days the mails are not triggered. I checked the procedure and tried it without the attachments and it works. If an Excel or a PDF attachment is there, the procedure throws the below error...

```<code>Location:    SpcAlloc.cpp:914
Expression:  pPage->IsType (Page::TEXT_MIX_PAGE)
SPID:        89
Process ID:  2108
Msg 3624, Level 20, State 1, Procedure sp_send_dbmail, Line 449
A system assertion check has failed. Check the SQL Server error log for details. Typically,
an assertion failure is caused by a software bug or data corruption. To check for database
corruption, consider running DBCC CHECKDB. If you agreed to send dumps to Microsoft during
setup, a mini dump will be sent to Microsoft. An update might be available from Microsoft
in the latest Service Pack or in a QFE from Technical Support.
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command.  The results, if any, should be discarded.
</code>```

Any Suggestions ?

答:
you will see more details in sqlserver error log and errorlog points out to dump location as well..

Right now,here are your options

1.Try checking if you are on the latest version of sqlserver and if you are not try upgrading to latest CU or SP

2.If you get this error even after  upgrading to latest CU or SP,try contacting microsoft support

IF you are latest version of sqlserver,you will have more luck as it has some extensions like  SQL Server Diagnostics (Preview)   .Once you are done installing this extension, you will provide below screen to upload dump

after uploading,SSMS will analyze the dumps for you and present relevant KB's like below

Body:
I used to send mails from SQL server using the sp_send_dbmail with attachments.
But for the past 10 days the mails are not triggered. I checked the procedure and tried it without the attachments and it works. If an Excel or a PDF attachment is there, the procedure throws the below error...

Location:    SpcAlloc.cpp:914
Expression:  pPage->IsType (Page::TEXT_MIX_PAGE)
SPID:        89
Process ID:  2108
Msg 3624, Level 20, State 1, Procedure sp_send_dbmail, Line 449
A system assertion check has failed. Check the SQL Server error log for details. Typically,
an assertion failure is caused by a software bug or data corruption. To check for database
corruption, consider running DBCC CHECKDB. If you agreed to send dumps to Microsoft during
setup, a mini dump will be sent to Microsoft. An update might be available from Microsoft
in the latest Service Pack or in a QFE from Technical Support.
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command.  The results, if any, should be discarded.

Any Suggestions ?


问:
Json Joining as in SQL
i have json objects like

```<code>{"COLORS":[[1,red],[2,yellow],[3,orange]]}

{"FRUITS":[[1,apple,1],[2,banana,2],[3,orange,3], [4,grenade,1], [5,apple,2]]}
</code>```

i need to make them like:

```<code>{"FRUITS":[[1,apple,red],[2,banana,yellow],[3,orange,orange], [4,grenade,red], [5,apple,yellow]]}
</code>```

答:
Here is a simple solution using jq. It assumes that $colors and $fruits contain the JSON values for 'colors' and 'fruits' respectively:

```<code>$colors.COLORS | map( {(.[0]|tostring): .[1] } ) | add as $dict
| $fruits
| .FRUITS |= map( (.[2]) |= $dict[tostring] )
</code>```

The example below shows how to set $coloars and $fruits.

If your jq has INDEX/1, the first line above could be shortened to:

```<code>$colors.COLORS | INDEX(.[0]) | map_values(.[1]) as $dict
</code>```

Explanation

The first line produces a dictionary ($dict), which is then used to make the translation.

Example

Assuming colors.json and fruits.json hold valid JSON values corresponding to the example give in the question, and that program.jq holds the above jq program, the invocation:

```<code>jq -n --argfile colors colors.json --argfile fruits fruits.json -f program.jq
</code>```

yields:

```<code>{"FRUITS":[[1,"apple","red"],[2,"banana","yellow"],[3,"orange","orange"],[4,"grenade","red"],[5,"apple","yellow"]]}
</code>```

Title: Json Joining as in SQL

Body:
i have json objects like

{"COLORS":[[1,red],[2,yellow],[3,orange]]}

{"FRUITS":[[1,apple,1],[2,banana,2],[3,orange,3], [4,grenade,1], [5,apple,2]]}

i need to make them like:

{"FRUITS":[[1,apple,red],[2,banana,yellow],[3,orange,orange], [4,grenade,red], [5,apple,yellow]]}

Body:
Here is a simple solution using jq. It assumes that $colors and $fruits contain the JSON values for 'colors' and 'fruits' respectively:

$colors.COLORS | map( {(.[0]|tostring): .[1] } ) | add as $dict
| $fruits
| .FRUITS |= map( (.[2]) |= $dict[tostring] )

The example below shows how to set $coloars and $fruits.

If your jq has INDEX/1, the first line above could be shortened to:

$colors.COLORS | INDEX(.[0]) | map_values(.[1]) as $dict

Explanation

The first line produces a dictionary ($dict), which is then used to make the translation.

Example

Assuming colors.json and fruits.json hold valid JSON values corresponding to the example give in the question, and that program.jq holds the above jq program, the invocation:

jq -n --argfile colors colors.json --argfile fruits fruits.json -f program.jq

yields:

{"FRUITS":[[1,"apple","red"],[2,"banana","yellow"],[3,"orange","orange"],[4,"grenade","red"],[5,"apple","yellow"]]}


问:
Pick a random item from a list and then delete any subsequent list items containing the same words as the randomly picked item?
I'm making a script to create a food menu by randomly picking dishes off of a list 7 times. However, I would like to make it so that it doesn't pick any similar dishes. For instance, if 'Lamb Chops' was chosen as dish1, then dish2 would be a random item from the same list with all the options including 'lamb' and 'chops' removed. Then if dish2 was 'Spaghetti Bolognese', then dish3 would be chosen from the same list excluding 'lamb', 'chops', 'spaghetti', and 'bolognese', and so on and so on. Can anyone help?

-Thanks.

答:
I'm somewhat rusty with AppleScript, so excuse me if I make mistakes.

To break down what you must do,

1) Choose a random item

```<code>-- The initial menuItems we start off with
set menuItems to {"Lamb Chops", "Lamb", "Chops", "Spaghetti Bolognese", "Spaghetti", "Bolognese"}

set randomItemNum to random number from 1 to count of menuItems
set randomItem to item randomItemNum of menuItems as string
</code>```

2) Repeat through menuItems so we can exclude items that contain a word from randomItem
We'll use this subroutine to split strings:

```<code>on splitString(theString, theDelimiter)
    -- save delimiters to restore old settings
    set oldDelimiters to AppleScript's text item delimiters
    -- set delimiters to delimiter to be used
    set AppleScript's text item delimiters to theDelimiter
    -- create the array
    set theArray to every text item of theString
    -- restore the old setting
    set AppleScript's text item delimiters to oldDelimiters
    -- return the result
    return theArray
end splitString
</code>```

and now we can easily split strings, lets continue with the reconstruction of the menu:

```<code>-- This loops through menuItems, and we can use menuItem to access the current looped item
-- We'll use this to reconstruct menuItems, but excluding what we need

set newMenuItems to {}
repeat with menuItem in menuItems
    -- Get words from randomItem
    -- For example, if randomItem is "Lamb Chops", it will return {"Lamb","Chops"}
    set menuItemWords to splitString(randomItem, " ")

    -- This is the conditional that will determine to include menuItem or not
    -- Feel free to change this to get the outcome you want
    if menuItemWords does not contain menuItem as string and menuItem does not contain menuItemWords then

        -- And this conditional to not re-add the randomItem
        -- However, it does it to one word items in the previous if statement
        -- Note: Without using "as string" to menuItem it doesn't work correctly, not sure why
       if menuItem as string is not equal to randomItem then
            set the end of newMenuItems to menuItem
        end

    end

end repeat
-- Now we've finished creating a new menu with the changes we want, set it to the main one
set menuItems to newMenuItems
</code>```

And, now it should work.

You might also want to examine the results easily, in which case, you can use this subroutine to concatenate the arrays into a string:

```<code>on arrayToString(theArray, theSeperator)
    set arrayString to ""
    repeat with theItem in theArray
        if arrayString is equal to "" then
            set arrayString to theItem
        else
            set arrayString to arrayString & theSeperator & theItem
        end if
    end repeat
end arrayToString
</code>```

and just display the results before you set the menu to the new one.

```<code>........

display alert "I've picked " & randomItem & " for you." message "Old menu:
" & arrayToString(menuItems, ", ") & "
New menu:
" & arrayToString(newMenuItems, ", ")

-- Now we've finished creating a new menu with the changes we want and displayed the results, set it to the main one
set menuItems to newMenuItems
</code>```

You can also loop through the menu items 7 times by warping the code in a repeat 7 times after specifying the initial menuItem, and a check to exit the repeat if menuItems is empty, like this:

```<code>on splitString(theString, theDelimiter)
    ...
end splitString

-- The initial menuItems we start off with
set menuItems to {"Lamb Chops", "Lamb", "Chops", "Spaghetti Bolognese", "Spaghetti", "Bolognese"}

-- Repeat statement to loop 7 times
repeat 7 times
  -- If menuItems is empty, exit the repeat
  if count of menuItems is 0 then
      exit repeat
  end if

  set randomItemNum to random number from 1 to count of menuItems
  set randomItem to item randomItemNum of menuItems as string

  set newMenuItems to {}
  repeat with menuItem in menuItems
      ...
  end repeat
  -- Now we've finished creating a new menu with the changes we want, set it to the main one
  set menuItems to newMenuItems

-- This is the end of loop for 7 times
end repeat
</code>```

I hope this helps.

If you need any other help, or there's an error, please comment below and l'll try my best.

Edit:

Here is the complete code that should do what you need, it repeats 7 times and shows the user a list of the selected dishes when completed:

```<code>on splitString(theString, theDelimiter)
    -- save delimiters to restore old settings
    set oldDelimiters to AppleScript's text item delimiters
    -- set delimiters to delimiter to be used
    set AppleScript's text item delimiters to theDelimiter
    -- create the array
    set theArray to every text item of theString
    -- restore the old setting
    set AppleScript's text item delimiters to oldDelimiters
    -- return the result
    return theArray
end splitString

on arrayToString(theArray, theSeperator)
    set arrayString to ""
    repeat with theItem in theArray
        if arrayString is equal to "" then
            set arrayString to theItem
        else
            set arrayString to arrayString & theSeperator & theItem
        end if
    end repeat
end arrayToString

-- The menu after you finish looping to show the user
set yourMenu to {}

-- The initial menuItems we start off with
set menuItems to {"Lamb Chops", "Lamb", "Chops", "Spaghetti Bolognese", "Spaghetti", "Bolognese"}

-- Repeat statement to loop 7 times
repeat 7 times
    -- If menuItems is empty, exit the repeat
    if (count of menuItems) is 0 then
        exit repeat
    end if

    set randomItemNum to random number from 1 to count of menuItems
    set randomItem to item randomItemNum of menuItems as string

    -- This loops through menuItems, and we can use menuItem to access the current looped item
    -- We'll use this to reconstruct menuItems, but excluding what we need
    set newMenuItems to {}
    repeat with menuItem in menuItems
        -- Get words from randomItem
        -- For example, if randomItem is "Lamb Chops", it will return {"Lamb","Chops"}
        set menuItemWords to splitString(randomItem, " ")

        -- This is the conditional that will determine to include menuItem or not
        -- Feel free to change this to get the outcome you want
        if menuItemWords does not contain menuItem as string and menuItem does not contain menuItemWords then

            -- And this conditional to not re-add the randomItem
            -- However, it does it to one word items in the previous if statement
            -- Note: Without using "as string" to menuItem it doesn't work correctly, not sure why
            if menuItem as string is not equal to randomItem then
                set the end of newMenuItems to menuItem
            end if

        end if

    end repeat

    -- Now we've finished creating a new menu with the changes we want, set it to the main one
    set menuItems to newMenuItems
    set the end of yourMenu to randomItem

    -- This is the end of loop for 7 times
end repeat

set itemSelected to (choose from list yourMenu with prompt "Here's your menu.")
display alert "You selected " & itemSelected & "."
</code>```

Body:
I'm somewhat rusty with AppleScript, so excuse me if I make mistakes.

To break down what you must do,

1) Choose a random item

-- The initial menuItems we start off with
set menuItems to {"Lamb Chops", "Lamb", "Chops", "Spaghetti Bolognese", "Spaghetti", "Bolognese"}

set randomItemNum to random number from 1 to count of menuItems
set randomItem to item randomItemNum of menuItems as string

2) Repeat through menuItems so we can exclude items that contain a word from randomItem
We'll use this subroutine to split strings:

on splitString(theString, theDelimiter)
    -- save delimiters to restore old settings
    set oldDelimiters to AppleScript's text item delimiters
    -- set delimiters to delimiter to be used
    set AppleScript's text item delimiters to theDelimiter
    -- create the array
    set theArray to every text item of theString
    -- restore the old setting
    set AppleScript's text item delimiters to oldDelimiters
    -- return the result
    return theArray
end splitString

and now we can easily split strings, lets continue with the reconstruction of the menu:

-- This loops through menuItems, and we can use menuItem to access the current looped item
-- We'll use this to reconstruct menuItems, but excluding what we need

set newMenuItems to {}
repeat with menuItem in menuItems
    -- Get words from randomItem
    -- For example, if randomItem is "Lamb Chops", it will return {"Lamb","Chops"}
    set menuItemWords to splitString(randomItem, " ")

    -- This is the conditional that will determine to include menuItem or not
    -- Feel free to change this to get the outcome you want
    if menuItemWords does not contain menuItem as string and menuItem does not contain menuItemWords then

        -- And this conditional to not re-add the randomItem
        -- However, it does it to one word items in the previous if statement
        -- Note: Without using "as string" to menuItem it doesn't work correctly, not sure why
       if menuItem as string is not equal to randomItem then
            set the end of newMenuItems to menuItem
        end

    end

end repeat
-- Now we've finished creating a new menu with the changes we want, set it to the main one
set menuItems to newMenuItems

And, now it should work.

You might also want to examine the results easily, in which case, you can use this subroutine to concatenate the arrays into a string:

on arrayToString(theArray, theSeperator)
    set arrayString to ""
    repeat with theItem in theArray
        if arrayString is equal to "" then
            set arrayString to theItem
        else
            set arrayString to arrayString & theSeperator & theItem
        end if
    end repeat
end arrayToString

and just display the results before you set the menu to the new one.

........

display alert "I've picked " & randomItem & " for you." message "Old menu:
" & arrayToString(menuItems, ", ") & "
New menu:
" & arrayToString(newMenuItems, ", ")

-- Now we've finished creating a new menu with the changes we want and displayed the results, set it to the main one
set menuItems to newMenuItems

You can also loop through the menu items 7 times by warping the code in a repeat 7 times after specifying the initial menuItem, and a check to exit the repeat if menuItems is empty, like this:

on splitString(theString, theDelimiter)
    ...
end splitString

-- The initial menuItems we start off with
set menuItems to {"Lamb Chops", "Lamb", "Chops", "Spaghetti Bolognese", "Spaghetti", "Bolognese"}

-- Repeat statement to loop 7 times
repeat 7 times
  -- If menuItems is empty, exit the repeat
  if count of menuItems is 0 then
      exit repeat
  end if

  set randomItemNum to random number from 1 to count of menuItems
  set randomItem to item randomItemNum of menuItems as string

  set newMenuItems to {}
  repeat with menuItem in menuItems
      ...
  end repeat
  -- Now we've finished creating a new menu with the changes we want, set it to the main one
  set menuItems to newMenuItems

-- This is the end of loop for 7 times
end repeat

I hope this helps.

If you need any other help, or there's an error, please comment below and l'll try my best.

Edit:

Here is the complete code that should do what you need, it repeats 7 times and shows the user a list of the selected dishes when completed:

on splitString(theString, theDelimiter)
    -- save delimiters to restore old settings
    set oldDelimiters to AppleScript's text item delimiters
    -- set delimiters to delimiter to be used
    set AppleScript's text item delimiters to theDelimiter
    -- create the array
    set theArray to every text item of theString
    -- restore the old setting
    set AppleScript's text item delimiters to oldDelimiters
    -- return the result
    return theArray
end splitString

on arrayToString(theArray, theSeperator)
    set arrayString to ""
    repeat with theItem in theArray
        if arrayString is equal to "" then
            set arrayString to theItem
        else
            set arrayString to arrayString & theSeperator & theItem
        end if
    end repeat
end arrayToString

-- The menu after you finish looping to show the user
set yourMenu to {}

-- The initial menuItems we start off with
set menuItems to {"Lamb Chops", "Lamb", "Chops", "Spaghetti Bolognese", "Spaghetti", "Bolognese"}

-- Repeat statement to loop 7 times
repeat 7 times
    -- If menuItems is empty, exit the repeat
    if (count of menuItems) is 0 then
        exit repeat
    end if

    set randomItemNum to random number from 1 to count of menuItems
    set randomItem to item randomItemNum of menuItems as string

    -- This loops through menuItems, and we can use menuItem to access the current looped item
    -- We'll use this to reconstruct menuItems, but excluding what we need
    set newMenuItems to {}
    repeat with menuItem in menuItems
        -- Get words from randomItem
        -- For example, if randomItem is "Lamb Chops", it will return {"Lamb","Chops"}
        set menuItemWords to splitString(randomItem, " ")

        -- This is the conditional that will determine to include menuItem or not
        -- Feel free to change this to get the outcome you want
        if menuItemWords does not contain menuItem as string and menuItem does not contain menuItemWords then

            -- And this conditional to not re-add the randomItem
            -- However, it does it to one word items in the previous if statement
            -- Note: Without using "as string" to menuItem it doesn't work correctly, not sure why
            if menuItem as string is not equal to randomItem then
                set the end of newMenuItems to menuItem
            end if

        end if

    end repeat

    -- Now we've finished creating a new menu with the changes we want, set it to the main one
    set menuItems to newMenuItems
    set the end of yourMenu to randomItem

    -- This is the end of loop for 7 times
end repeat

set itemSelected to (choose from list yourMenu with prompt "Here's your menu.")
display alert "You selected " & itemSelected & "."


问:
How to disable single option of a select in cakephp with form helper?
I need to disable a single particular option of a selectbox with form helper in cakephp. I am creating selectbox with below way :

```<code><?php
    $options = array(1=>'Option 1',2=>'Option 2',3=>'Option 3')
    echo $this->Form->input('Model.field', array('options' => $options, 'empty' => '--select--'));
?>
</code>```

So now i need to disable Option 2 in selectbox like :

```<code><select id="dropdown" name="dropdown">
    <option value="1">Option1</option>
    <option value="2" disabled="disabled">Option2</option>
    <option value="3">Option3</option>
</select>
</code>```

So is there any disable property available in options array to disable single options?

Thanks in adavance.

答:
As per the reference of CakePHP.

Your can add disabled attribute like the below:

```<code><?php
    $options = array(1=>'Option 1',2=>'Option 2',3=>'Option 3')
    echo $this->Form->input('Model.field', array('options' => $options, 'disabled' => array(2), 'empty' => '--select--'));
?>
</code>```

Hope this help for you.

Body:
I need to disable a single particular option of a selectbox with form helper in cakephp. I am creating selectbox with below way :

<?php
    $options = array(1=>'Option 1',2=>'Option 2',3=>'Option 3')
    echo $this->Form->input('Model.field', array('options' => $options, 'empty' => '--select--'));
?>

So now i need to disable Option 2 in selectbox like :

<select id="dropdown" name="dropdown">
    <option value="1">Option1</option>
    <option value="2" disabled="disabled">Option2</option>
    <option value="3">Option3</option>
</select>

So is there any disable property available in options array to disable single options?

Thanks in adavance.

Body:
As per the reference of CakePHP.

Your can add disabled attribute like the below:

<?php
    $options = array(1=>'Option 1',2=>'Option 2',3=>'Option 3')
    echo $this->Form->input('Model.field', array('options' => $options, 'disabled' => array(2), 'empty' => '--select--'));
?>

Hope this help for you.


问:
API integration using RxJava and Retrofit
Hi  i am new to RxJava and Retrofit, and i am having API's like generate OTP and Check OTP , how to call these API's in android project for OTP generation and validation. I have to give mobile number, generated OTP has to received to mobile after this OTP validation also have to takes place.</p>

答:
API's like generate OTP and Check OTP are also very much similar to other APIs,

In retrofit, you call generate OTP service call with call back once response success, you alert user to enter OTP and then verify with the OTP by calling Check OTP API inside the success block (once after user submits the OTP).


问:
How to create Triangle shaped drawable?
I'm trying to draw a triangle shape in my XML layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="135%"
            android:pivotY="1%"
            android:toDegrees="45">
            <shape android:shape="rectangle">
                <solid android:color="@color/red" />
            </shape>
        </rotate>
    </item>
</layer-list>
</code>```

My expectation is to build my drawable like below image's top right corner.
I have to add this drawable in list item.

答:
   drawable-backround_triangle.xml

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="250%"
            android:pivotY="80%">
            <shape android:shape="rectangle">
                <solid android:color="@color/colorAccent" />
            </shape>
        </rotate>
    </item>
</layer-list>
</code>```

then make your view as below example:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:cardCornerRadius="4dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="false">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background_triangle">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="@dimen/dp8"
            android:weightSum="1">

            <LinearLayout
                android:id="@+id/img_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:orientation="vertical">

                <de.hdodenhof.circleimageview.CircleImageView
                    android:id="@+id/contact_img"
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="@dimen/dp8"
                    android:src="@drawable/ic_cars" />
            </LinearLayout>

            <RelativeLayout
                android:id="@+id/content_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="@dimen/dp8"
                android:layout_toRightOf="@+id/img_view">

                <TextView
                    android:id="@+id/tv_request_status"
                    style="@style/txtview_standard_widget"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_marginBottom="@dimen/dp8"
                    android:text="Pending"
                    android:textColor="@color/colorAccent" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/tv_request_status"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Phone" />

                        <TextView
                            android:id="@+id/tv_phone_number"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="Phone" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Email" />

                        <TextView
                            android:id="@+id/tv_email"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="joe@gmail.com" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Age" />

                        <TextView
                            android:id="@+id/tv_age"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="Phone" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="4dp"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Gender" />

                        <TextView
                            android:id="@+id/tv_gender"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="Phone" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Efficiency" />

                        <TextView
                            android:id="@+id/tv_efficiency"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="75%" />
                    </LinearLayout>
                </LinearLayout>
            </RelativeLayout>
        </RelativeLayout>
    </RelativeLayout>

</android.support.v7.widget.CardView>
</code>```

Title: How to create Triangle shaped drawable?

Body:
I'm trying to draw a triangle shape in my XML layout.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="135%"
            android:pivotY="1%"
            android:toDegrees="45">
            <shape android:shape="rectangle">
                <solid android:color="@color/red" />
            </shape>
        </rotate>
    </item>
</layer-list>

My expectation is to build my drawable like below image's top right corner.
I have to add this drawable in list item.

Body:
   drawable-backround_triangle.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="250%"
            android:pivotY="80%">
            <shape android:shape="rectangle">
                <solid android:color="@color/colorAccent" />
            </shape>
        </rotate>
    </item>
</layer-list>

then make your view as below example:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:cardCornerRadius="4dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="false">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background_triangle">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="@dimen/dp8"
            android:weightSum="1">

            <LinearLayout
                android:id="@+id/img_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:orientation="vertical">

                <de.hdodenhof.circleimageview.CircleImageView
                    android:id="@+id/contact_img"
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="@dimen/dp8"
                    android:src="@drawable/ic_cars" />
            </LinearLayout>

            <RelativeLayout
                android:id="@+id/content_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="@dimen/dp8"
                android:layout_toRightOf="@+id/img_view">

                <TextView
                    android:id="@+id/tv_request_status"
                    style="@style/txtview_standard_widget"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_marginBottom="@dimen/dp8"
                    android:text="Pending"
                    android:textColor="@color/colorAccent" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/tv_request_status"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Phone" />

                        <TextView
                            android:id="@+id/tv_phone_number"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="Phone" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Email" />

                        <TextView
                            android:id="@+id/tv_email"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="joe@gmail.com" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Age" />

                        <TextView
                            android:id="@+id/tv_age"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="Phone" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="4dp"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Gender" />

                        <TextView
                            android:id="@+id/tv_gender"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="Phone" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/dp4"
                        android:layout_marginTop="@dimen/dp4"
                        android:weightSum="1">

                        <TextView
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.4"
                            android:text="Efficiency" />

                        <TextView
                            android:id="@+id/tv_efficiency"
                            style="@style/txtview_standard_widget"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.6"
                            android:text="75%" />
                    </LinearLayout>
                </LinearLayout>
            </RelativeLayout>
        </RelativeLayout>
    </RelativeLayout>

</android.support.v7.widget.CardView>


问:
How to convert yuy2 to a BITMAP in C++
I'm using a security camera DLL to retreive the image from the camera. The DLL call a function of my program passing the image buffer as a parameter, but the image is in yuy2 format. I need to convert this buffer to RGB, but I tried every formula I found on Internet with no success. Every example I tried (including http://msdn.microsoft.com/en-us/library/aa904813(VS.80).aspx#yuvformats_2) gives me wrong colors.

I'm able to convert the buffer to a BW image using only the Y component of the pixel, but I really need the color picture. I debugged (assembly only) the DLL that shows the image in the screen and it uses DirectDraw to do this.

答:
You will have to write your own converter.  GDI+ doesn't know how to deal with YUY2 bitmaps.

Look here.

Please note that 2 pixels share same color values and have different luminance values.

Here are some formulas to help you write your converter.

Title: How to convert yuy2 to a BITMAP in C++


问:
UIDatePicker not showing up in UITextField. Swift 3
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

```<code>import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}
</code>```

答:
https://github.com/yudiz-solutions/PickerDemo
please try this library, its provide all pickers and easy to implements with callback </p>

Body:
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}


问:
Build Succeeded, but no .lib file gets created
I inherited a substantial amount of code, including a visual studio project that is supposed to (as best as I can tell) build a .lib file.  Visual studio says "... Generating Code... Creating Library... Creating browse information file...", and at the end, it says the build succeeded.  In the release/debug folder, it has a bunch of .obj files, but it doesn't have a .lib file.  What could I be missing?

Thanks!

答: .lib will not get generated if you miss to add prefix __declspec(dllexport)  for methods.</p>