问:
android.content.res.Resources$NotFoundException, android.view.InflateException with ImageButton
I receive the error below, mostly on Android 4.1 and 4.4:

```<code>    java.lang.RuntimeException: Unable to create service se.weblink.weblinkunified.services.FloatingWindowService: android.view.InflateException: Binary XML file line #68: Error inflating class <unknown>
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2406)
at android.app.ActivityThread.access$1700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #68: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:666)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:691)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at se.weblink.weblinkunified.services.FloatingWindowService.addViewToWindow(FloatingWindowService.java:122)
at se.weblink.weblinkunified.services.FloatingWindowService.onCreate(FloatingWindowService.java:92)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2396)
... 10 more
</code>```

The addViewToWindow function:

```<code>    final LayoutInflater layoutInflater = LayoutInflater.from(this);
    popupWindow = layoutInflater.inflate(R.layout.window_floating_call, null);

    final WindowManager.LayoutParams params = setupLayoutParams();

    final View.OnClickListener clickListener = getViewClickListener();
    final View.OnTouchListener touchListener = getTouchListener(params);
    popupWindow.setOnClickListener(clickListener);
    popupWindow.setOnTouchListener(touchListener);

    final View overlayView = popupWindow.findViewById(R.id.overlay_view);
    overlayView.setOnClickListener(clickListener);
    overlayView.setOnTouchListener(touchListener);

    final View topContainer = popupWindow.findViewById(R.id.call_top_container);

    buttonContainer = (LinearLayout) popupWindow.findViewById(R.id.call_bottom_container);
    buttonContainer.addView(getActiveCallButtons());

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final Resources resources = getResources();

    topContainer.setBackgroundColor(sharedPreferences.getInt(Constants.THEME_COLOR_PRIMARY, resources.getColor(R.color.accent_color_default)));

    setupCloseButton();

    windowManager.addView(popupWindow, params);
    popupWindow.setTranslationY(Tools.getDensityIndependentSize(-120, resources));
    popupWindow.setVisibility(View.GONE);
</code>```

And the xml file "window_floating_call":

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout       xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">

<RelativeLayout
    android:id="@+id/call_top_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:background="@color/accent_color_default"
    >
    <ImageView
        android:id="@+id/contact_image"
        android:layout_width="54dp"
        android:layout_height="54dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/ic_contact_picture"
        />
    <TextView
        android:id="@+id/contact_initial_label"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:gravity="center"
        android:layout_marginRight="10dp"
        android:textSize="25dp"
        android:fontFamily="sans-serif-light"/>
    <TextView
        android:id="@+id/incoming_call_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dp"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/contact_image"
        android:textColor="@color/text_color_bright"
        android:text="@string/incoming_call"
        android:textSize="10sp"
        android:fontFamily="sans-serif"/>
    <TextView
        android:id="@+id/contact_name_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/incoming_call_label"
        android:layout_marginTop="4dp"
        android:layout_toRightOf="@+id/contact_image"
        android:textColor="@color/text_color_bright"
        android:textSize="18sp"
        android:fontFamily="sans-serif"/>

    <TextView
        android:id="@+id/contact_number_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/contact_image"
        android:gravity="top"
        android:layout_below="@+id/contact_name_label"
        android:fontFamily="sans-serif-light"
        android:textSize="14sp"
        android:textColor="@color/text_color_bright"/>
    <View
        android:id="@+id/overlay_view"
        android:layout_width="match_parent"
        android:layout_height="54dp"/>
    <ImageButton
        android:id="@+id/close_button"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_action_cancel"
        android:alpha="0.7"
        style="@style/Base.Widget.AppCompat.ActionButton"/>
</RelativeLayout>
<LinearLayout
    android:id="@+id/call_bottom_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/call_top_container"
    android:orientation="vertical"
    android:weightSum="1"
    >

</LinearLayout>
</code>```

I can't figure out what causes the error. The problem does not occur on Android 5.1. And I don't seem to get why this code wouldn't be able to run on Android 4.1, 4.2, 4.4.

I appreciate if someone could help me. Thanks in advance!

Forgot to include the android.content.res.Resources$NotFoundException error. But the exception says that the resource file is not a drawable. I have the image ic_action_cancel in all other drawable folders (drawable-hdpi, drawable-mdpi etc.) except the main drawable folder(drawable). I tried adding the .png file to the main folder but it did not work.

答:
I've faced the same problem as yours.I firstly used my inflateUtils that write by myself.

The code is:

```<code>public static View inflate(int id) {
    return View.inflate(getContext(), id, null);
}
</code>```

And the getContext() method return a applicationContext. And it occurred InflateExcepition.

And now I change to use View.inflate(context, resId, null), and the context is my activity. And it worked fun now! hope that can help you.

sorry for my poor English!

Body:
I receive the error below, mostly on Android 4.1 and 4.4:

    java.lang.RuntimeException: Unable to create service se.weblink.weblinkunified.services.FloatingWindowService: android.view.InflateException: Binary XML file line #68: Error inflating class <unknown>
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2406)
at android.app.ActivityThread.access$1700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #68: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:666)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:691)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at se.weblink.weblinkunified.services.FloatingWindowService.addViewToWindow(FloatingWindowService.java:122)
at se.weblink.weblinkunified.services.FloatingWindowService.onCreate(FloatingWindowService.java:92)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2396)
... 10 more

The addViewToWindow function:

    final LayoutInflater layoutInflater = LayoutInflater.from(this);
    popupWindow = layoutInflater.inflate(R.layout.window_floating_call, null);

    final WindowManager.LayoutParams params = setupLayoutParams();

    final View.OnClickListener clickListener = getViewClickListener();
    final View.OnTouchListener touchListener = getTouchListener(params);
    popupWindow.setOnClickListener(clickListener);
    popupWindow.setOnTouchListener(touchListener);

    final View overlayView = popupWindow.findViewById(R.id.overlay_view);
    overlayView.setOnClickListener(clickListener);
    overlayView.setOnTouchListener(touchListener);

    final View topContainer = popupWindow.findViewById(R.id.call_top_container);

    buttonContainer = (LinearLayout) popupWindow.findViewById(R.id.call_bottom_container);
    buttonContainer.addView(getActiveCallButtons());

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final Resources resources = getResources();

    topContainer.setBackgroundColor(sharedPreferences.getInt(Constants.THEME_COLOR_PRIMARY, resources.getColor(R.color.accent_color_default)));

    setupCloseButton();

    windowManager.addView(popupWindow, params);
    popupWindow.setTranslationY(Tools.getDensityIndependentSize(-120, resources));
    popupWindow.setVisibility(View.GONE);

And the xml file "window_floating_call":

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout       xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">

<RelativeLayout
    android:id="@+id/call_top_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:background="@color/accent_color_default"
    >
    <ImageView
        android:id="@+id/contact_image"
        android:layout_width="54dp"
        android:layout_height="54dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/ic_contact_picture"
        />
    <TextView
        android:id="@+id/contact_initial_label"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:gravity="center"
        android:layout_marginRight="10dp"
        android:textSize="25dp"
        android:fontFamily="sans-serif-light"/>
    <TextView
        android:id="@+id/incoming_call_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dp"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/contact_image"
        android:textColor="@color/text_color_bright"
        android:text="@string/incoming_call"
        android:textSize="10sp"
        android:fontFamily="sans-serif"/>
    <TextView
        android:id="@+id/contact_name_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/incoming_call_label"
        android:layout_marginTop="4dp"
        android:layout_toRightOf="@+id/contact_image"
        android:textColor="@color/text_color_bright"
        android:textSize="18sp"
        android:fontFamily="sans-serif"/>

    <TextView
        android:id="@+id/contact_number_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/contact_image"
        android:gravity="top"
        android:layout_below="@+id/contact_name_label"
        android:fontFamily="sans-serif-light"
        android:textSize="14sp"
        android:textColor="@color/text_color_bright"/>
    <View
        android:id="@+id/overlay_view"
        android:layout_width="match_parent"
        android:layout_height="54dp"/>
    <ImageButton
        android:id="@+id/close_button"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_action_cancel"
        android:alpha="0.7"
        style="@style/Base.Widget.AppCompat.ActionButton"/>
</RelativeLayout>
<LinearLayout
    android:id="@+id/call_bottom_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/call_top_container"
    android:orientation="vertical"
    android:weightSum="1"
    >

</LinearLayout>

I can't figure out what causes the error. The problem does not occur on Android 5.1. And I don't seem to get why this code wouldn't be able to run on Android 4.1, 4.2, 4.4.

I appreciate if someone could help me. Thanks in advance!

Forgot to include the android.content.res.Resources$NotFoundException error. But the exception says that the resource file is not a drawable. I have the image ic_action_cancel in all other drawable folders (drawable-hdpi, drawable-mdpi etc.) except the main drawable folder(drawable). I tried adding the .png file to the main folder but it did not work.

Body:
I've faced the same problem as yours.I firstly used my inflateUtils that write by myself.

The code is:

public static View inflate(int id) {
    return View.inflate(getContext(), id, null);
}

And the getContext() method return a applicationContext. And it occurred InflateExcepition.

And now I change to use View.inflate(context, resId, null), and the context is my activity. And it worked fun now! hope that can help you.

sorry for my poor English!


来源: stackexchange

问:
Where is the words in ' ' located?
I am learning php, (absolute beginner) and want to know where the words in '' are located. I downloaded a code from online for a login system and am trying to learn how it works. Here is the code portion:

```<code><?php

