问:
ClassNotFoundException: Didn't find class "android.support.design.widget.AppBarLayout"
I'm using AppBarLayout and NestedScrollview in my code .But I get a error. The code compile successfully but crash with the stacktrace

```<code>05-02 17:10:17.255 31335 31335 E AndroidRuntime: FATAL EXCEPTION: main
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Process: com.android.settings, PID: 31335
05-02 17:10:17.255 31335 31335 E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{XXXXXXXXXXXXXXXXXXX}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.access$900(ActivityThread.java:153)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:102)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:148)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:5438)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:736)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:543)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.Activity.setContentView(Activity.java:2183)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.Activity.performCreate(Activity.java:6303)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    ... 9 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    ... 18 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.AppBarLayout" on path: DexPathList[[zip file "/system/framework/cloud-common.jar", zip file "/system/framework/zxing.jar", zip file "/system/framework/android-support-v13.jar", zip file "/system/framework/protobuf.jar", zip file "/system/priv-app/Settings/Settings.apk"],nativeLibraryDirectories=[/system/priv-app/Settings/lib/arm, /vendor/lib, /system/lib]]
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createView(LayoutInflater.java:587)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:768)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    ... 22 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    Suppressed: java.lang.ClassNotFoundException: android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.Class.classForName(Native Method)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        ... 25 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
</code>```

I develop with intellij .thanks for any suggestion.

答:
also check your target sdk version before add any support library in gradel

for example:

if target sdk = 25

then your support library will be com.android.support:design:25.4.0 or it may we between minSdkVersion and targetSdkVersion.

Body:
I'm using AppBarLayout and NestedScrollview in my code .But I get a error. The code compile successfully but crash with the stacktrace

05-02 17:10:17.255 31335 31335 E AndroidRuntime: FATAL EXCEPTION: main
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Process: com.android.settings, PID: 31335
05-02 17:10:17.255 31335 31335 E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{XXXXXXXXXXXXXXXXXXX}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.access$900(ActivityThread.java:153)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:102)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:148)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:5438)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:736)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:543)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.Activity.setContentView(Activity.java:2183)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.Activity.performCreate(Activity.java:6303)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    ... 9 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:708)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.rInflate(LayoutInflater.java:839)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:802)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    ... 18 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.AppBarLayout" on path: DexPathList[[zip file "/system/framework/cloud-common.jar", zip file "/system/framework/zxing.jar", zip file "/system/framework/android-support-v13.jar", zip file "/system/framework/protobuf.jar", zip file "/system/priv-app/Settings/Settings.apk"],nativeLibraryDirectories=[/system/priv-app/Settings/lib/arm, /vendor/lib, /system/lib]]
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createView(LayoutInflater.java:587)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:768)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    ... 22 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    Suppressed: java.lang.ClassNotFoundException: android.support.design.widget.AppBarLayout
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.Class.classForName(Native Method)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
05-02 17:10:17.255 31335 31335 E AndroidRuntime:        ... 25 more
05-02 17:10:17.255 31335 31335 E AndroidRuntime:    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

I develop with intellij .thanks for any suggestion.


来源: stackexchange

问:
How to make map object (eg: circle) clickable in android google maps v2?
Google recently introduced the circle as a map object in V2 and can easily be drawn:
https://developers.google.com/maps/documentation/android/shapes#circles

Does anyone know how to make this clickable, so that I can open an info window etc... ?

Thanks a lot for the help.

答: It's very straight forward - mMap.setOnCircleClickListener(this);</p>

ContentLicense: CC BY-SA 3.0


问:
Core ML iOS 11 not recognizing images properly
I tried Core ML which was recently introduced in iOS to recognise and classify images. The problem is, it is not giving proper results for the images sent.

If i send an earth image(Globe) it is giving me the class as bubble. Below is the code i used,

```<code>            let model = Resnet50()

            let pixelBuffer: CVPixelBuffer =  (modelImg.pixelBuffer())!

            if let prediction = try? model.prediction(image: pixelBuffer) {
                print( "Found it!! It is a/an \(prediction.classLabel)")
            }
</code>```

Is it possible to train the Model with custom use cases on top of the existing Core ML model?(For ex. Resnet50)

答:
Core ML can only be used for inference with already trained models. You will have to use some other tool to previously train your model, and then convert it to Core ML, using Core ML Tools. You can find the supported third-party machine learning tools and formats in the documentation:

https://developer.apple.com/documentation/coreml/converting_trained_models_to_core_ml

Body:
I tried Core ML which was recently introduced in iOS to recognise and classify images. The problem is, it is not giving proper results for the images sent.

If i send an earth image(Globe) it is giving me the class as bubble. Below is the code i used,

            let model = Resnet50()

            let pixelBuffer: CVPixelBuffer =  (modelImg.pixelBuffer())!

            if let prediction = try? model.prediction(image: pixelBuffer) {
                print( "Found it!! It is a/an \(prediction.classLabel)")
            }

Is it possible to train the Model with custom use cases on top of the existing Core ML model?(For ex. Resnet50)


问:
That is my program in C++ using OpenCv library to read the sequence of images from a dataset, but it doesn't run
```<code>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
VideoCapture cap("F:/TestIJCNN2013Download/%05d.ppm");
Mat frame;
cap >> frame;
cap.read(frame);
imshow("frame" , frame);
return 0;
}
</code>```

The program compiled with zero errors but doesn't run. How can I run the program correctly, is that false logic or something else.

答:
You are missing the cv::waitKey() call. The image will not be displayed unless you use this function.

Please refer this short code on using VideoCapture() for more details.

Body:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
VideoCapture cap("F:/TestIJCNN2013Download/%05d.ppm");
Mat frame;
cap >> frame;
cap.read(frame);
imshow("frame" , frame);
return 0;
}

The program compiled with zero errors but doesn't run. How can I run the program correctly, is that false logic or something else.


问:
Avoiding the creation of .aux, .log and .synctex.gz files when using pdflatex
I just want to have a .tex file which I compile with pdflatex and end up with a .pdf file. I don't want all the other .aux, .log and .synctex.gz files. pdflatex doesn't seem to have arguments for this.

答:
I always build my PDF files like this:

```<code>pdflatex -aux-directory=/some/temp/dir <additional options>
</code>```

That way, I don't have too see all the additional files. Those files should not be removed, as they are important for cross referencing, bibliographies, table of contents etc. To run pdflatex several times and then remove the files takes too much time.

The -aux-directory unfortunately does not exist in the linux version of pdflatex. Tested on Ubuntu Lucid.

ContentLicense: CC BY-SA 4.0

Body:
I always build my PDF files like this:

pdflatex -aux-directory=/some/temp/dir <additional options>

That way, I don't have too see all the additional files. Those files should not be removed, as they are important for cross referencing, bibliographies, table of contents etc. To run pdflatex several times and then remove the files takes too much time.

The -aux-directory unfortunately does not exist in the linux version of pdflatex. Tested on Ubuntu Lucid.

ContentLicense: CC BY-SA 2.5


问:
C# repository and localizable entities
In my app I have many localizable entities. Database structure for this entities
is . Types of PK in some tables may be differ (some of them is int, some is bigint). It depends on how much data will be stored in a table.
I use Dapper as ORM.

Now I have this solution (but something inside tells me that this solution is bad):

```<code>// ENTITY
public abstract class Entity
{
    public object Id { get; set; }
}

public abstract class Entity<TKey> : Entity
{
    public new TKey Id { get; set; }
}

// LOCALIZABLE ENTITY
public abstract class LocalizableEntity<TTranslation> : Entity
    where TTranslation : EntityTranslation
{
    public ICollection<TTranslation> Translations { get; set; }
}

public abstract class LocalizableEntity<TKey, TTranslation> : Entity<TKey>
    where TTranslation : EntityTranslation
{
    public ICollection<TTranslation> Translations { get; set; }
}

// ENTITY TRANSLATION
public abstract class EntityTranslation
{
    public object LocalizableId { get; set; }

    public int LanguageId { get; set; }
}

public abstract class EntityTranslation<TKey> : EntityTranslation
{
    public new TKey LocalizableId { get; set; }
}

// REPOSITORIES

public class BaseRepository: IRepository, IDisposable
{
    public string ConnectionString { get; set; }

    // ....
}

public abstract class BaseEntityRepository: BaseRepository
{
    protected IDbConnection Connection => _connection ?? (_connection = CreateDbConnection(GetConnectionStringValue(ConnectionString)));

    protected abstract IDbConnection CreateDbConnection(string connectionString);

    // SaveEntity<T>(T entity), DeleteEntity(object id)
}

public abstract class BaseEntityRepository<TEntity, TKey, TSearchOptions, TLoadOptions> : BaseEntityRepository
    where TEntity : Entity<TKey>
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    // GetEntities(TSearchOptions sopts, TLoadOptions lopts), EntityCount(TSearchOptions) ...
}

public abstract class BaseLocalizableEntityRepository<TEntity, TKey, TEntityTranslation, TSearchOptions, TLoadOptions> : BaseEntityRepository<TEntity, TSearchOptions, TLoadOptions>
    where TEntity : Entity<TKey>
    where TEntityTranslation : EntityTranslation<TKey>
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    // GetTranslations, SaveTranslation ...
}
</code>```