// any HTML input *must* be HTML-escaped to prevent the user from injecting malicious JavaScript code
function html_escape($raw_input, $encoding)
{
return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}

/* Displays user information and some useful messages */
session_start();

if ($_SESSION['logged_in'] != 1) {
$first_name = 'Guest, Please Login or Sign Up to Play!';
$last_name = '';
}
else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
}
?>
</code>```

So where it says, "if ($_SESSION['logged_in'] != 1) {", when it says logged_in, where would that be defined? Is it defined in another file with the $logged_in, or what?

Also, i found some file where it says "$_SESSION['logged_in'] = true;" but i don't know if it means something, if it does please tell me!

Thanks so much.

(i'm a beginner so go easy on me please)

答:
You can store data in $_SESSION variables after session_start(); and assign values to it with:

$_SESSION['keyname'] = 'value';

You can write apostrophe (') or double quote (") to save string variables.
More informations here: http://php.net/manual/de/reserved.variables.session.php

Your code if ($_SESSION['logged_in'] != 1) is just a boolean check if $_SESSION['logged_in'] is set to 1 (true) or 0 (false).
So it checks your $_SESSION array with the key logged_in if 1 is set or not.

I hope I could help you with that?

ContentLicense: CC BY-SA 3.0

Title: Where is the words in ' ' located?

Body:
I am learning php, (absolute beginner) and want to know where the words in '' are located. I downloaded a code from online for a login system and am trying to learn how it works. Here is the code portion:

<?php

// any HTML input *must* be HTML-escaped to prevent the user from injecting malicious JavaScript code
function html_escape($raw_input, $encoding)
{
return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}

/* Displays user information and some useful messages */
session_start();

if ($_SESSION['logged_in'] != 1) {
$first_name = 'Guest, Please Login or Sign Up to Play!';
$last_name = '';
}
else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
}
?>

So where it says, "if ($_SESSION['logged_in'] != 1) {", when it says logged_in, where would that be defined? Is it defined in another file with the $logged_in, or what?

Also, i found some file where it says "$_SESSION['logged_in'] = true;" but i don't know if it means something, if it does please tell me!

Thanks so much.

(i'm a beginner so go easy on me please)


问:
Swift 3.1 deprecates initialize(). How can I achieve the same thing?
Objective-C declares a class function, initialize(), that is run once for each class, before it is used. It is often used as an entry point for exchanging method implementations (swizzling), among other things.

Swift 3.1 deprecates this function with a warning:

Method 'initialize()' defines Objective-C class method 'initialize',
  which is not guaranteed to be invoked by Swift and will be disallowed
  in future versions

How can this be resolved, while still maintaining the same behaviour and features that I currently implement using the initialize() entry point?

答:
My approach is essentially the same as adib's. Here's an example from a desktop application that uses Core Data; the goal here is to register our custom transformer before any code mentions it:

```<code>@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    override init() {
        super.init()
        AppDelegate.doInitialize
    }

    static let doInitialize : Void = {
        // set up transformer
        ValueTransformer.setValueTransformer(DateToDayOfWeekTransformer(), forName: .DateToDayOfWeekTransformer)
    }()

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

The nice thing is that this works for any class, just as initialize did, provided you cover all your bases — that is, you must implement every initializer. Here's an example of a text view that configures its own appearance proxy once before any instances have a chance to appear onscreen; the example is artificial but the encapsulation is extremely nice:

```<code>class CustomTextView : UITextView {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame:frame, textContainer: textContainer)
        CustomTextView.doInitialize
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        CustomTextView.doInitialize
    }

    static let doInitialize : Void = {
        CustomTextView.appearance().backgroundColor = .green
    }()

}
</code>```

That demonstrates the advantage of this approach much better than the app delegate does. There is only one app delegate instance, so the problem isn't very interesting; but there can be many CustomTextView instances. Nevertheless, the line CustomTextView.appearance().backgroundColor = .green will be executed only once, as the first instance is created, because it is part of the initializer for a static property. That is very similar to the behavior of the class method initialize.

Body:
My approach is essentially the same as adib's. Here's an example from a desktop application that uses Core Data; the goal here is to register our custom transformer before any code mentions it:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    override init() {
        super.init()
        AppDelegate.doInitialize
    }

    static let doInitialize : Void = {
        // set up transformer
        ValueTransformer.setValueTransformer(DateToDayOfWeekTransformer(), forName: .DateToDayOfWeekTransformer)
    }()

    // ...
}

The nice thing is that this works for any class, just as initialize did, provided you cover all your bases — that is, you must implement every initializer. Here's an example of a text view that configures its own appearance proxy once before any instances have a chance to appear onscreen; the example is artificial but the encapsulation is extremely nice:

class CustomTextView : UITextView {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame:frame, textContainer: textContainer)
        CustomTextView.doInitialize
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        CustomTextView.doInitialize
    }

    static let doInitialize : Void = {
        CustomTextView.appearance().backgroundColor = .green
    }()

}

That demonstrates the advantage of this approach much better than the app delegate does. There is only one app delegate instance, so the problem isn't very interesting; but there can be many CustomTextView instances. Nevertheless, the line CustomTextView.appearance().backgroundColor = .green will be executed only once, as the first instance is created, because it is part of the initializer for a static property. That is very similar to the behavior of the class method initialize.


问:
How to convert lowercase string to uppercase string without toUppercase() function
```<code>function alpha()
{
    var a=prompt("Enter String: ");

    for(var b=[i=0];c=a.charCodeAt(i);)
    {
        b[i++]=String.fromCharCode(c|(c>96 && c<123));
    }
    alert(b.join(""))
}
console.log(alpha());
</code>```