Is it good or bad? If it is bad, how should I do it?

答:
As you need highly customizable localization your solution is not so bad. I perform the same way if I need translation. But instead having a different table per entity-translation I have a unique table to which any entities that support translation reference to:

CREATE TABLE Test_Translations
(
    Language char(10) NOT NULL,
    TextId int NOT NULL,
    Value text NOT NULL,
    CONSTRAINT Test_Translations_Language_TextId_pk PRIMARY KEY (Language, TextId)
);

CREATE TABLE Test_LocalizableStrings
(
    Id int NOT NULL CONSTRAINT Test2_Test1Id_pk primary key
);

ALTER TABLE Test_Translations ADD FOREIGN KEY (TextId) REFERENCES Test_LocalizableStrings;
```

Then in the tables that need a translation support just create a reference key to Test_LocalizableStrings. At query time query for TextId and Language.

Title: C# repository and localizable entities

Body:
In my app I have many localizable entities. Database structure for this entities
is . Types of PK in some tables may be differ (some of them is int, some is bigint). It depends on how much data will be stored in a table.
I use Dapper as ORM.

Now I have this solution (but something inside tells me that this solution is bad):

// ENTITY
public abstract class Entity
{
    public object Id { get; set; }
}

public abstract class Entity<TKey> : Entity
{
    public new TKey Id { get; set; }
}

// LOCALIZABLE ENTITY
public abstract class LocalizableEntity<TTranslation> : Entity
    where TTranslation : EntityTranslation
{
    public ICollection<TTranslation> Translations { get; set; }
}

public abstract class LocalizableEntity<TKey, TTranslation> : Entity<TKey>
    where TTranslation : EntityTranslation
{
    public ICollection<TTranslation> Translations { get; set; }
}

// ENTITY TRANSLATION
public abstract class EntityTranslation
{
    public object LocalizableId { get; set; }

    public int LanguageId { get; set; }
}

public abstract class EntityTranslation<TKey> : EntityTranslation
{
    public new TKey LocalizableId { get; set; }
}

// REPOSITORIES

public class BaseRepository: IRepository, IDisposable
{
    public string ConnectionString { get; set; }

    // ....
}

public abstract class BaseEntityRepository: BaseRepository
{
    protected IDbConnection Connection => _connection ?? (_connection = CreateDbConnection(GetConnectionStringValue(ConnectionString)));

    protected abstract IDbConnection CreateDbConnection(string connectionString);

    // SaveEntity<T>(T entity), DeleteEntity(object id)
}

public abstract class BaseEntityRepository<TEntity, TKey, TSearchOptions, TLoadOptions> : BaseEntityRepository
    where TEntity : Entity<TKey>
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    // GetEntities(TSearchOptions sopts, TLoadOptions lopts), EntityCount(TSearchOptions) ...
}

public abstract class BaseLocalizableEntityRepository<TEntity, TKey, TEntityTranslation, TSearchOptions, TLoadOptions> : BaseEntityRepository<TEntity, TSearchOptions, TLoadOptions>
    where TEntity : Entity<TKey>
    where TEntityTranslation : EntityTranslation<TKey>
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    // GetTranslations, SaveTranslation ...
}

Is it good or bad? If it is bad, how should I do it?

Body:
As you need highly customizable localization your solution is not so bad. I perform the same way if I need translation. But instead having a different table per entity-translation I have a unique table to which any entities that support translation reference to:

CREATE TABLE Test_Translations
(
    Language char(10) NOT NULL,
    TextId int NOT NULL,
    Value text NOT NULL,
    CONSTRAINT Test_Translations_Language_TextId_pk PRIMARY KEY (Language, TextId)
);

CREATE TABLE Test_LocalizableStrings
(
    Id int NOT NULL CONSTRAINT Test2_Test1Id_pk primary key
);

ALTER TABLE Test_Translations ADD FOREIGN KEY (TextId) REFERENCES Test_LocalizableStrings;

Then in the tables that need a translation support just create a reference key to Test_LocalizableStrings. At query time query for TextId and Language.


问:
Does the use of styleSheets in a dynamic manner add a lot of computation
I have about 40 buttons that are also indicators (On or Off) and once a second I refresh the color of these indicators depending on the state.  I do this by changing the stylesheet. Is it over kill to do this and if so should I only set a new stylesheet when it the indicator has changed state or should I use something like QBrush?</p>

答:
Yes. I found that with Qt 4.6.2 on Linux, setting a stylesheet to change the colour of the text on a QLabel is very slow.

The dynamic stylesheet looked like a great solution but for me, the necessary setStyle() was just as expensive as setStyleSheet()!

After much experimentation, I found this alternative to be at least twice as quick, and usually more than 50 times as quick:

```<code>QPalette palette = lbl->palette();
palette.setColor(QPalette::WindowText, Qt::gray);
lbl->setPalette(palette);
</code>```

Depending on how your (static) stylesheet is set up, you'd have to replace QPalette::WindowText with QPalette::Window or QPalette::Button. See the QPalette documentation for details.

Body:
Yes. I found that with Qt 4.6.2 on Linux, setting a stylesheet to change the colour of the text on a QLabel is very slow.

The dynamic stylesheet looked like a great solution but for me, the necessary setStyle() was just as expensive as setStyleSheet()!

After much experimentation, I found this alternative to be at least twice as quick, and usually more than 50 times as quick:

QPalette palette = lbl->palette();
palette.setColor(QPalette::WindowText, Qt::gray);
lbl->setPalette(palette);

Depending on how your (static) stylesheet is set up, you'd have to replace QPalette::WindowText with QPalette::Window or QPalette::Button. See the QPalette documentation for details.


问:
Read all available data in serial port with boost asio
I cannot find a way to make what seems to be one of the simplest thing with the boost asio library :

Read all the data available in a serial port

For example in Qt there is a readAll() method from QextSerialPort.

Actually, all the examples I found are about reading a certain amount of data, or multi threaded.

In my case I need it to read the data from a GSM controller. The response size depends on the sent command and the controller context so I can't specify it.

答:
Try this:</p>
```<code>boost::asio::read(
    sock,
    boost::asio::buffer(buf),
    boost::asio::transfer_at_least(1),
    ec
);
</code>```

Body:
Try this:

boost::asio::read(
    sock,
    boost::asio::buffer(buf),
    boost::asio::transfer_at_least(1),
    ec
);


问:
SignalR - Individual variables
I am using SignalR to setup a connection between my client and my server. I would like to store some user data on init. When the user calls a method I want access to these variables to do some calculations and send a response back to the client.

I can not use static variables because I want these variables to be individual for each client. Saving these variables in one global dictionary seems not performant for a lot of users. Saving the data in a database is not an option because the client will call a method approximately every 15-30 seconds and this for a few minutes and then the hub can be disposed.

What I am trying to archieve is one hub instance per client. One open connection with the server, 1-on-1. Is this possible with SignalR and how or do I have to look for another library?

Thanks a lot,

Have a great day!

答:
by trying to get a hub instance per client connection is pretty hard since hubs are designed to be just the opposite (a way to talk to some or all clients connected)

you are probably looking for the Persistent Connection API

PS: I don't really see why you rule out a db so quickly since you could always use an in memory cache like redis.

Title: SignalR - Individual variables


问:
if ( Selection < 0) and (Selection > 3) condition behaves differently for input =4. Why?
```<code>def PrintBlue():
    print (" You chose Blue!\r\n")

def PrintRed():
    print (" You chose Red!\r\n")

def PrintOrange():
    print (" You chose Orange!\r\n")

def PrintYellow():
    print (" You chose Yellow!\r\n")

#Let's create a dictionary with unique key

ColorSelect = {
    0:PrintBlue,
    1:PrintRed,
    2:PrintOrange,
    3:PrintYellow
    }

Selection = 0

while (Selection != 4):
    print ("0.Blue")
    print ("1.Red")
    print ("2.Orange")
    print ("3.Yellow")
    try:
        Selection = int(input("Select a color option: "))
        x=0
        if ( Selection < 0) and (Selection > 3):
            raise KeyError(" Enter a number >=0 and <4)")
        else:
            ColorSelect[Selection]() # Run the function inside dictionary as well
    except KeyError:
        pass