<p>So far some letters in the code change when I run this but for some reason it is not changing the string characters to all uppercase. (Example of output; I type "hi" into the prompt and the alert outputs "i" so the h disappears for some reason. </p>

答:
```<code>function alpha()
{
    var a=prompt("Enter String: ");
    var output="";
    for(var x=0;x<a.length;x++)
            output+=String.fromCharCode(a.charCodeAt(x)>96 && a.charCodeAt(x)<123 ? a.charCodeAt(x)-32: a.charCodeAt(x))
    return output;
}
console.log("--" + alpha());
</code>```

Just get the ascii code for each char, and if it ranges between 97 to 122 ( a to z ) deduct 32 from val to get the corresponding upper case char. Hope this helps.

Body:
function alpha()
{
    var a=prompt("Enter String: ");

    for(var b=[i=0];c=a.charCodeAt(i);)
    {
        b[i++]=String.fromCharCode(c|(c>96 && c<123));
    }
    alert(b.join(""))
}
console.log(alpha());

So far some letters in the code change when I run this but for some reason it is not changing the string characters to all uppercase. (Example of output; I type "hi" into the prompt and the alert outputs "i" so the h disappears for some reason.

Body:
function alpha()
{
    var a=prompt("Enter String: ");
    var output="";
    for(var x=0;x<a.length;x++)
            output+=String.fromCharCode(a.charCodeAt(x)>96 && a.charCodeAt(x)<123 ? a.charCodeAt(x)-32: a.charCodeAt(x))
    return output;
}
console.log("--" + alpha());

Just get the ascii code for each char, and if it ranges between 97 to 122 ( a to z ) deduct 32 from val to get the corresponding upper case char. Hope this helps.


问:
Run new conversation in current
I use that PHP Telegram SDK: https://github.com/akalongman/php-telegram-bot

How I can run a new Conversation in current Conversation? I have a KeyboardButtons and when user clicks on "Feedback" button, bot starts the new dialog (conversation) like "write your message for admins". I have a StartCommand with code:

```<code><?php
namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\InlineKeyboard;
use Longman\TelegramBot\Entities\InlineKeyboardButton;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Entities\KeyboardButton;
use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Request;

class StartCommand extends SystemCommand
{
    protected $name = 'start';
    protected $description = 'Start command';
    protected $usage = '/start';
    protected $version = '1.1.0';

    public function execute()
    {
        $message = $this->getMessage();
        $chat = $message->getChat();
        $user = $message->getFrom();
        $text = trim($message->getText(true));
        $chat_id = $chat->getId();
        $user_id = $user->getId();

        $data = [
            'chat_id' => $chat_id,
        ];

        if ($chat->isGroupChat() || $chat->isSuperGroup()) {
            $data['reply_markup'] = Keyboard::forceReply(['selective' => true]);
        }

        // Conversation start
        $this->conversation = new Conversation($user_id, $chat_id, $this->getName());
        $notes = &$this->conversation->notes;
        !is_array($notes) && $notes = [];
        // cache data from the tracking session if any
        $state = 0;
        if (isset($notes['state'])) {
            $state = $notes['state'];
        }
        $result = Request::emptyResponse();

        switch ($state) {
            case 0:
                $keyboards = [];
                $keyboards[] = new Keyboard(
                        ['Information'],
                        ['Books', 'Feedback'],
                        ['Hide menu']
                    );

                $keyboard = $keyboards[0]
                        ->setResizeKeyboard(true)
                        ->setOneTimeKeyboard(false)
                        ->setSelective(false);

                if ($text === '') {
                    $notes['state'] = 0;
                    $this->conversation->update();
                    $data['text']         = 'Please choose a section:';

                    $data['reply_markup'] = $keyboard;
                    $result = Request::sendMessage($data);
                }
                elseif ($text === 'Information') {
                    $this->conversation->update();
                    $data['text'] = file_get_contents(__DIR__ . '/../../other/texts/infrormation.txt');
                    $data['reply_markup'] = $keyboard;
                    $result = Request::sendMessage($data);
                }
                elseif ($text === 'Books') {
                    $this->conversation->update();
                    $data['text'] = file_get_contents(__DIR__ . '/../../other/texts/books.txt');
                    $data['reply_markup'] = $keyboard;
                    $result = Request::sendMessage($data);
                }
                elseif ($text === 'Feedback') {
                    /**
                     * HERE NEED START NEW CONSERVATION
                     * LIKE THESE (StartCommand or SurveyCommand)
                     */
                }
                elseif ($text === 'Hide menu') {
                    $this->conversation->stop();
                    $data['text'] = 'Done!';
                    $data['reply_markup'] = Keyboard::remove();
                    $result = Request::sendMessage($data);
                }
                $notes['name'] = $text;
                $text          = '';
        }
        return $result;
    }
}
</code>```

答:
One of many solutions is in creating dedicated group for this conversation. For redirecting to this group just use invite link (you can get it from group description) and provide it in bot's message if ReplyKeyboardMarkup used or url field of button for InlineKeyboardMarkup (preferred in my opinion).

Also you can use forwardMessage. When user hit the Feedback button let your bot send "write your message for admins" as you said and let it be with ForceReply option. After this you need to check your received messages for reply_to_message field is not null. If so - then get this message for forwarding to admins group (or channel).

Title: Run new conversation in current

Body:
I use that PHP Telegram SDK: https://github.com/akalongman/php-telegram-bot

How I can run a new Conversation in current Conversation? I have a KeyboardButtons and when user clicks on "Feedback" button, bot starts the new dialog (conversation) like "write your message for admins". I have a StartCommand with code:

<?php
namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\InlineKeyboard;
use Longman\TelegramBot\Entities\InlineKeyboardButton;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Entities\KeyboardButton;
use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Request;

class StartCommand extends SystemCommand
{
    protected $name = 'start';
    protected $description = 'Start command';
    protected $usage = '/start';
    protected $version = '1.1.0';

    public function execute()
    {
        $message = $this->getMessage();
        $chat = $message->getChat();
        $user = $message->getFrom();
        $text = trim($message->getText(true));
        $chat_id = $chat->getId();
        $user_id = $user->getId();

        $data = [
            'chat_id' => $chat_id,
        ];

        if ($chat->isGroupChat() || $chat->isSuperGroup()) {
            $data['reply_markup'] = Keyboard::forceReply(['selective' => true]);
        }

        // Conversation start
        $this->conversation = new Conversation($user_id, $chat_id, $this->getName());
        $notes = &$this->conversation->notes;
        !is_array($notes) && $notes = [];
        // cache data from the tracking session if any
        $state = 0;
        if (isset($notes['state'])) {
            $state = $notes['state'];
        }
        $result = Request::emptyResponse();

        switch ($state) {
            case 0:
                $keyboards = [];
                $keyboards[] = new Keyboard(
                        ['Information'],
                        ['Books', 'Feedback'],
                        ['Hide menu']
                    );

                $keyboard = $keyboards[0]
                        ->setResizeKeyboard(true)
                        ->setOneTimeKeyboard(false)
                        ->setSelective(false);

                if ($text === '') {
                    $notes['state'] = 0;
                    $this->conversation->update();
                    $data['text']         = 'Please choose a section:';

                    $data['reply_markup'] = $keyboard;
                    $result = Request::sendMessage($data);
                }
                elseif ($text === 'Information') {
                    $this->conversation->update();
                    $data['text'] = file_get_contents(__DIR__ . '/../../other/texts/infrormation.txt');
                    $data['reply_markup'] = $keyboard;
                    $result = Request::sendMessage($data);
                }
                elseif ($text === 'Books') {
                    $this->conversation->update();
                    $data['text'] = file_get_contents(__DIR__ . '/../../other/texts/books.txt');
                    $data['reply_markup'] = $keyboard;
                    $result = Request::sendMessage($data);
                }
                elseif ($text === 'Feedback') {
                    /**
                     * HERE NEED START NEW CONSERVATION
                     * LIKE THESE (StartCommand or SurveyCommand)
                     */
                }
                elseif ($text === 'Hide menu') {
                    $this->conversation->stop();
                    $data['text'] = 'Done!';
                    $data['reply_markup'] = Keyboard::remove();
                    $result = Request::sendMessage($data);
                }
                $notes['name'] = $text;
                $text          = '';
        }
        return $result;
    }
}

ContentLicense: CC BY-SA 4.0


答:
As Barmar mentioned in the comments above:

Subtract 32 from the character code if the character is between 97 and 123.

You can make your looping logic a little clearer with a split-map-join combination.

Since you can also compare single-character strings in JavaScript, like 'a' < 'b', this can further reduce the amount of code needed to handle the conversion of  character codes.

function alpha (s) {
  return s.split('').map(function (c) {
    return 'a' <= c && c <= 'z' ? String.fromCharCode(c.charCodeAt(0) - 32) : c
  }).join('')
}

console.log(
  alpha(prompt("Enter String: "))
)```

Title: How to convert lowercase string to uppercase string without toUppercase() function


问:
Fill out datetime-local field with existing localdatetime object in jsp using spring form
This is an editing form that will have all the fields filled out using existing data from database.  Regular text input fills out just fine but I am having issue doing the same with datetime.             </p>

```<code><sf:form class="form-horizontal" role="form" modelAttribute="sighting" action="edit" method="POST">
    <div class="form-group">
          <label for="Reported Time" class="col-md-4 col-sm-4 col-xs-12 control-label">
               Reported Time:
          </label>
          <div class="col-md-4 col-sm-6 col-xs-12">
               <sf:input type="datetime-local" class="add-form form-control" path="sightingDate" name="sightingDate"/>
          </div>
    </div>
</code>```

答:
Use value attribute,

<input type="datetime-local" name="sightingDate" value="sighting.sightingDate">

Body:
This is an editing form that will have all the fields filled out using existing data from database.  Regular text input fills out just fine but I am having issue doing the same with datetime.

<sf:form class="form-horizontal" role="form" modelAttribute="sighting" action="edit" method="POST">

               Reported Time:

               <sf:input type="datetime-local" class="add-form form-control" path="sightingDate" name="sightingDate"/>


问:
Internet Explorer Smooth Scrolling Detection
This is a two part question.  I building a web page and I need to know:

Is there a way to detect if IE has smooth scrolling enabled (if so, how)?

Is there a way to force IE to turn off smooth scrolling for my web page?

To be clear, I'm not asking how to turn off smooth scrolling for the whole computer.  I am the developer developing a web page that will only work properly if smooth scrolling is disabled.

答:
I'm just chirping in here 5 years later...

You can remove smooth scrolling in IE if you manually override the event yourself.

```<code>if(navigator.userAgent.match(/Trident\/7\./)) {
    $('body').on("mousewheel", function () {
        event.preventDefault();
        var wd = event.wheelDelta;
        var csp = window.pageYOffset;
        window.scrollTo(0, csp - wd);
    });
}
</code>```

This was sufficient for me to resolve my IE smooth scrolling issues.
Blatantly stolen from Here

Body:
I'm just chirping in here 5 years later...

You can remove smooth scrolling in IE if you manually override the event yourself.

if(navigator.userAgent.match(/Trident\/7\./)) {
    $('body').on("mousewheel", function () {
        event.preventDefault();
        var wd = event.wheelDelta;
        var csp = window.pageYOffset;
        window.scrollTo(0, csp - wd);
    });
}

This was sufficient for me to resolve my IE smooth scrolling issues.
Blatantly stolen from Here


问:
Android: strange thing about loading contact info
I created an app. It is working on htc desire hd, but when i tested it on ZTE Blade, a strange problem appeared. In my app when user selects a contact name from a spinner a menu appears. In the menu the user can send sms to the user, call him/her or just look at his/her contact info. On HTC Desire HD, everything is working fine. On ZTE there seems to be an exasperating problem with the contact info button: In certain cases when user selects a contact and wants to see his contact info, some other contact's info is shown. So I select Pete from my spinner but I get Dave's contact info. In other cases I select Tom from the spinner and I get Tom's contact info. The problem is not existing on my HTC. I couldn't figure out what causes the problem. By the way, my contact list on HTC is populated also from gmail and facebook and the app still working fine, while the contact list of the ZTE has never seen any gmail or facebook accounts (i am not entirely sure about this).

This is the code i am using to get to the contact info:

```<code>         infobtn.setOnClickListener(new View.OnClickListener()
         {
            public void onClick(View v)
            {
                ContentResolver cr = getContentResolver();
                Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

                if (cur.getCount() > 0)
                {

                    while (cur.moveToNext()) {
                    id_contact = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    name_contact = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        if (name_contact.equals(name1))
                        {
                        Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id_contact}, null);
                           id_contact2 = id_contact;

                            while (pCur.moveToNext()){
                            }
                        pCur.close();
                        }
                    }
                    Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/" + id_contact2));
                    startActivity(intent_contacts);
                }

            }
         });
</code>```

答:
instead of using "contacts/people/xxx", try using contactsContract.Contacts.CONTENT_URI.

basically, you want to replace.

```<code>Uri contactUri = Uri.parse("content://contacts/people/" + id_contact2));
</code>```

with

```<code>Uri contactUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,
    id_contact2);
</code>```

Another thing to note is that "id_contact2" may be changed if a sync occurs before you use it (like when google sync merges a contact). To prevent this, it might be better to use a LookupKey instead.

```<code>ContactsContract.Contacts.LOOKUP_KEY
</code>```

and retrieve using

```<code>Uri contactUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI,
    yourContactLookupKey);
</code>```

Body:
I created an app. It is working on htc desire hd, but when i tested it on ZTE Blade, a strange problem appeared. In my app when user selects a contact name from a spinner a menu appears. In the menu the user can send sms to the user, call him/her or just look at his/her contact info. On HTC Desire HD, everything is working fine. On ZTE there seems to be an exasperating problem with the contact info button: In certain cases when user selects a contact and wants to see his contact info, some other contact's info is shown. So I select Pete from my spinner but I get Dave's contact info. In other cases I select Tom from the spinner and I get Tom's contact info. The problem is not existing on my HTC. I couldn't figure out what causes the problem. By the way, my contact list on HTC is populated also from gmail and facebook and the app still working fine, while the contact list of the ZTE has never seen any gmail or facebook accounts (i am not entirely sure about this).

This is the code i am using to get to the contact info:

         infobtn.setOnClickListener(new View.OnClickListener()
         {
            public void onClick(View v)
            {
                ContentResolver cr = getContentResolver();
                Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

                if (cur.getCount() > 0)
                {

                    while (cur.moveToNext()) {
                    id_contact = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    name_contact = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        if (name_contact.equals(name1))
                        {
                        Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id_contact}, null);
                           id_contact2 = id_contact;

                            while (pCur.moveToNext()){
                            }
                        pCur.close();
                        }
                    }
                    Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/" + id_contact2));
                    startActivity(intent_contacts);
                }

            }
         });

Body:
instead of using "contacts/people/xxx", try using contactsContract.Contacts.CONTENT_URI.

basically, you want to replace.

Uri contactUri = Uri.parse("content://contacts/people/" + id_contact2));

with

Uri contactUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,
    id_contact2);

Another thing to note is that "id_contact2" may be changed if a sync occurs before you use it (like when google sync merges a contact). To prevent this, it might be better to use a LookupKey instead.

ContactsContract.Contacts.LOOKUP_KEY

and retrieve using

Uri contactUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI,
    yourContactLookupKey);


问:
No type definitions in pre-defined IDL FILE
Firstly,

Using plain C++, without ATL, MFC attempting to use COM Object interface.

Using oleview (OLE/COM Object viewer) - used to engineer the IDL code.

At this stage, using MIDL Compiler, now I'm having trouble trying to produce the following:

Syntax on cmd line:

midl /nologo /env win32 /tlb ".\S8_.tlb" /h ".\S8_.h" /iid ".\S8_i.c" S8.idl

A corresponding .TLB (Type Library)

A .H (header)

An IID definitions include file (*_i.c)

A proxy (*_p.c)

MIDL compiler error:

S8.IDL(513) : error MIDL2025 : syntax error : expecting a type specification near "S8SimObject"

```<code>    HRESULT LinkSimObjects(
                    [in] S8SimObject* SourceObject, ####line 513 ####
                    [in] S8SimObject* DestObject,
                    [in] float TravelTime);
</code>```

答:
Well, I do not really understand your question here, but following should help:

Public enum definitions need to have their own uuid to be really public.

I've seen that those enum definitions don't go into the type-library unless they are actually used in some interface method.  I do not know the reason for this, probably I missed something simple (like adding that enum to a library block, or whatever).

short usually means a short integer, not a single-precision floating-point number.

The equivalent of float is single in VB, but as I've seen on other questions of you, I suspect you actually meant replacing single with float.

By the way, I'd recommend to post one minimal (compilable) IDL file (stripped of most definitions), which resembles more or less what you're trying to compile.  This helps against some confusion, as you're for instance using IS8Simulation in your text, but S8SimObject in your copied IDL snippet.  And it would also help if you specify the expected result, and the unexpected (for you) error.

Edit

Well, this compile error you now inserted is simple: S8SimObject is not defined.  You need to always refer to the interface in the method declarations (IS8Simulation), never to the coclass which implements the interface.

As you said you're changing an existing IDL file here: What is the basic goal? If the original IDL file always uses S8SimObject, maybe the only problem is that the definition of S8SimObject is not included at the top of the IDL file?  If you've the type-library defining S8SimObject around, you can export the IDL of this interface by using OleView.

OwnerDisplayName: Atklin

ContentLicense: CC BY-SA 2.5

Body:
Firstly,

Using plain C++, without ATL, MFC attempting to use COM Object interface.

Using oleview (OLE/COM Object viewer) - used to engineer the IDL code.

At this stage, using MIDL Compiler, now I'm having trouble trying to produce the following:

Syntax on cmd line:

midl /nologo /env win32 /tlb ".\S8_.tlb" /h ".\S8_.h" /iid ".\S8_i.c" S8.idl

A corresponding .TLB (Type Library)

A .H (header)

An IID definitions include file (*_i.c)

A proxy (*_p.c)

MIDL compiler error:

S8.IDL(513) : error MIDL2025 : syntax error : expecting a type specification near "S8SimObject"

    HRESULT LinkSimObjects(
                    [in] S8SimObject* SourceObject, ####line 513 ####
                    [in] S8SimObject* DestObject,
                    [in] float TravelTime);

LastEditorDisplayName: Atklin

OwnerDisplayName: gimpf

LastEditorDisplayName: gimpf


问:
Visual Studio 2008 - Toolbar missing 'Release' / 'Debug' dropdown build configuration
how to enable the dropdown that shows build mode 'release/debug' ?
I have set the 'show advanced build configuration' option. I added the 'configuration manager' to the build toolbar but in previous versions we could do this by using the drop-down control.

TIA

答:
To add the Solution Configuration onto your Toolbar, try the following:

View|Toolbars|Customize,
then select the Commands tab,
select the Build category and
drag the Solution Configuration and drop it onto your toolbar


问:
Google Play Console API level 26+
I try to upload a beta version of an app on Google Play Console. I got this error message:

This configuration cannot be published for the following reason(s):

   It is forbidden that a device upgrading from API levels in range 14-25 to API levels in range 26+ should downgrade from version 118018 to version 118008, which would occur when

     Release track containing any of [BETA] and

     Screen layouts containing any of [small, normal, large, xlarge] and

     Features containing all of [android.hardware.FAKETOUCH,   android.hardware.screen.PORTRAIT]

I'm looking for this error for a few hours, I'm out of ideas...

Edit:
Here is my build.gradle:

Pastebin link

答:
According to doc you cannot release or publish an Apk for Android O until the release.

You cannot publish your app with this configuration. The “O” version
  is a provisional API level that is usable only for development and
  testing during the Android O Developer Preview. You must wait to
  publish your Android O changes until the final API level is released,
  and then update your configuration again at that time.

More information here.

Title: Google Play Console API level 26+


问:
python regex to find the substring from the string
I have a string:

```<code> <robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">
</code>```

I want to get the value of "generated", but with below code, it doesn't work

```<code>import re
doc=r'<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'
match = re.match(r'generated="(\d+ \d+:\d+:\d+.\d+)',doc)
</code>```

the value of match is none. can anyone help?

答:
re.match matches only at the beginning of the string. Use re.search instead which matches not only at the beginning, but matches anywhere.

```<code>>>> import re
>>> doc=r'<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'
>>> re.search(r'generated="(\d+ \d+:\d+:\d+\.\d+)',doc)
<_sre.SRE_Match object at 0x1010505d0>