</code>```

Above is my python code. I am using 2.7 version. but after running I got different result for input =4. While I am expecting same result for Selection<0 or >3.Here is result look like:

0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 5
0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 4

Notice after I enter input =4 , python exits from run time.When I enter 0,1,2,3,5,6,7, every time it ask again to enter value again, but when I enter 4 it exits.

答: You have "while (Selection != 4)" on line 24 -- when the selection is equal to 4 the while loop (and the program) exits.</p>

Body:
def PrintBlue():
    print (" You chose Blue!\r\n")

def PrintRed():
    print (" You chose Red!\r\n")

def PrintOrange():
    print (" You chose Orange!\r\n")

def PrintYellow():
    print (" You chose Yellow!\r\n")

#Let's create a dictionary with unique key

ColorSelect = {
    0:PrintBlue,
    1:PrintRed,
    2:PrintOrange,
    3:PrintYellow
    }

Selection = 0

while (Selection != 4):
    print ("0.Blue")
    print ("1.Red")
    print ("2.Orange")
    print ("3.Yellow")
    try:
        Selection = int(input("Select a color option: "))
        x=0
        if ( Selection < 0) and (Selection > 3):
            raise KeyError(" Enter a number >=0 and <4)")
        else:
            ColorSelect[Selection]() # Run the function inside dictionary as well
    except KeyError:
        pass

Above is my python code. I am using 2.7 version. but after running I got different result for input =4. While I am expecting same result for Selection<0 or >3.Here is result look like:

0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 5
0.Blue
1.Red
2.Orange
3.Yellow
Select a color option: 4

Notice after I enter input =4 , python exits from run time.When I enter 0,1,2,3,5,6,7, every time it ask again to enter value again, but when I enter 4 it exits.


问:
Onsen UI, how to use isShow() Method
I'm creating a very simple app, and I'm using Onsen UI and purely JavaScript (no Angular, React, or Vue). This is the first time a use this framework, but so far seems pretty simple and straight forward, except the isShow() method. I have a dialog that I open using:

```<code>document.getElementById(id).show({ animation: "fade" });
</code>```

But now I need to know how to check if the dialog is open or not. I thought that using something like this would work:

```<code>console.log(document.getElementById(id).isShown());
</code>```

But I get a document.getElementById(...).isShown is not a function error message.The only thing I can find is what is says inn the Onsen UI documentation: isShown() Returns whether the popover is visible or not.

How can I determine if a Dialog <ons-dialog> element is open (visible) in Onsen UI?

答: The isShown() method was part of Onsen UI v1. For v2 you can access visible property and get the same value. Docs here.

Title: Onsen UI, how to use isShow() Method

Body:
I'm creating a very simple app, and I'm using Onsen UI and purely JavaScript (no Angular, React, or Vue). This is the first time a use this framework, but so far seems pretty simple and straight forward, except the isShow() method. I have a dialog that I open using:

document.getElementById(id).show({ animation: "fade" });

But now I need to know how to check if the dialog is open or not. I thought that using something like this would work:

console.log(document.getElementById(id).isShown());

But I get a document.getElementById(...).isShown is not a function error message.The only thing I can find is what is says inn the Onsen UI documentation: isShown() Returns whether the popover is visible or not.

How can I determine if a Dialog <ons-dialog> element is open (visible) in Onsen UI?


问:
Changing class combinations based on multiple conditions
I have few style classes defined in my style sheet as like the following:

```<code>.left-align{
  /* some styles here */
}
.right-align{
  /* some styles here */
}
.validate-error{
  /* some styles here */
}
</code>```

Based on the type of data in the class I need to align the content left or right, and also I wanted to call a method which will validate my data in the control, if validation fails need to append the validate-error class as well to the ng-class. I gone through different SO threads and other articles and QA sites that titled as multiple conditions in ng-class but nothing found working in my scenario, I have tried the following based on the references:

```<code>ng-class="{!vm.validate()?'validate-error': vm.isNumericField?'right-align':'left-align'}"
</code>```

But this will not align the content to the right even isNumericField is true when validate() returns false.

In short, I need to add left-align or right-align depends on the isNumericField property and also validate-error if validate() returns false.

```<code> "isNumericField?{'left-align':'right-align'} + 'validate-error':validate()"
</code>```

Please anyone let me know if there any way to achieve this:

答:
You can specify "map" of class names to boolean values:</p>

```<code>ng-class="{'validate-error': !vm.validate(), 'right-align': vm.isNumericField, 'left-align': !vm.isNumericField}"
</code>```

Body:
I have few style classes defined in my style sheet as like the following:

.left-align{
  /* some styles here */
}
.right-align{
  /* some styles here */
}
.validate-error{
  /* some styles here */
}

Based on the type of data in the class I need to align the content left or right, and also I wanted to call a method which will validate my data in the control, if validation fails need to append the validate-error class as well to the ng-class. I gone through different SO threads and other articles and QA sites that titled as multiple conditions in ng-class but nothing found working in my scenario, I have tried the following based on the references:

ng-class="{!vm.validate()?'validate-error': vm.isNumericField?'right-align':'left-align'}"

But this will not align the content to the right even isNumericField is true when validate() returns false.

In short, I need to add left-align or right-align depends on the isNumericField property and also validate-error if validate() returns false.

 "isNumericField?{'left-align':'right-align'} + 'validate-error':validate()"

Please anyone let me know if there any way to achieve this:

Body:
You can specify "map" of class names to boolean values:

ng-class="{'validate-error': !vm.validate(), 'right-align': vm.isNumericField, 'left-align': !vm.isNumericField}"


问:
Centering my Logo Div
I have tried every possible method to center my logo div but no luck. I even ended up going back to old school align="center" but no luck.

Please help - http://rezaee.me/kel/

Cheers

答: Just remove position: fixed; from your CSS for #logo.

Title: Centering my Logo Div


问:
Are there known safety issues caused by floating-point overflow?
IEEE754 standard seems to give floating-point overflow a pass by introducing the infinity representation. It  seems to me that overflow is more tolerated in  floats than in integers. My question is, how dangerous is floating-point overflow? Are there known safety issues caused by undetected floating-point overflow? </p>

<p>(The well-known Ariane 5 explosion is caused by double -> long int conversion, which is not a proper floating-point overflow discussed here.) </p>

答:
In a context of high safety level needed, you shall check for all errors that can affect the result in a substantial way. That sounds tautologic but is still the main principle and nobody can tell you more from his side view, without digging into details. But some general recipes are still expressable. Particularly, if you get INF as a result, this likely means you have no result at all, because you donʼt know how early this infinity appeared, so, the whole result shall be dropped. The same is true for NaN.

Please keep in mind that IEEE754 is IEEE standard, so, it is for adapted for ease of hardware implementation, at least for basic operations, with all related peculiarities and limitations. There are situations that IEEE754 is unsatisfactory: this includes higher precision, variable precision (see e.g. "rounding for shorter precision" == "von Neumann rounding"), interval arithmetic for error tracking, and so on. For them, software implementations shall be used.

But, IEEE754 still provides some measures to cover the most common case set. It supports "exceptions" for all intermediate actions, (and, as already known here, values as INF and NaN), for cases it can't provide a result but still can express a discrepancy in a fast and cheap way. If you concern on all possible issues in calculations, you should, at least,

clear exceptions before calculations

do calculations

check both: final values (neither shall be INF or NaN until you are sure this fits your case), and exceptions (at least: overflow, divide by 0, domain error).

Saying again, this doesnʼt cover all cases, but, typically, most of them.

It's very situation-specific whether underflow and inexact exceptions are worth your attention. Most cases of inexact exception are simply inevitable and not important in physics-related calculations, but they are critical in decimal floating or fixed-point financial calculations. Underflow can be sign of serious issues like catastrophic cancellation.

(The well-known Ariane 5 explosion is caused by double -> long int conversion, which is not a proper floating-point overflow discussed here.)

There is no principal difference for the practical result - it was an overflow that was detected in time, but then respective exception was not handled.

Body:
IEEE754 standard seems to give floating-point overflow a pass by introducing the infinity representation. It  seems to me that overflow is more tolerated in  floats than in integers. My question is, how dangerous is floating-point overflow? Are there known safety issues caused by undetected floating-point overflow?

(The well-known Ariane 5 explosion is caused by double -> long int conversion, which is not a proper floating-point overflow discussed here.)


问:
How to handle null field when exporting MYSQL tables to CSV
Right now when I export MYSQL tables to CSV files, I'm getting \N for NULL fields in the database which is expected. If there a way to change the \N output to just an empty string when exporting tables to csv?

Thanks

```<code>SELECT 'CU_CustomerID','CU_UserName','CU_Password','CU_Email','CU_Company','CU_Comment','CU_LastBasket','CON_FirstName','CON_MiddleI','CON_LastName','CON_Address1','CON_Address2','CON_City','CON_State','CON_Province','CON_Country','CON_Zip','CON_Phone1','CON_Phone2'
UNION
SELECT T1.CU_CustomerID,T1.CU_UserName,T1.CU_Password,T1.CU_Email,T1.CU_Company,T1.CU_Comment,T1.CU_ShopperPoints,T2.CON_FirstName,T2.CON_MiddleI,T2.CON_LastName,T2.CON_Address1,T2.CON_Address2,T2.CON_City,T2.CON_State,T2.CON_Province,T2.CON_Country,T2.CON_Zip,T2.CON_Phone1,T2.CON_Phone2
FROM CUSTOMERS AS T1
INNER JOIN CONTACT AS T2 ON T1.CU_CustomerID = T2.CON_CustomerID
WHERE T1.CU_CustomerID BETWEEN 0 AND 1000
INTO OUTFILE  'customers.csv'
FIELDS TERMINATED BY  ','
ENCLOSED BY  '"'
</code>```

答:
The hardway:-

```
SELECT 'CU_CustomerID','CU_UserName','CU_Password','CU_Email','CU_Company','CU_Comment','CU_LastBasket','CON_FirstName','CON_MiddleI','CON_LastName','CON_Address1','CON_Address2','CON_City','CON_State','CON_Province','CON_Country','CON_Zip','CON_Phone1','CON_Phone2'
UNION
SELECT COALESCE(T1.CU_CustomerID,''),COALESCE(T1.CU_UserName,''),COALESCE(T1.CU_Password,''),COALESCE(T1.CU_Email,''),COALESCE(T1.CU_Company,''),COALESCE(T1.CU_Comment,''),COALESCE(T1.CU_ShopperPoints,''),COALESCE(T2.CON_FirstName,''),COALESCE(T2.CON_MiddleI,''),COALESCE(T2.CON_LastName,''),COALESCE(T2.CON_Address1,''),COALESCE(T2.CON_Address2,''),COALESCE(T2.CON_City,''),COALESCE(T2.CON_State,''),COALESCE(T2.CON_Province,''),COALESCE(T2.CON_Country,''),COALESCE(T2.CON_Zip,''),COALESCE(T2.CON_Phone1,''),COALESCE(T2.CON_Phone2,'')
FROM CUSTOMERS AS T1
INNER JOIN CONTACT AS T2 ON T1.CU_CustomerID = T2.CON_CustomerID
WHERE T1.CU_CustomerID BETWEEN 0 AND 1000
INTO OUTFILE  'customers.csv'
FIELDS TERMINATED BY  ','
ENCLOSED BY  '"'
```

This will default all values to an empty string rather than NULL ('\N').

Body:
Right now when I export MYSQL tables to CSV files, I'm getting \N for NULL fields in the database which is expected. If there a way to change the \N output to just an empty string when exporting tables to csv?

Thanks

SELECT 'CU_CustomerID','CU_UserName','CU_Password','CU_Email','CU_Company','CU_Comment','CU_LastBasket','CON_FirstName','CON_MiddleI','CON_LastName','CON_Address1','CON_Address2','CON_City','CON_State','CON_Province','CON_Country','CON_Zip','CON_Phone1','CON_Phone2'
UNION
SELECT T1.CU_CustomerID,T1.CU_UserName,T1.CU_Password,T1.CU_Email,T1.CU_Company,T1.CU_Comment,T1.CU_ShopperPoints,T2.CON_FirstName,T2.CON_MiddleI,T2.CON_LastName,T2.CON_Address1,T2.CON_Address2,T2.CON_City,T2.CON_State,T2.CON_Province,T2.CON_Country,T2.CON_Zip,T2.CON_Phone1,T2.CON_Phone2
FROM CUSTOMERS AS T1
INNER JOIN CONTACT AS T2 ON T1.CU_CustomerID = T2.CON_CustomerID
WHERE T1.CU_CustomerID BETWEEN 0 AND 1000
INTO OUTFILE  'customers.csv'
FIELDS TERMINATED BY  ','
ENCLOSED BY  '"'

Body:
The hardway:-

SELECT 'CU_CustomerID','CU_UserName','CU_Password','CU_Email','CU_Company','CU_Comment','CU_LastBasket','CON_FirstName','CON_MiddleI','CON_LastName','CON_Address1','CON_Address2','CON_City','CON_State','CON_Province','CON_Country','CON_Zip','CON_Phone1','CON_Phone2'
UNION
SELECT COALESCE(T1.CU_CustomerID,''),COALESCE(T1.CU_UserName,''),COALESCE(T1.CU_Password,''),COALESCE(T1.CU_Email,''),COALESCE(T1.CU_Company,''),COALESCE(T1.CU_Comment,''),COALESCE(T1.CU_ShopperPoints,''),COALESCE(T2.CON_FirstName,''),COALESCE(T2.CON_MiddleI,''),COALESCE(T2.CON_LastName,''),COALESCE(T2.CON_Address1,''),COALESCE(T2.CON_Address2,''),COALESCE(T2.CON_City,''),COALESCE(T2.CON_State,''),COALESCE(T2.CON_Province,''),COALESCE(T2.CON_Country,''),COALESCE(T2.CON_Zip,''),COALESCE(T2.CON_Phone1,''),COALESCE(T2.CON_Phone2,'')
FROM CUSTOMERS AS T1
INNER JOIN CONTACT AS T2 ON T1.CU_CustomerID = T2.CON_CustomerID
WHERE T1.CU_CustomerID BETWEEN 0 AND 1000
INTO OUTFILE  'customers.csv'
FIELDS TERMINATED BY  ','
ENCLOSED BY  '"'

This will default all values to an empty string rather than NULL ('\N').


问:
jboss maven project add jar not exist in public repository
I need to add a jar not exist in publi repo to my maven project i have using system scope like this :

```<code><dependency>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>X.Y.Z</version>
  <scope>system</scope>
  <systemPath>${user.home}/jars/my.jar</systemPath>