>>> re.search(r'generated="(\d+ \d+:\d+:\d+\.\d+)',doc).group()
'generated="20170330 17:19:11.956'

>>> re.search(r'generated="(\d+ \d+:\d+:\d+\.\d+)',doc).group(1)
'20170330 17:19:11.956'
</code>```

See search() vs. match() from re module documentation

Body:
I have a string:

 <robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">

I want to get the value of "generated", but with below code, it doesn't work

import re
doc=r'<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'
match = re.match(r'generated="(\d+ \d+:\d+:\d+.\d+)',doc)

the value of match is none. can anyone help?

Body:
re.match matches only at the beginning of the string. Use re.search instead which matches not only at the beginning, but matches anywhere.

>>> import re
>>> doc=r'<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'
>>> re.search(r'generated="(\d+ \d+:\d+:\d+\.\d+)',doc)
<_sre.SRE_Match object at 0x1010505d0>

>>> re.search(r'generated="(\d+ \d+:\d+:\d+\.\d+)',doc).group()
'generated="20170330 17:19:11.956'

>>> re.search(r'generated="(\d+ \d+:\d+:\d+\.\d+)',doc).group(1)
'20170330 17:19:11.956'

See search() vs. match() from re module documentation


问:
Error loading MySQLdb module: No module named 'MySQLdb'
I have tried a lot to solve this issue but I did not solve it. I have searched a lot on google and stackoverflow, no option is working for me. Please help me. Thanks in advance. I am using django 1.10, python 3.4.
I have tried :

pip install mysqldb.

pip install mysql.

pip install mysql-python.

pip install MySQL-python.

easy_install mysql-python.

easy_install MySQL-python.

Anything else left ?

```<code>      C:\Users\benq\Desktop\dimo-develop\Project>python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0332D348>
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 25, in <module>
    import MySQLdb as Database
ImportError: No module named 'MySQLdb'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python34\lib\site-packages\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Python34\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "C:\Python34\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Python34\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Python34\lib\site-packages\django\db\models\base.py", line 108, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Python34\lib\site-packages\django\db\models\base.py", line 299, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Python34\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Python34\lib\site-packages\django\db\__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Python34\lib\site-packages\django\db\utils.py", line 212, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Python34\lib\site-packages\django\db\utils.py", line 116, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 28, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'
</code>```

答:
MySQLdb is the interface to MySQL database. As mentioned by other posts, MySQLdb doesn't support Python 3.x. I used PyMySQL as the replacement. You need to install it first:

```<code>pip install PyMySQL
</code>```

The next step is to replace 'MySQLdb' with 'pymysql' in all the codes, which is intimidating. Luckily, PyMySQL can be loaded as MySQLdb dyanamically. In order to achieve it in Django, you need to add the following lines to __init__.py file under the dir of the project's default app (If your have a project named 'myproject', add lines to myproject/myproject/init.py):

```<code>import pymysql
pymysql.install_as_MySQLdb()
</code>```

This __init__.py would be executed when you run the Django project, and MySQLdb will be replaced. You problem is then solved.

Body:
I have tried a lot to solve this issue but I did not solve it. I have searched a lot on google and stackoverflow, no option is working for me. Please help me. Thanks in advance. I am using django 1.10, python 3.4.
I have tried :

pip install mysqldb.

pip install mysql.

pip install mysql-python.

pip install MySQL-python.

easy_install mysql-python.

easy_install MySQL-python.

Anything else left ?

      C:\Users\benq\Desktop\dimo-develop\Project>python manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0332D348>
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 25, in <module>
    import MySQLdb as Database
ImportError: No module named 'MySQLdb'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python34\lib\site-packages\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Python34\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "C:\Python34\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Python34\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Python34\lib\site-packages\django\db\models\base.py", line 108, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Python34\lib\site-packages\django\db\models\base.py", line 299, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Python34\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Python34\lib\site-packages\django\db\__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Python34\lib\site-packages\django\db\utils.py", line 212, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Python34\lib\site-packages\django\db\utils.py", line 116, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Python34\lib\site-packages\django\db\backends\mysql\base.py", line 28, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'

Body:
MySQLdb is the interface to MySQL database. As mentioned by other posts, MySQLdb doesn't support Python 3.x. I used PyMySQL as the replacement. You need to install it first:

pip install PyMySQL

The next step is to replace 'MySQLdb' with 'pymysql' in all the codes, which is intimidating. Luckily, PyMySQL can be loaded as MySQLdb dyanamically. In order to achieve it in Django, you need to add the following lines to __init__.py file under the dir of the project's default app (If your have a project named 'myproject', add lines to myproject/myproject/init.py):

import pymysql
pymysql.install_as_MySQLdb()

This __init__.py would be executed when you run the Django project, and MySQLdb will be replaced. You problem is then solved.


问:
How to add a field to an ArrayList from a different class?
I'm quite new to programming, I'm building a program that adds different jobs done by the same person in an organisation to an ArrayList.

I'm trying to add more than two job titles from the main class to the ArrayList but I keep getting an error, could you please guide me in the right direction?

```<code>import java.util.ArrayList;
public class Employee
{
 private String name;
  private String department;

  private ArrayList<String>job = new ArrayList();

 public void setJob(ArrayList<String> job)
  {
  this.job =job;
 }

 public ArrayList<String> getJob()
 {
   return job;
 }
 }
</code>```

Here is the Main class

    public class Main

```<code>{
 public static void main(String[] args)
 {

  Employee walter = new Employee();
   walter.setName("Walter White");
   walter.setJob("Chemistry Teacher");//The error occurs here it says
   //method setJob in class Employee cannot be applied to given types;
</code>```

walter.setJob("Chemistry Teacher");
^
required: java.util.ArrayList
found: java.lang.String
reason: actual argument java.lang.String cannot be converted to java.util.ArrayList by method invocation conversion

```<code>   walter.setDepartment("Science");
  }
  }
</code>```

答:
You defined job as an ArrayList of String, therefore you can't set it with a plain String you must pass a List to it. Here is one way to do it:

```<code>walter.setJob(Arrays.asList(new String("Chemistry Teacher")));
</code>```

Or less verbal way as suggested by @Daedalus

```<code>walter.setJob(Arrays.asList("Chemistry Teacher"));
</code>```

If your requirement is that an employee have many jobs than there is nothing wrong with defining it as a list. The more elegant way would be to follow the suggestion of @HovercraftFullOfEels in comments above but since you are a starter you should know that it is not wrong per se.

His suggestion is that you have a method to add a job to the existing list so:

```<code>public void addJob(String jobName){
    job.add(jobName);
}
</code>```

Then you would use:

```<code> walter.addJob("Chemistry Teacher");
</code>```

Body:
I'm quite new to programming, I'm building a program that adds different jobs done by the same person in an organisation to an ArrayList.

I'm trying to add more than two job titles from the main class to the ArrayList but I keep getting an error, could you please guide me in the right direction?

import java.util.ArrayList;
public class Employee
{
 private String name;
  private String department;

  private ArrayList<String>job = new ArrayList();

 public void setJob(ArrayList<String> job)
  {
  this.job =job;
 }

 public ArrayList<String> getJob()
 {
   return job;
 }
 }

Here is the Main class

    public class Main

{
 public static void main(String[] args)
 {

  Employee walter = new Employee();
   walter.setName("Walter White");
   walter.setJob("Chemistry Teacher");//The error occurs here it says
   //method setJob in class Employee cannot be applied to given types;

walter.setJob("Chemistry Teacher");
^
required: java.util.ArrayList
found: java.lang.String
reason: actual argument java.lang.String cannot be converted to java.util.ArrayList by method invocation conversion

   walter.setDepartment("Science");
  }
  }

Body:
You defined job as an ArrayList of String, therefore you can't set it with a plain String you must pass a List to it. Here is one way to do it:

walter.setJob(Arrays.asList(new String("Chemistry Teacher")));

Or less verbal way as suggested by @Daedalus

walter.setJob(Arrays.asList("Chemistry Teacher"));

If your requirement is that an employee have many jobs than there is nothing wrong with defining it as a list. The more elegant way would be to follow the suggestion of @HovercraftFullOfEels in comments above but since you are a starter you should know that it is not wrong per se.

His suggestion is that you have a method to add a job to the existing list so:

public void addJob(String jobName){
    job.add(jobName);
}

Then you would use:

 walter.addJob("Chemistry Teacher");


问:
Do I have to use id attr?
In angular 2, when I want to style a specific component I use the following:

```<code><div #mask id="mask" class="col-xs-12 some-generi-ccss-class"></div>

// in .css
#mask{
  height: 50px;
}
</code>```

In my opinion it seems like a bit of a double handle defining both an id (id="mask") to style with and a ng2 selector string (#mask) to use with @ViewChild('mask') in my component.ts for the one element.

Am I able to drop one of these attributes but still achieve both functionalities? Or is this boilerplate?

答:
Answer is no and yes :

Coz it looks same but both are different :

#mask in div elements shows the template variable , so you can access it inside template and in component , that's part of angular 2

id="mask" is html's default attribute,

Though if you want to access the div without using #mask , there is way , via
document.getElementById('mask') and remove #mask if you don't want to access it from template side.

Title: Do I have to use id attr?

Body:
In angular 2, when I want to style a specific component I use the following:

// in .css
#mask{
  height: 50px;
}

In my opinion it seems like a bit of a double handle defining both an id (id="mask") to style with and a ng2 selector string (#mask) to use with @ViewChild('mask') in my component.ts for the one element.

Am I able to drop one of these attributes but still achieve both functionalities? Or is this boilerplate?


问:
Setting Android images from string value
Currently I'm drawing a PNG image in my Android application like so:

```<code>ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))
</code>```

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

```<code>ID:    Name:    ImageName:
-      Test     testimage
</code>```

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

```<code>int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;
</code>```

However this isn't very efficient!

Thanks

答:
Put you images in the assets/ folder and open </p>

```<code>image.setImageURI("file:///android_asset/" + nameFromDB);
</code>```

Body:
Currently I'm drawing a PNG image in my Android application like so:

ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

ID:    Name:    ImageName:
-      Test     testimage

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;

However this isn't very efficient!

Thanks

Body:
Put you images in the assets/ folder and open

image.setImageURI("file:///android_asset/" + nameFromDB);


答:
Here's what I would do.

function alpha() {
  var a = prompt("Enter string: ");

  var upper = a.split('').map((e) => e.charCodeAt(0) > 96 && e.charCodeAt(0) < 123 ? String.fromCharCode(e.charCodeAt(0) - 32) : e);

  return upper.join('');
}

console.log(alpha());```

Body:
function alpha()
{
    var a=prompt("Enter String: ");

    for(var b=[i=0];c=a.charCodeAt(i);)
    {
        b[i++]=String.fromCharCode(c|(c>96 && c<123));
    }
    alert(b.join(""))
}
console.log(alpha());