</dependency>
</code>```

This solution working fine in local machine but not in distant server. when i google it i find that system scope is aleardy a bad practice so there is another solution to add a jar to project?

答:
You have two options here.

First:

```<code><dependency>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>X.Y.Z</version>
  <scope>system</scope>
  <systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>
</code>```

Second:

Install this jar in your local repository and it will be included in your built project.
You can add jar in you local repository like this:

```<code>    mvn install:install-file
   -Dfile=<path-to-file>
   -DgroupId=<group-id>
   -DartifactId=<artifact-id>
   -Dversion=<version>
   -Dpackaging=<packaging>
   -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
   <group-id>      the group that the file should be registered under
   <artifact-id>   the artifact name for the file
   <version>       the version of the file
   <packaging>     the packaging of the file e.g. jar
</code>```

Edit your pom.xml

```<code> <dependency>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>X.Y.Z</version>
</dependency>
</code>```

Body:
I need to add a jar not exist in publi repo to my maven project i have using system scope like this :

<dependency>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>X.Y.Z</version>
  <scope>system</scope>
  <systemPath>${user.home}/jars/my.jar</systemPath>
</dependency>

This solution working fine in local machine but not in distant server. when i google it i find that system scope is aleardy a bad practice so there is another solution to add a jar to project?

Body:
You have two options here.

First:

<dependency>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>X.Y.Z</version>
  <scope>system</scope>
  <systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>

Second:

Install this jar in your local repository and it will be included in your built project.
You can add jar in you local repository like this:

    mvn install:install-file
   -Dfile=<path-to-file>
   -DgroupId=<group-id>
   -DartifactId=<artifact-id>
   -Dversion=<version>
   -Dpackaging=<packaging>
   -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
   <group-id>      the group that the file should be registered under
   <artifact-id>   the artifact name for the file
   <version>       the version of the file
   <packaging>     the packaging of the file e.g. jar

Edit your pom.xml

 <dependency>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>X.Y.Z</version>
</dependency>


问:
StatusBarNotification how to get data or resend intent?
My Apps receives Push Notification via Firebase. Now there a 3 distinct situations that can happen when the notification arrives:

The app is in the foreground

The app is in the background

The app is not running

Situation 1 is no problem. The notification is received in the app ok.
Situation 2 and 3 work fine as long as you tap the notification in the drawer.
In Situation 2 and 3 when the app icon is tapped instead of the drawer icon the app does not receive any notification at all. I've tried to get the active notifications from the StatusBar and that works but I can not either retrieve the data from the Extras or resend the notification to the waiting push notification service. Here's the experimental code to get the Notifications.

```<code>        NotificationManager notificationManager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService);

        var notifications = notificationManager.GetActiveNotifications()
            .Where(notif => notif.PackageName == Application.Context.PackageName);

        foreach (var notification in notifications)
        {
            Log.Info(TAG, "OnActivityResumed: Notification in active in Status Bar: {0}", notification.Notification.ToString());

            var data = notification.Notification.Extras.GetString("data");

            Log.Debug("Notifier", "Data received: {0}", data);

            //if (data != null)
            //{
            //    Settings.Notification = JsonConvert.DeserializeObject<LoginNotificationParameter>(data);
            //}
        }

        // Canceling all notifications
        notificationManager.CancelAll();