So far some letters in the code change when I run this but for some reason it is not changing the string characters to all uppercase. (Example of output; I type "hi" into the prompt and the alert outputs "i" so the h disappears for some reason.


问:
I can't figure out why there are extra parenthesis in my console
I'm learning the basics of programming and I can't seem to understand why my console is displaying extra parenthesis with the following code:

```<code>// My Constants Dictionary!

let numberOneScore = 10
let numberTwoScore = 20
let numberThreeScore = 30
let numberFourScore = 40
let numberFiveScore = 50

// Game Stats

func playerOneStats() {
    let playerOneScore = (numberTwoScore) + (numberThreeScore) + (numberOneScore)
    print ("Player one has scored \(playerOneScore) points.")
        }

func playerTwoStats() {
    let playerTwoScore = (numberFiveScore) + (numberOneScore) + (numberOneScore)
    print ("Player two has scored \(playerTwoScore) points.")
        }

func showStats() {
    print(playerOneStats())
    print(playerTwoStats())
        }

showStats()
</code>```

My console shows this:

```<code>Player one has scored 60 points.
()
Player two has scored 70 points.
()
</code>```

And my question is, why are those extra parenthesis being printed on console at the end of each player's score?

答:
Because

```<code>Player one has scored 60 points.
</code>```

and

```<code>Player two has scored 70 points.
</code>```

are printed by playerOneStats() and playerTwoStats(), while the () by the unnecessary prints in showStats(). You should do

```<code>func showStats() {
    playerOneStats()
    playerTwoStats()
}
</code>```

Body:
I'm learning the basics of programming and I can't seem to understand why my console is displaying extra parenthesis with the following code:

// My Constants Dictionary!

let numberOneScore = 10
let numberTwoScore = 20
let numberThreeScore = 30
let numberFourScore = 40
let numberFiveScore = 50

// Game Stats

func playerOneStats() {
    let playerOneScore = (numberTwoScore) + (numberThreeScore) + (numberOneScore)
    print ("Player one has scored \(playerOneScore) points.")
        }

func playerTwoStats() {
    let playerTwoScore = (numberFiveScore) + (numberOneScore) + (numberOneScore)
    print ("Player two has scored \(playerTwoScore) points.")
        }

func showStats() {
    print(playerOneStats())
    print(playerTwoStats())
        }

showStats()

My console shows this:

Player one has scored 60 points.
()
Player two has scored 70 points.
()

And my question is, why are those extra parenthesis being printed on console at the end of each player's score?

Body:
Because

Player one has scored 60 points.

and

Player two has scored 70 points.

are printed by playerOneStats() and playerTwoStats(), while the () by the unnecessary prints in showStats(). You should do

func showStats() {
    playerOneStats()
    playerTwoStats()
}


答:
Since this is a learning objective, I will only described a means to do this and let you try to figure it out using this answer as a guideline.

first you want to loop through the characters in string.
for each character you would want some code to turn it into a capital letter, assuming it is a letter.
finally you want to hold the capitalized letters in a variable.

This link may help for UTF-8 charcodes. Even if you aren't using utf-8, it may give you some ideas.
http://www.utf8-chartable.de/


问:
How to use functions in order
```<code>import XCTest

class TestClass: XCTestCase
{

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = true
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()

        // UIApplication.shared.keyWindow?.layer.speed = 100
        UIApplication.sharedApplication().keyWindow?.layer.speed = 100

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample()
    {
    }

    func testA1_TC8InvalidEmailAndPasswordTC8_A1()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("test@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("dgbnnnbb")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testA2_TC9KeepAllFieldBlankTC9_A2()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        app.textFields["Email ID"].tap()
        let passwordSecureTextField = app.secureTextFields["Password"]
        app.secureTextFields["Password"].tap()

        if passwordSecureTextField.value as! String != ""
        {
            passwordSecureTextField.clearAndEnterText(passwordSecureTextField.value as! String)
        }

        app.secureTextFields["Password"].tap()
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testTC10ValidUsernameAndInvalidPasswordTC10C()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("gfdedkff@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("grtegrgrtst")

        let moreNumbersKey = app.keys["more, numbers"]
        moreNumbersKey.tap()
        passwordSecureTextField.typeText("@123")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }
</code>```

I have multiple functions in test class. I want to use these functions one by one (synchronously) in order because function one result is function two output or parameter. Can you help me to find-out the solution?

答:
This testing framework that you're using (XCTest provided by Apple) is designed such that tests are independent of one another. This is for very (many) good reasons that is out of scope for this answer.

You can do it but you'll be fighting the framework the whole way and or losing out on key functionality provided to you by Xcode and the XCTest framework.

A quick an easy way to do this, is to just have one test() func. Then write all your individual tests as helper functions and call them sequentially within func test().

So...

```<code>func testSequentially() {
    assertThisFirst()
    assertThisSecond()
}

func assertThisFirst() {
    // Some test
}

func assertThisSecond() {
    // Some other test
}
</code>```

Now let me reassert that this is not a good way of running tests. You miss out on the ability to run individual tests. You miss out on a lot of nice GUI in Xcode for inspecting tests. Your tests will be a lot harder to debug when failures inevitably do occur. On and on and on... I wish you the best of luck!

Title: How to use functions in order

Body:
import XCTest

class TestClass: XCTestCase
{

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = true
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()

        // UIApplication.shared.keyWindow?.layer.speed = 100
        UIApplication.sharedApplication().keyWindow?.layer.speed = 100

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample()
    {
    }

    func testA1_TC8InvalidEmailAndPasswordTC8_A1()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("test@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("dgbnnnbb")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testA2_TC9KeepAllFieldBlankTC9_A2()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        app.textFields["Email ID"].tap()
        let passwordSecureTextField = app.secureTextFields["Password"]
        app.secureTextFields["Password"].tap()

        if passwordSecureTextField.value as! String != ""
        {
            passwordSecureTextField.clearAndEnterText(passwordSecureTextField.value as! String)
        }

        app.secureTextFields["Password"].tap()
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

    func testTC10ValidUsernameAndInvalidPasswordTC10C()
    {
        let app = XCUIApplication()
        let emailIdTextField = app.textFields["Email ID"]
        emailIdTextField.tap()

        if emailIdTextField.value as! String != ""
        {
            emailIdTextField.clearAndEnterText(emailIdTextField.value as! String)
        }

        emailIdTextField.typeText("gfdedkff@gmail.com")

        let passwordSecureTextField = app.secureTextFields["Password"]
        passwordSecureTextField.tap()
        passwordSecureTextField.typeText("grtegrgrtst")

        let moreNumbersKey = app.keys["more, numbers"]
        moreNumbersKey.tap()
        passwordSecureTextField.typeText("@123")
        app.buttons["Login"].tap()
        app.buttons["OK"].tap()
    }

I have multiple functions in test class. I want to use these functions one by one (synchronously) in order because function one result is function two output or parameter. Can you help me to find-out the solution?

Body:
This testing framework that you're using (XCTest provided by Apple) is designed such that tests are independent of one another. This is for very (many) good reasons that is out of scope for this answer.

You can do it but you'll be fighting the framework the whole way and or losing out on key functionality provided to you by Xcode and the XCTest framework.

A quick an easy way to do this, is to just have one test() func. Then write all your individual tests as helper functions and call them sequentially within func test().

So...

func testSequentially() {
    assertThisFirst()
    assertThisSecond()
}

func assertThisFirst() {
    // Some test
}

func assertThisSecond() {
    // Some other test
}

Now let me reassert that this is not a good way of running tests. You miss out on the ability to run individual tests. You miss out on a lot of nice GUI in Xcode for inspecting tests. Your tests will be a lot harder to debug when failures inevitably do occur. On and on and on... I wish you the best of luck!


问:
HQL projection on entities/tables
I have two tables with one to one relationship - Person and House
I tried to use HQL projection like Select p.name, p.dob from Person which returns me the name and dob fine.
However, I dont know how to use projection in HQL if:
1. I want to include the House
2. I want to include only color and year of the House.

i tried SELECT p.firstName, p.lastName p.house FROM Person p" but got error with "could not resolve property". What do i need to do to get this right? thanks

答:
It is quite simple actually by using HQL:

```<code>SELECT p.firstName, p.lastName, h.color, h.year FROM Person p join p.house h
</code>```

This will return a array constain those values.

For your second comment, yes, you can has a DTO to do that, e.g.

```<code>class PersonDTO {
    String firstName;
    String lastName;
    Hourse hourse;
    public PersonDTO(){}

    public PersonDTO(String firstName, String lastName, Hourse hourse) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.hourse = hourse;
    }

    // getter & setter
}
</code>```

then in you HQL, you can return it like
SELECT new PersonDTO(p.firstName, p.lastName, h) FROM Person p join p.house h

Title: HQL projection on entities/tables

Body:
It is quite simple actually by using HQL:

SELECT p.firstName, p.lastName, h.color, h.year FROM Person p join p.house h

This will return a array constain those values.

For your second comment, yes, you can has a DTO to do that, e.g.

class PersonDTO {
    String firstName;
    String lastName;
    Hourse hourse;
    public PersonDTO(){}

    public PersonDTO(String firstName, String lastName, Hourse hourse) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.hourse = hourse;
    }

    // getter & setter
}

then in you HQL, you can return it like
SELECT new PersonDTO(p.firstName, p.lastName, h) FROM Person p join p.house h


问:
MYSQL SELECT ... FOR UPDATE Not working?
I am having issues with MySQL's SELECT .. FOR UPDATE, here is the query I am trying to run:

```<code>SQL = "SELECT * " +
      "FROM " + TableName + " " +
      "WHERE out_status IN ("+outSStatus+") AND queued <= NOW() " +
      "ORDER BY out_status, id_queue ASC "+ limitSql+
      "FOR UPDATE";
</code>```

After this, the thread will do an UPDATE and change the out_status to 99, which is then it should unlock the row.

I am running a multi-threaded java application, so 3 threads are running this SQL statement, but when thread 1 runs this, it doesn't lock (hide) its results from thread 2 & 3. Therefore threads 2 & 3 are getting the same results.

Also each thread is on its own mysql connection.

Can anybody please help me with this? OR perhaps have a better solution?

Much Appreciated.

答: I had a similar issue. Both answers, from @Vikash and @Adeel Ansari, are valid suggestions. However, I solved the issue by using InnoDB engine instead of MyISAM. MyISAM only allows locking on table level, not on row level. You still need transactions, when using InnoDB.

Body:
I am having issues with MySQL's SELECT .. FOR UPDATE, here is the query I am trying to run:

SQL = "SELECT * " +
      "FROM " + TableName + " " +
      "WHERE out_status IN ("+outSStatus+") AND queued <= NOW() " +
      "ORDER BY out_status, id_queue ASC "+ limitSql+
      "FOR UPDATE";

After this, the thread will do an UPDATE and change the out_status to 99, which is then it should unlock the row.

I am running a multi-threaded java application, so 3 threads are running this SQL statement, but when thread 1 runs this, it doesn't lock (hide) its results from thread 2 & 3. Therefore threads 2 & 3 are getting the same results.

Also each thread is on its own mysql connection.

Can anybody please help me with this? OR perhaps have a better solution?

Much Appreciated.


问:
How should I store a long list of IDs in redis?
I want to store a list of IDs (>100,000 of them) in redis.

So the list might look like: 332 99 91 78 10 98989 18221

I'll also need to be able to check to see if multiple IDs exist within this list as well.

e.g. I'd need to be able to check at once whether 99 and 332 and 41 exists on the list.

How would I go about storing this type of data?

答:
You can also use a SET to store these ids. Although the SISMEMBER command can only check whether a single member exists, you can write a lua script to check the existence of multiple keys in one call.

```<code>-- multi-sismember.lua
for i, v in ipairs(ARGV) do
    if (redis.call('sismember', KEYS[1], v) == 0) then return false end
end
return true
</code>```

Run it as redis-cli --eval multi-sismember.lua key , 99 332 41.

Body:
You can also use a SET to store these ids. Although the SISMEMBER command can only check whether a single member exists, you can write a lua script to check the existence of multiple keys in one call.

-- multi-sismember.lua
for i, v in ipairs(ARGV) do
    if (redis.call('sismember', KEYS[1], v) == 0) then return false end
end
return true

Run it as redis-cli --eval multi-sismember.lua key , 99 332 41.


问:
How to unserialize the JSON data in server part
I have a simple form which I try to post using jQuery post in JSON format. The form is getting post but my problem is at PHP part. I am unable to get the data. From other stack question I found solution of just doing $_POST['FirstName'] but I am getting result as "FirstName=john&LastName=plar&Address=home&PhoneNumber=23423423".

How can I decode this JSON data? Below are the code that I have tried so far. Thank you.

```<code><form action="user.php" method="post" id="myForm">
    First Name: <input type="text" name="FirstName" />
    Last Name: <input type="text" name="LastName" />
    Address: <input type="text" name="Address" />
    Phone: <input type="text" name="PhoneNumber" />
    <input type="submit" id="submit" value="Submit"/>
</form>

<script>
$("#submit").on('click', function(e){
    e.preventDefault();
    var data = $("#myForm input").serialize();
    $.post('user.php',{"data":JSON.stringify(data)},function(data){

    },'json');

})
</script>
</code>```

user.php

```<code>$object =$_POST['data'];
$array = json_decode($object);
print_r($object);
</code>```

答:
You don't need to use JSON at all, just serialize and upload the form.

```<code>$("#submit").on('click', function(e){
    e.preventDefault();
    $.post(
        'user.php',
        $("#myForm").serialize(),
        function(data, textStatus){
            // do stuff with the response
        }
    );
});
</code>```

Then in your PHP

```<code><?php
echo $_POST["FirstName"];
// etc
</code>```

Body:
I have a simple form which I try to post using jQuery post in JSON format. The form is getting post but my problem is at PHP part. I am unable to get the data. From other stack question I found solution of just doing $_POST['FirstName'] but I am getting result as "FirstName=john&LastName=plar&Address=home&PhoneNumber=23423423".

How can I decode this JSON data? Below are the code that I have tried so far. Thank you.

<form action="user.php" method="post" id="myForm">
    First Name: <input type="text" name="FirstName" />
    Last Name: <input type="text" name="LastName" />
    Address: <input type="text" name="Address" />
    Phone: <input type="text" name="PhoneNumber" />
    <input type="submit" id="submit" value="Submit"/>
</form>

user.php

$object =$_POST['data'];
$array = json_decode($object);
print_r($object);

Body:
You don't need to use JSON at all, just serialize and upload the form.

$("#submit").on('click', function(e){
    e.preventDefault();
    $.post(
        'user.php',
        $("#myForm").serialize(),
        function(data, textStatus){
            // do stuff with the response
        }
    );
});

Then in your PHP

<?php
echo $_POST["FirstName"];
// etc


答:
Your showStats method should be simply calling the other two methods like this:

```<code>func showStats() {
    playerOneStats()
    playerTwoStats()
}
</code>```

Instead of that, you wrap the two method calls in print statements. If those two methods returned a value, then that value would be printed by the print statement. However, those methods return no value at all. So that's why you get the empty parentheses.

Title: I can't figure out why there are extra parenthesis in my console

Body:
Your showStats method should be simply calling the other two methods like this:

func showStats() {
    playerOneStats()
    playerTwoStats()
}

Instead of that, you wrap the two method calls in print statements. If those two methods returned a value, then that value would be printed by the print statement. However, those methods return no value at all. So that's why you get the empty parentheses.


问:
VB6 application connecting to mapi
I have created a VB6 application which contains a service to basically send and receive emails,the service uses a service account and mapi profile configured in Windows 2003 serverR2.

This was working when both exchange server and domain account were in the same network.  Once the exchange server got changed the service is unable to send or receive emails giving error

Microsoft Exchange is not available.  Either there are network problems or the Exchange computer is down for maintenance. [Microsoft Exchange Information Store - [MAPI_E_FAILONEPROVIDER(8004011D)]], Collaboration Data Objects.

I have searched this error but I wasn't able to gather all as the explanation is for same network.
Anyone could you please advice what can I do to resolve this ?
Thanks,

答:
MAPI has been discontinued by Microsift as suggested by @bob77 also.
I would recommend to use SMTP or EWS.

That being said if you still want to go with it.
Please find the working code below:

```<code>   Set objMAPI = New MAPI.Session
  objMAPI.Logon ShowDialog:=False, NewSession:=False, ProfileInfo:=gobjINI.gstrExchangeServer & vbLf & gobjINI.gstrProfile

 'Add a new mesage to the OUtbo Messages Collection
 Set objMSG = objMAPI.Outbox.Messages.Add

 Set fsoMy_File_Sys_Obj = New FileSystemObject

 'Add the recipient list specified in INI File
 'Check if this is a multiple Recipient List (names or groups seperated by semicolons!)
 If InStr(1, Recipients, ";") Then
  objMSG.Recipients.AddMultiple Recipients, CdoTo
  objMSG.Recipients.Resolve
 Else
  'This section is for handling of single recipient name
  'Be aware that this may be an email group list name !
  Set objRecipients = objMSG.Recipients.Add(Recipients)
  objRecipients.Resolve
 End If

'Add an attachment if needed
If Attachment_Name <> "" Then
    bolAttach_File_Exists = fsoMy_File_Sys_Obj.FileExists(Attachment_Path)
    If bolAttach_File_Exists = True Then
        'Open the attachment file and add it to the message text
        Set tsAttachment = fsoMy_File_Sys_Obj.OpenTextFile(Attachment_Path)
        Do While Not tsAttachment.AtEndOfStream
            strAttachment_Read = tsAttachment.ReadLine
            Message = Message & strAttachment_Read & vbCrLf
        Loop
        tsAttachment.Close
    Else
        gobjMAPI.MailSend gobjINI.gstrMailRecipients, "Email Send - Attachment Addition", "Attempted To Attach A File That Does Not Exist", "", ""
    End If
End If

 'Add Subject Line, Message Content and Send Message
 objMSG.Subject = Subject
 objMSG.Text = Message
 objMSG.Importance = mapiHigh

 'The Update method adds all our assignments to collecttion
 objMSG.Update

 'Now let's actually send the message
 objMSG.Send

 'End MAPI Session
 objMAPI.Logoff
 Set objMAPI = Nothing
</code>```

Title: VB6 application connecting to mapi

Body:
MAPI has been discontinued by Microsift as suggested by @bob77 also.
I would recommend to use SMTP or EWS.

That being said if you still want to go with it.
Please find the working code below:

   Set objMAPI = New MAPI.Session
  objMAPI.Logon ShowDialog:=False, NewSession:=False, ProfileInfo:=gobjINI.gstrExchangeServer & vbLf & gobjINI.gstrProfile

 'Add a new mesage to the OUtbo Messages Collection
 Set objMSG = objMAPI.Outbox.Messages.Add

 Set fsoMy_File_Sys_Obj = New FileSystemObject

 'Add the recipient list specified in INI File
 'Check if this is a multiple Recipient List (names or groups seperated by semicolons!)
 If InStr(1, Recipients, ";") Then
  objMSG.Recipients.AddMultiple Recipients, CdoTo
  objMSG.Recipients.Resolve
 Else
  'This section is for handling of single recipient name
  'Be aware that this may be an email group list name !
  Set objRecipients = objMSG.Recipients.Add(Recipients)
  objRecipients.Resolve
 End If

'Add an attachment if needed
If Attachment_Name <> "" Then
    bolAttach_File_Exists = fsoMy_File_Sys_Obj.FileExists(Attachment_Path)
    If bolAttach_File_Exists = True Then
        'Open the attachment file and add it to the message text
        Set tsAttachment = fsoMy_File_Sys_Obj.OpenTextFile(Attachment_Path)
        Do While Not tsAttachment.AtEndOfStream
            strAttachment_Read = tsAttachment.ReadLine
            Message = Message & strAttachment_Read & vbCrLf
        Loop
        tsAttachment.Close
    Else
        gobjMAPI.MailSend gobjINI.gstrMailRecipients, "Email Send - Attachment Addition", "Attempted To Attach A File That Does Not Exist", "", ""
    End If
End If

 'Add Subject Line, Message Content and Send Message
 objMSG.Subject = Subject
 objMSG.Text = Message
 objMSG.Importance = mapiHigh

 'The Update method adds all our assignments to collecttion
 objMSG.Update

 'Now let's actually send the message
 objMSG.Send

 'End MAPI Session
 objMAPI.Logoff
 Set objMAPI = Nothing


问:
jquery attributes from multiple elements
I am trying ot figure how to use jQuery to get the value of html attribute of many elements. My webpage updates dynamically using ajax. I have an attribute called number for in element in the part that is updated. I want to use the attribute value from each element so that i can use that data as parameters to a php file link. I have come across jquery's .attr() function, but it only seems to take the attribute value of the first element if finds. But what I want to do is get the attribute value for each element so that when I click on that element its corresponding attribute value is sent as parameters to the php file.

Thanks

答:
Disclaimer: This most likely does not respond to the OP question (after re-reading), but will stay for some time in case it fill some need of the OP.

Use the .map() method

```<code>var numbers = $('[number]').map(function(){
  return $(this).attr('number');
});
</code>```

this will create an array filled with the number attribute of all the elements that have one.

Body:
Disclaimer: This most likely does not respond to the OP question (after re-reading), but will stay for some time in case it fill some need of the OP.

Use the .map() method

var numbers = $('[number]').map(function(){
  return $(this).attr('number');
});

this will create an array filled with the number attribute of all the elements that have one.


问:
Reading a .conf file PHP
I am stuck and hoping someone can help me out. I am trying to read a .conf file in PHP to get some variables.

My file is in this format:

```<code>class: English
room: 150e
</code>```

How can I go about getting the value from class or room?

答:
This should work:

```<code>$file = 'yourfile.conf';
$contents = file($file);
foreach($contents as $line) {
    $e = explode(':', $line);
    $conf[trim($e[0])] = trim($e[1]);
}
</code>```

Now you have an array with your configurations.

Title: Reading a .conf file PHP

Body:
I am stuck and hoping someone can help me out. I am trying to read a .conf file in PHP to get some variables.

My file is in this format:

class: English
room: 150e

How can I go about getting the value from class or room?

Body:
This should work:

$file = 'yourfile.conf';
$contents = file($file);
foreach($contents as $line) {
    $e = explode(':', $line);
    $conf[trim($e[0])] = trim($e[1]);
}

Now you have an array with your configurations.