</code>```

Questions:

Is it correct behavior that the app does not receive any intents when a notification is in the drawer?

If so how to I handle situations 2 and 3 when the user tapps the app icon instead of the drawer notification?

I see this data in het Notification when printing all the Extras Key Values:

```<code>06-28 16:34:13.174 20792 20792 I Notifier: OnActivityResumed: Notification is active in Status Bar: Notification(pri=0 contentView=null vibrate=null sound=content://settings/system/notification_sound defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0)
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.title Data: Login
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.subText Data:
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.template Data: android.app.Notification$BigTextStyle
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.showChronometer Data: false
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.text Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progress Data: 0
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progressMax Data: 0
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.appInfo Data: ApplicationInfo{a27f281 nl.natuurnetwerk.notifier}
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.showWhen Data: true
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.largeIcon Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.bigText Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.infoText Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.originatingUserId Data: 0
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.progressIndeterminate Data: false
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.remoteInputHistory Data:
</code>```

答:
Ok, this works for me for all app states I can think of:</p>

```<code>using Android.App;
using Android.Content;
using Android.OS;
using MvvmCross.Droid.Platform;
using MvvmCross.Droid.Support.V4;

namespace Notifier.Android.Classes.Services
{
    /// <summary>
    /// This class receives all Firebase intents.
    /// </summary>
    [BroadcastReceiver(Enabled = true, Permission = "com.google.android.c2dm.permission.SEND")]
    [IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[] { "com.yourdomain.yourapp" })]
    public class FirebaseBroadcastReceiver : MvxWakefulBroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            var setup = MvxAndroidSetupSingleton.EnsureSingletonAvailable(context);
            setup.EnsureInitialized();

            var service = new Intent(context, typeof(FirebaseBroadcastReceiver));

            PowerManager.WakeLock sWakeLock;
            var pm = PowerManager.FromContext(context);
            sWakeLock = pm.NewWakeLock(WakeLockFlags.Full, "FirebaseBroadcastReceiver");
            sWakeLock.Acquire();

            if (intent.Extras != null)
            {
                // Your code to handle the intent
            }

            sWakeLock.Release();

            StartWakefulService(context, service);
        }
    }
}
</code>```

Body:
My Apps receives Push Notification via Firebase. Now there a 3 distinct situations that can happen when the notification arrives:

The app is in the foreground

The app is in the background

The app is not running

Situation 1 is no problem. The notification is received in the app ok.
Situation 2 and 3 work fine as long as you tap the notification in the drawer.
In Situation 2 and 3 when the app icon is tapped instead of the drawer icon the app does not receive any notification at all. I've tried to get the active notifications from the StatusBar and that works but I can not either retrieve the data from the Extras or resend the notification to the waiting push notification service. Here's the experimental code to get the Notifications.

        NotificationManager notificationManager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService);

        var notifications = notificationManager.GetActiveNotifications()
            .Where(notif => notif.PackageName == Application.Context.PackageName);

        foreach (var notification in notifications)
        {
            Log.Info(TAG, "OnActivityResumed: Notification in active in Status Bar: {0}", notification.Notification.ToString());

            var data = notification.Notification.Extras.GetString("data");

            Log.Debug("Notifier", "Data received: {0}", data);

            //if (data != null)
            //{
            //    Settings.Notification = JsonConvert.DeserializeObject<LoginNotificationParameter>(data);
            //}
        }

        // Canceling all notifications
        notificationManager.CancelAll();

Questions:

Is it correct behavior that the app does not receive any intents when a notification is in the drawer?

If so how to I handle situations 2 and 3 when the user tapps the app icon instead of the drawer notification?

I see this data in het Notification when printing all the Extras Key Values:

06-28 16:34:13.174 20792 20792 I Notifier: OnActivityResumed: Notification is active in Status Bar: Notification(pri=0 contentView=null vibrate=null sound=content://settings/system/notification_sound defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0)
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.title Data: Login
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.subText Data:
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.template Data: android.app.Notification$BigTextStyle
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.showChronometer Data: false
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.text Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progress Data: 0
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progressMax Data: 0
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.appInfo Data: ApplicationInfo{a27f281 nl.natuurnetwerk.notifier}
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.showWhen Data: true
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.largeIcon Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.bigText Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.infoText Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.originatingUserId Data: 0
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.progressIndeterminate Data: false
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.remoteInputHistory Data:

Body:
Ok, this works for me for all app states I can think of:

using Android.App;
using Android.Content;
using Android.OS;
using MvvmCross.Droid.Platform;
using MvvmCross.Droid.Support.V4;

namespace Notifier.Android.Classes.Services
{
    /// <summary>
    /// This class receives all Firebase intents.
    /// </summary>
    [BroadcastReceiver(Enabled = true, Permission = "com.google.android.c2dm.permission.SEND")]
    [IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[] { "com.yourdomain.yourapp" })]
    public class FirebaseBroadcastReceiver : MvxWakefulBroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            var setup = MvxAndroidSetupSingleton.EnsureSingletonAvailable(context);
            setup.EnsureInitialized();

            var service = new Intent(context, typeof(FirebaseBroadcastReceiver));

            PowerManager.WakeLock sWakeLock;
            var pm = PowerManager.FromContext(context);
            sWakeLock = pm.NewWakeLock(WakeLockFlags.Full, "FirebaseBroadcastReceiver");
            sWakeLock.Acquire();

            if (intent.Extras != null)
            {
                // Your code to handle the intent
            }

            sWakeLock.Release();

            StartWakefulService(context, service);
        }
    }
}


问:
Python UTF8 encoding
I have looked at other questions around Python and encoding but not quite found the solution to my problem. Here it is:

I have a small script which attempts to compare 2 lists of files:

A list given in a text file, which is supposed to be encoded in UTF8 (at least Notepad++ detects it as such).

A list from a directory which I build like this:

```<code>local = [f.encode('utf-8') for f in listdir(dir) ]
</code>```

However, for some characters, I do not get the same representation: when looking in a HEX editor, I find that in 1, the  character é is given by 65 cc whereas in 2 it is given by c3 a9 ...

What I would like is to have them to the same encoding, whatever it is.

答:
Your first sequence is incomplete - cc is the prefix for a two-byte UTF-8 sequence. Most probably, the full sequence is 65 cc 81, which indeed is the character e (0x65) followed by a COMBINING ACUTE ACCENT (0x301, which in UTF-8 gets expressed as cc 81).

The other sequence instead is the precomposed LATIN SMALL LETTER E WITH ACUTE character (0xe9, expressed as c3 a9 in UTF-8). You'll notice in the linked page that its decomposition is exactly the first sequence.

Unicode normalization

Now, in Unicode there are many instances of different sequences that graphically and/or semantically are the same, and while it's generally a good idea to treat a UTF-8 stream as an opaque binary sequence, this poses a problem if you want to do searching or indexing - looking for one sequence won't match the other, even if they are graphically and semantically the same thing. For this reason, Unicode defines four types of normalization, that can be used to "flatten" this kind of differences and obtain the same codepoints from both the composed and decomposed forms. For example, the NFC and NFKC normalization forma in this case will give the 0xe9 code point for both your sequences, while the NFD and NFKD will give the 0x65 0x301 decomposed form.

To do this in Python you'll have first to decode your UTF-8 str objects to unicode objects, and then use the unicodedata.normalize method.

Important note: don't normalize unless you are implementing "intelligent" indexing/searching, and use the normalized data only for this purpose - i.e index and search normalized, but store/provide to the user the original form. Normalization is a lossy operation (some forms particularly so), applying it blindly over user data is like entering with a sledgehammer in a pottery shop.

File paths

Ok, this was about Unicode in general. Talking about filesystem paths is both simpler and more complicated.

In line of principle, virtually all common filesystems on Windows and Linux treat paths as opaque character1 sequences (modulo the directory separator and possibly the NUL character), with no particular normalization form applied2. So, in a given directory you can have two file names that look the same but are indeed different:

So, when dealing with file paths in line of principle you should never normalize - again, file paths are an opaque sequence of code points (actually, an opaque sequence of bytes on Linux) which should not be messed with.

However, if the list you receive and you have to deal with is normalized differently (which probably means that either it has been passed through a broken software that "helpfully" normalizes composed/decomposed sequences, or that the name has been typed in by hand) you'll have to perform some normalized matching.

If I were to deal with a similar (broken by definition) scenario, I'd do something like this:

first try to match exactly;

if this fails, try to match the normalized file name against a set containing the normalized content of the directory; notice that, if multiple original names are mapped to the same normalized name and you don't match it exactly you have no way to know which one is the "right one".

Footnotes

Linux-native filesystems all use 8-bit byte-based paths - they may be in whatever encoding, the kernel doesn't care, although recent systems generally happen to use UTF-8; Windows-native filesystem will instead use 16-bit word-based paths, which nominally contain UTF-16 (originally UCS-2) values.

On Windows it's a bit more complicated at the API level, since there's the whole ANSI API mess that performs codepage conversion, and case-insensitive matching for Win32 paths adds one more level of complication, but down at kernel and filesystem level it's all opaque 2-byte WCHAR strings.

Title: Python UTF8 encoding

Body:
I have looked at other questions around Python and encoding but not quite found the solution to my problem. Here it is:

I have a small script which attempts to compare 2 lists of files:

A list given in a text file, which is supposed to be encoded in UTF8 (at least Notepad++ detects it as such).

A list from a directory which I build like this:

local = [f.encode('utf-8') for f in listdir(dir) ]

However, for some characters, I do not get the same representation: when looking in a HEX editor, I find that in 1, the  character é is given by 65 cc whereas in 2 it is given by c3 a9 ...

What I would like is to have them to the same encoding, whatever it is.


问:
Is mousemove event fire once in per frame?
In this fiddle demo, press and move the mouse will draw the dot according to the mouse's position. The draw method is listen to mousemove callback, but it draw the discrete dot which show that the mousemove event is not fired continuously.

What is more, I collect the event.timeStamp and log in console. I found that the offset between adjacent event is near 16.7ms. So is mousemove event fire once in per frame?

答:
The mousemove event frequency is implementation specific, and not defined by any specification.

A user agent MUST dispatch this event when a pointing device is moved while it is over an element. The frequency rate of events while the pointing device is moved is implementation-, device-, and platform-specific, but multiple consecutive mousemove events SHOULD be fired for sustained pointer-device movement, rather than a single event for each instance of mouse movement. Implementations are encouraged to determine the optimal frequency rate to balance responsiveness with performance.

-- UI Events, W3C Working Draft, 04 August 2016

It's entirely possible some browsers on some platforms will limit it to once per-frame. There is no guarantee any browser that may do this will continue to do so however.

If you want to draw a continuous line, you would need to create interpolation data between each two points.


问:
Can I use SQL's IN(...) statement for a namedQuery?
How can I use IN at my namedQuery?

```<code>@NamedQueries(
 {
 @NamedQuery(name = "GetAvailableProducts", query = new StringBuilder("").append("SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN ('I want to define changeable size of an array or sometinhg like that') OR p.available = :available)")),
 }
</code>```

I mean that I can set 'type' parameter (I defined it as a variable----> :type) and I want to define variables inside of IN statement to. However the number of parameters are not constant. I want to define an array or something like that :array[] and I want to set it when I call that namedQuery.

答:
NamedQuery

```<code>@NamedQueries(
{
 @NamedQuery(name = "GetAvailableProducts", query = "FROM Product p WHERE p.type= :type AND (p.available IN (:availableCollection) OR p.available = :available)",
}
</code>```

Set parameters

Hibernate:

```<code>query.setParameterList('availableCollection', yourCollection);
</code>```

JPA:

```<code>query.setParameter('availableCollection', yourCollection);
</code>```

Body:
How can I use IN at my namedQuery?

@NamedQueries(
 {
 @NamedQuery(name = "GetAvailableProducts", query = new StringBuilder("").append("SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN ('I want to define changeable size of an array or sometinhg like that') OR p.available = :available)")),
 }

I mean that I can set 'type' parameter (I defined it as a variable----> :type) and I want to define variables inside of IN statement to. However the number of parameters are not constant. I want to define an array or something like that :array[] and I want to set it when I call that namedQuery.

Body:
NamedQuery

@NamedQueries(
{
 @NamedQuery(name = "GetAvailableProducts", query = "FROM Product p WHERE p.type= :type AND (p.available IN (:availableCollection) OR p.available = :available)",
}

Set parameters

Hibernate:

query.setParameterList('availableCollection', yourCollection);

JPA:

query.setParameter('availableCollection', yourCollection);


问:
How to implement threading to run two bash shell commands in python?
I have to record a wav file and at the same time I have to analyze it with sox. I am using fifo type file for this operation.

So here I need to start 2 threads at the same time but even if I use the threads I am not able to achieve what I wanna do. Always one executing first and then the other. I want them to be in parallel so that I can do some stuff.

```<code>#this should be in one thread
def test_wav(self):
    """ analyze the data """
    bashCommand = "sox {} -n stat".format(self.__rawfile)
    while self.__rec_thread.is_alive():
        process = subprocess.Popen(bashCommand.split(),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        wav_output = process.communicate()[1] #sox outputs the details in stderr
        #do something and return

#this should be in another thread
def record_wav(self):
    bashCommand = "arecord -d 10 -c 2 -r 48000 -f S32_LE > {}".format(self.__rawfile)
    pid = subprocess.Popen(bashCommand.split())
    pid.wait()
    if pid.returncode != 0:
        raise RecordException("Failed while recording with error {}".format(pid.returncode))
</code>```

I tried the following code to make them threads but failed(Always one executing first and then the other. I want them to be in parallel so that I can do some stuff).
imported from threading import Thread

```<code>self.__rec_thread = Thread(target = self.record_wav())
amp_thread = Thread(target = self.test_wav())
self.__rec_thread.start()
amp_thread.start()
</code>```

EDIT: First its executing the record(it minimum takes 10 sec because of the option -d 10) function completely and then the test wav function. Its like calling them one after another.

答:
if you probably use python3, you can use asyncio to run the shell command in goroutines way.</p>

```<code>import asyncio
import sys

async def execute(command, cwd=None, shell=True):
    process = await asyncio.create_subprocess_exec(*command,
                                                   stdout=asyncio.subprocess.PIPE,
                                                   stderr=asyncio.subprocess.PIPE,
                                                   cwd=cwd,
                                                   shell=shell)
    std_out, std_err = await process.communicate()

    error = std_err.decode().strip()
    result = std_out.decode().strip()
    print(result)
    print(error)
    return result

if sys.platform == "win32":
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(
        asyncio.gather(execute(["bash", "-c", "echo hello && sleep 2"]), execute(["bash", "-c", "echo ok && sleep 1"])))
except Exception as e:
    raise e
finally:
    loop.close()
</code>```

Body:
I have to record a wav file and at the same time I have to analyze it with sox. I am using fifo type file for this operation.

So here I need to start 2 threads at the same time but even if I use the threads I am not able to achieve what I wanna do. Always one executing first and then the other. I want them to be in parallel so that I can do some stuff.

#this should be in one thread
def test_wav(self):
    """ analyze the data """
    bashCommand = "sox {} -n stat".format(self.__rawfile)
    while self.__rec_thread.is_alive():
        process = subprocess.Popen(bashCommand.split(),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        wav_output = process.communicate()[1] #sox outputs the details in stderr
        #do something and return

#this should be in another thread
def record_wav(self):
    bashCommand = "arecord -d 10 -c 2 -r 48000 -f S32_LE > {}".format(self.__rawfile)
    pid = subprocess.Popen(bashCommand.split())
    pid.wait()
    if pid.returncode != 0:
        raise RecordException("Failed while recording with error {}".format(pid.returncode))

I tried the following code to make them threads but failed(Always one executing first and then the other. I want them to be in parallel so that I can do some stuff).
imported from threading import Thread

self.__rec_thread = Thread(target = self.record_wav())
amp_thread = Thread(target = self.test_wav())
self.__rec_thread.start()
amp_thread.start()

EDIT: First its executing the record(it minimum takes 10 sec because of the option -d 10) function completely and then the test wav function. Its like calling them one after another.

Body:
if you probably use python3, you can use asyncio to run the shell command in goroutines way.

import asyncio
import sys

async def execute(command, cwd=None, shell=True):
    process = await asyncio.create_subprocess_exec(*command,
                                                   stdout=asyncio.subprocess.PIPE,
                                                   stderr=asyncio.subprocess.PIPE,
                                                   cwd=cwd,
                                                   shell=shell)
    std_out, std_err = await process.communicate()

    error = std_err.decode().strip()
    result = std_out.decode().strip()
    print(result)
    print(error)
    return result

if sys.platform == "win32":
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(
        asyncio.gather(execute(["bash", "-c", "echo hello && sleep 2"]), execute(["bash", "-c", "echo ok && sleep 1"])))
except Exception as e:
    raise e
finally:
    loop.close()


问:
Toolbaritem in ToolBar not Firing when click
My code is as below. I dont know if the Command is implemented correctly for the ToolbarItem. There is no error in compiling. When the baritem is clicked, nothing happen.</p>

```<code>--- Xaml

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:local ="clr-namespace:SembIWIS.View"
            BackgroundColor="White"
            Title="Repair and Service"
            x:Class="MyMainMenu">
    <ContentPage.ToolbarItems>
        <ToolbarItem Name="MenuItem1" Order="Primary" Icon="itemIcon1" Command="{Binding Item1Command}"  Priority="0" />
        <ToolbarItem Name="MenuItem2" Order="Primary" Icon="itemIcon2" Priority="1" />
    </ContentPage.ToolbarItems>

    <local:Product>
    </local:Product>

    <local:Service>
    </local:Service>

</TabbedPage>

--------- Code Behind:

public partial class MyMainMenu : TabbedPage
    {
        public ICommand Item1Command { get; private set; }

        public MyMainMenu()
        {
            InitializeComponent();

            BindingContext = this;

            NavigationPage.SetHasBackButton(this, true);
            Init();
        }

        private void Init()
        {

          this.Item1Command = new Command((sender) =>
          {
               Navigation.PushAsync(new UpdateProduct());
          });

}
</code>```

答:
From the comments I gather that you have forgotten to add the BindingContext. While you did add it right now, the timing is wrong. You need to execute the Init(); method before you set the BindingContext.

When the BindingContext is set, at that point everything is wired up and any change you make will not be picked up, unless you implement the INotifyPropertyChanged interface correctly. Anyhow, for this problem, adapt your code to this:

```<code>public MyMainMenu()
{
    InitializeComponent();

    NavigationPage.SetHasBackButton(this, true);
    Init();

    BindingContext = this;
}
</code>```

In regard to your question on performance and unit tests in the comment:

There is no performance difference because whichever MVVM framework you will use will execute this very same code only it will do it for you automatically. If anything, the MVVM framework will probably be a tad slower because it will probably resolve your ViewModels with reflection or something similar. If you want to do unit tests you will have to split your code into a separate ViewModel and set that as your BindingContext. For example have a look at this blog post on using FreshMvvm with separate Views and ViewModels.

Body:
My code is as below. I dont know if the Command is implemented correctly for the ToolbarItem. There is no error in compiling. When the baritem is clicked, nothing happen.

--- Xaml

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:local ="clr-namespace:SembIWIS.View"
            BackgroundColor="White"
            Title="Repair and Service"
            x:Class="MyMainMenu">
    <ContentPage.ToolbarItems>
        <ToolbarItem Name="MenuItem1" Order="Primary" Icon="itemIcon1" Command="{Binding Item1Command}"  Priority="0" />
        <ToolbarItem Name="MenuItem2" Order="Primary" Icon="itemIcon2" Priority="1" />
    </ContentPage.ToolbarItems>

    <local:Product>
    </local:Product>

    <local:Service>
    </local:Service>

</TabbedPage>

--------- Code Behind:

public partial class MyMainMenu : TabbedPage
    {
        public ICommand Item1Command { get; private set; }

        public MyMainMenu()
        {
            InitializeComponent();

            BindingContext = this;

            NavigationPage.SetHasBackButton(this, true);
            Init();
        }

        private void Init()
        {

          this.Item1Command = new Command((sender) =>
          {
               Navigation.PushAsync(new UpdateProduct());
          });

}

Body:
From the comments I gather that you have forgotten to add the BindingContext. While you did add it right now, the timing is wrong. You need to execute the Init(); method before you set the BindingContext.

When the BindingContext is set, at that point everything is wired up and any change you make will not be picked up, unless you implement the INotifyPropertyChanged interface correctly. Anyhow, for this problem, adapt your code to this:

public MyMainMenu()
{
    InitializeComponent();

    NavigationPage.SetHasBackButton(this, true);
    Init();

    BindingContext = this;
}

In regard to your question on performance and unit tests in the comment:

There is no performance difference because whichever MVVM framework you will use will execute this very same code only it will do it for you automatically. If anything, the MVVM framework will probably be a tad slower because it will probably resolve your ViewModels with reflection or something similar. If you want to do unit tests you will have to split your code into a separate ViewModel and set that as your BindingContext. For example have a look at this blog post on using FreshMvvm with separate Views and ViewModels.


答: don't make its position: fixed</p>

Title: Centering my Logo Div

Body:
I have tried every possible method to center my logo div but no luck. I even ended up going back to old school align="center" but no luck.

Please help - http://rezaee.me/kel/

Cheers

Body: don't make its position: fixed


问:
jar related to hadoop-2.7.3 is not found in lib folder
I downloaded Hadoop 2.7.3 version now I want all jar related to this version but inside lib folder of this version not showing any jar.Previously when I was working on hadoop-1.2.1 inside lib folder of it I got all the jar.So from where could I get all jar related to Hadoop -2.7.3
thanks in advance</p>

答:
In Hadoop 2.x, the jar location has changed from ${HADOOP_HOME}/lib to ${HADOOP_HOME}/share/hadoop/common/lib

All the jars can be found at:

```<code>${HADOOP_HOME}/share/hadoop/common
${HADOOP_HOME}/share/hadoop/common/lib
${HADOOP_HOME}/share/hadoop/mapreduce
${HADOOP_HOME}/share/hadoop/mapreduce/lib
${HADOOP_HOME}/share/hadoop/yarn
${HADOOP_HOME}/share/hadoop/yarn/lib
</code>```

You might also want to take a look at : Migrating fro Hadoop MRv1 to MRv2

Body:
In Hadoop 2.x, the jar location has changed from ${HADOOP_HOME}/lib to ${HADOOP_HOME}/share/hadoop/common/lib

All the jars can be found at:

${HADOOP_HOME}/share/hadoop/common
${HADOOP_HOME}/share/hadoop/common/lib
${HADOOP_HOME}/share/hadoop/mapreduce
${HADOOP_HOME}/share/hadoop/mapreduce/lib
${HADOOP_HOME}/share/hadoop/yarn
${HADOOP_HOME}/share/hadoop/yarn/lib

You might also want to take a look at : Migrating fro Hadoop MRv1 to MRv2


问:
TCL man page: it is better to place comment section way ahead
I know I am really picky here, but like to throw it out in case I am off in my interpreting the TCL man page, actually, I wish I was wrong here, as you see the below story.

So for every new TCL developer, we recommend reading the famous "11 rules" (now it is 12 rules).

Yesterday I was asked this question: why does the following script fail?

```<code># puts "hello
world!"
</code>```

Of course it fails, I said, the first line is taken as comment, that leaves world!" as a command.

But, the newbie said, the manpage indicates that the script is parsed in certain order:

As #2 Evaluation states, the command is parsed to words first.

As #4 Double quotes states, newline is taken as is in parsing double quotes. This makes hello and world! into one word, with a newline in between.

Comments at #10 does states everything up till the next newline is ignored, but after the above processing, the newline should be the 2nd newline, the one after world!.

I see he had a point.

It makes more sense to move the comment section way ahead in the man page, maybe at the second section. With this order change, it indicates that comment recognition is preceding the word-tokenizing process.

How do you think?

Again, I have no intention to ask for change of the manpage, just want to make sure if I miss anything in interpreting the bible.

[UPDATE]
To the people suggesting to close this question as not-a-technical question, it is the same as if my colleague came here asking why that script fails even though his understanding of TCL man page indicates it is a good script.

Again, I am not asking to change the man page.

Let me re-phrase my question - when you are asked this same question, what flaw do you see in his reasoning?

[UPDATE2]
Thanks Donal. I think this is what I learnt, TCL parser goes one char by another, there is no look-ahead.

This is another example:

```<code>puts [#haha]
</code>```

Such script fails at tclsh for the same reason, TCL parser does not break down the script first and only parses the string embedded inside the matching brackets, instead it recognizes "#" as the start of comment and ignores everything after it.

答:
The rules in the Tcl(n) manual page describe pretty precisely the parser that Tcl uses. Requests to change it substantively are usually denied as they tend to have far-reaching consequences and interact with each other trickily. Verifying that a reordering of the rules is not substantive is a non-trivial task, as they correspond to quite a bit of code (our parser and a chunk of our bytecode compiler).

Adding non-normative sections (e.g., EXAMPLES) is easier.

Update based on your updated question

The problem with the reasoning is that the rules are a whole, not really a layered set of parts. They do interact with each other. (The one that usually trips people up is the interaction between the brace rule and the comment rule when inside a braced string such as a procedure body.) Comments really are true comments, and extend up to the end of the line (allowing for backslash-newline sequences) but not beyond, but they only start at places where commands start, not at other places with a # character, and that's the genuinely tricky bit.

Unfortunately, the way that the Tcl parser works is a bit different to the way that programmers think, but most of the time it's pretty good at pretending to work in a “reasonable fashion”. The tricky edge cases don't actually come up too often other than when dealing with the brace-comment interaction mentioned above. The other cases which I hit tend to be either with a switch (resolvable by just putting the comment in the arm) or with long literal lists of things where I want to comment some sections of the list; in that latter case, I actually post-process the string before using it as a list.

```<code>set exampleList {
    a b c
    d e f
    # Not really a comment but I want to use it like one!
    g h i
    j k l
}
# Convert “comment” lines to empty lines
regsub -all -line "^\\s*#.*$" $exampleList "" exampleList
</code>```

The general advantage of Tcl's rules is that it is actually pretty easy to embed other languages within Tcl, precisely because Tcl only treats # (and other character) as special in well-defined contexts. As long as you can have the embedded language be one that uses balanced braces — and that's almost all of them in practice — then embedding it is utterly trivial. The other cases have to use backslashes and/or double quotes and are pretty ugly, but are also a minuscule fraction of all the embedding cases.

Your colleague's problem is that he's looking at the whole script in one go, whereas the Tcl parser handles one character at a time and doesn't do meaningful amounts of lookahead. It's just some dumb code.

Body:
I know I am really picky here, but like to throw it out in case I am off in my interpreting the TCL man page, actually, I wish I was wrong here, as you see the below story.

So for every new TCL developer, we recommend reading the famous "11 rules" (now it is 12 rules).

Yesterday I was asked this question: why does the following script fail?

# puts "hello
world!"

Of course it fails, I said, the first line is taken as comment, that leaves world!" as a command.

But, the newbie said, the manpage indicates that the script is parsed in certain order:

As #2 Evaluation states, the command is parsed to words first.

As #4 Double quotes states, newline is taken as is in parsing double quotes. This makes hello and world! into one word, with a newline in between.

Comments at #10 does states everything up till the next newline is ignored, but after the above processing, the newline should be the 2nd newline, the one after world!.

I see he had a point.

It makes more sense to move the comment section way ahead in the man page, maybe at the second section. With this order change, it indicates that comment recognition is preceding the word-tokenizing process.

How do you think?

Again, I have no intention to ask for change of the manpage, just want to make sure if I miss anything in interpreting the bible.

[UPDATE]
To the people suggesting to close this question as not-a-technical question, it is the same as if my colleague came here asking why that script fails even though his understanding of TCL man page indicates it is a good script.

Again, I am not asking to change the man page.

Let me re-phrase my question - when you are asked this same question, what flaw do you see in his reasoning?

[UPDATE2]
Thanks Donal. I think this is what I learnt, TCL parser goes one char by another, there is no look-ahead.

This is another example:

puts [#haha]

Such script fails at tclsh for the same reason, TCL parser does not break down the script first and only parses the string embedded inside the matching brackets, instead it recognizes "#" as the start of comment and ignores everything after it.

Body:
The rules in the Tcl(n) manual page describe pretty precisely the parser that Tcl uses. Requests to change it substantively are usually denied as they tend to have far-reaching consequences and interact with each other trickily. Verifying that a reordering of the rules is not substantive is a non-trivial task, as they correspond to quite a bit of code (our parser and a chunk of our bytecode compiler).

Adding non-normative sections (e.g., EXAMPLES) is easier.

Update based on your updated question

The problem with the reasoning is that the rules are a whole, not really a layered set of parts. They do interact with each other. (The one that usually trips people up is the interaction between the brace rule and the comment rule when inside a braced string such as a procedure body.) Comments really are true comments, and extend up to the end of the line (allowing for backslash-newline sequences) but not beyond, but they only start at places where commands start, not at other places with a # character, and that's the genuinely tricky bit.

Unfortunately, the way that the Tcl parser works is a bit different to the way that programmers think, but most of the time it's pretty good at pretending to work in a “reasonable fashion”. The tricky edge cases don't actually come up too often other than when dealing with the brace-comment interaction mentioned above. The other cases which I hit tend to be either with a switch (resolvable by just putting the comment in the arm) or with long literal lists of things where I want to comment some sections of the list; in that latter case, I actually post-process the string before using it as a list.

set exampleList {
    a b c
    d e f
    # Not really a comment but I want to use it like one!
    g h i
    j k l
}
# Convert “comment” lines to empty lines
regsub -all -line "^\\s*#.*$" $exampleList "" exampleList

The general advantage of Tcl's rules is that it is actually pretty easy to embed other languages within Tcl, precisely because Tcl only treats # (and other character) as special in well-defined contexts. As long as you can have the embedded language be one that uses balanced braces — and that's almost all of them in practice — then embedding it is utterly trivial. The other cases have to use backslashes and/or double quotes and are pretty ugly, but are also a minuscule fraction of all the embedding cases.

Your colleague's problem is that he's looking at the whole script in one go, whereas the Tcl parser handles one character at a time and doesn't do meaningful amounts of lookahead. It's just some dumb code.


问:
Call event in dispatchtimer after every one minute interval
I created a dispatcher timer with one minute interval,

```<code>DispatcherTimer dispatcherTimer = new DispatcherTimer();//creation of dispatchtimer

private void btnstart_Click(object sender, RoutedEventArgs e)
{
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Start();
    dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
}
</code>```

When button click the timer start and I created event in it.Every one minute interval it will call the event.

```<code>private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    if (dispatcherTimer.Interval == TimeSpan.FromMinutes(1))
    {
        //...
        //...
    }
}
</code>```

But, My problem is when I click start button it go to event (dispatcherTimer_Tick) after 60 seconds it need to go for that event and after every 1minute interval it will call that event it's working correctly. Initially when I click start button it suddenly call that event but I want after 60seconds (ie after 1 minute) need to call that dispatcherTimer_Tick event.

答:
Your problem is that your code doing:

```<code>//...
dispatcherTimer.Start();
dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
//...
</code>```

instead of:

```<code>//...
dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
dispatcherTimer.Start();
//...
</code>```

Set the dispatcherTimer.Interval before calling Start().

Body:
I created a dispatcher timer with one minute interval,

DispatcherTimer dispatcherTimer = new DispatcherTimer();//creation of dispatchtimer

private void btnstart_Click(object sender, RoutedEventArgs e)
{
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Start();
    dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
}

When button click the timer start and I created event in it.Every one minute interval it will call the event.

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    if (dispatcherTimer.Interval == TimeSpan.FromMinutes(1))
    {
        //...
        //...
    }
}

But, My problem is when I click start button it go to event (dispatcherTimer_Tick) after 60 seconds it need to go for that event and after every 1minute interval it will call that event it's working correctly. Initially when I click start button it suddenly call that event but I want after 60seconds (ie after 1 minute) need to call that dispatcherTimer_Tick event.

Body:
Your problem is that your code doing:

//...
dispatcherTimer.Start();
dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
//...

instead of:

//...
dispatcherTimer.Interval = TimeSpan.FromMinutes(1);
dispatcherTimer.Start();
//...

Set the dispatcherTimer.Interval before calling Start().


问:
Html Anchor doesn't redirect
Here is main site link where each link working fine:
  http://www.hipackages.com/

but when redirect to bellow link, then links on the menubar doesn't responding:
 http://www.hipackages.com/lifestyle/page_detail/1

i try to redirect like this:
 http://www.hipackages.com#body

but this didn't redirect me to the required page.

Thanks to all for any response.

答:
The problem is rather related to a Google Maps integrated object that is breaking the logic perhaps because of an unescaped ampersand after the Google Maps API Key.

Try looking into this resource:

```<code>                     <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDE9vyoAQQIcDWLXCZyjPxDFUoxEvaz1j0&callback=map"></script>
</code>```

1.) Noting that the bold character is merely a replace from: & to &

```<code>                    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDE9vyoAQQIcDWLXCZyjPxDFUoxEvaz1j0**&**callback=map"></script>
</code>```

2.)

A good practice would be to add charset="utf-8" to your scripts especially if they go and touch an API, as it's the encoding declared at the top of your web document. Give it a try to that, as the only error seen in here (web console) is with that script shown as: "TypeError: a is null" so perhaps is expecting a parameter.

Try replacing that line for the following:

```<code>                    <script charset="utf-8" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDE9vyoAQQIcDWLXCZyjPxDFUoxEvaz1j0&callback=map"></script>
</code>```

Title: Html Anchor doesn't redirect

Body:
The problem is rather related to a Google Maps integrated object that is breaking the logic perhaps because of an unescaped ampersand after the Google Maps API Key.

Try looking into this resource:

                     <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDE9vyoAQQIcDWLXCZyjPxDFUoxEvaz1j0&callback=map"></script>

1.) Noting that the bold character is merely a replace from: & to &amp;

                    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDE9vyoAQQIcDWLXCZyjPxDFUoxEvaz1j0**&amp;**callback=map"></script>

2.)

A good practice would be to add charset="utf-8" to your scripts especially if they go and touch an API, as it's the encoding declared at the top of your web document. Give it a try to that, as the only error seen in here (web console) is with that script shown as: "TypeError: a is null" so perhaps is expecting a parameter.

Try replacing that line for the following:

                    <script charset="utf-8" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDE9vyoAQQIcDWLXCZyjPxDFUoxEvaz1j0&amp;callback=map"></script>


问:
How to navigate directories in Hadoop HDFS
I would like to navigate in HDFS

First i looked on the directories in "root" HDFS

```<code>[cloudera@localhost ~]$ sudo -u hdfs hadoop fs -ls hdfs:/
Found 5 items
drwxr-xr-x   - hbase hbase               0 2015-10-10 07:03 hdfs:///hbase
drwxr-xr-x   - solr  solr                0 2014-06-01 16:16 hdfs:///solr
drwxrwxrwx   - hdfs  supergroup          0 2015-10-08 11:45 hdfs:///tmp
drwxr-xr-x   - hdfs  supergroup          0 2015-04-13 08:26 hdfs:///user
drwxr-xr-x   - hdfs  supergroup          0 2014-06-01 16:15 hdfs:///var
</code>```

then i tried entering one of them

```<code>[cloudera@localhost ~]$ sudo -u hdfs hadoop -cd hdfs:///hbase
Error: No command named `-cd' was found. Perhaps you meant `hadoop cd'
</code>```

trying also 'hadoop cd' do not work

```<code>[cloudera@localhost ~]$ sudo -u hdfs hadoop cd hdfs:///hbase
Exception in thread "main" java.lang.NoClassDefFoundError: cd
Caused by: java.lang.ClassNotFoundException: cd
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: cd.  Program will exit.
</code>```

Please don't offer to use -ls -R  (recursive) to show all files .

I want to be able navigate using commands like cd

答:
```<code>hadoop fs –ls /user/scott/
</code>```

To see the list of values in the path, we have to give the full path. Other than that navigation is not possible.

Body:
I would like to navigate in HDFS

First i looked on the directories in "root" HDFS

[cloudera@localhost ~]$ sudo -u hdfs hadoop fs -ls hdfs:/
Found 5 items
drwxr-xr-x   - hbase hbase               0 2015-10-10 07:03 hdfs:///hbase
drwxr-xr-x   - solr  solr                0 2014-06-01 16:16 hdfs:///solr
drwxrwxrwx   - hdfs  supergroup          0 2015-10-08 11:45 hdfs:///tmp
drwxr-xr-x   - hdfs  supergroup          0 2015-04-13 08:26 hdfs:///user
drwxr-xr-x   - hdfs  supergroup          0 2014-06-01 16:15 hdfs:///var

then i tried entering one of them

[cloudera@localhost ~]$ sudo -u hdfs hadoop -cd hdfs:///hbase
Error: No command named `-cd' was found. Perhaps you meant `hadoop cd'

trying also 'hadoop cd' do not work

[cloudera@localhost ~]$ sudo -u hdfs hadoop cd hdfs:///hbase
Exception in thread "main" java.lang.NoClassDefFoundError: cd
Caused by: java.lang.ClassNotFoundException: cd
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: cd.  Program will exit.

Please don't offer to use -ls -R  (recursive) to show all files .

I want to be able navigate using commands like cd

Body:
hadoop fs –ls /user/scott/

To see the list of values in the path, we have to give the full path. Other than that navigation is not possible.