问:
ClassCastException while upgrading to Gradle 4.1
I use the following Gradle distribution:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-bin.zip
</code>```

When using above version of Gradle, It's giving me the ClassCastException when I run below command.

```<code>./gradlew dependencyUpdates --stacktrace

     * What went wrong:
     Execution failed for task ':app:dependencyUpdates'.
     > java.lang.String cannot be cast to org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.Version

     * Try:
     Run with --info or --debug option to get more log output.

     * Exception is:
     org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:dependencyUpdates'.
             at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
             at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
             at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
             at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
             at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
             at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
             at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
            at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
            at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
            at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
            at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
            at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
            at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
            at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
            at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
            at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
            at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
            at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
            at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to
org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.Version
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.StaticVersionComparator.compare(StaticVersionComparator.java:25)
            at java_util_Comparator$compare.call(Unknown Source)
            at com.github.benmanes.gradle.versions.updates.VersionComparator.compare(VersionComparator.groovy:49)
            at com.github.benmanes.gradle.versions.updates.VersionComparator$compare.call(Unknown Source)
            at com.github.benmanes.gradle.versions.updates.Resolver.<init>(Resolver.groovy:53)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdates$_run_closure2.doCall(DependencyUpdates.groovy:57)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdates.run(DependencyUpdates.groovy:56)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdates$run.call(Unknown Source)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask.dependencyUpdates(DependencyUpdatesTask.groovy:54)
            at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
            at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
            at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
            at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
            at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:731)
            at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:705)
            at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
            at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
            at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
            ... 27 more

    * Get more help at https://help.gradle.org
</code>```

答: Upgrade to the latest version of gradle-versions-plugin

Body:
I use the following Gradle distribution:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-bin.zip

When using above version of Gradle, It's giving me the ClassCastException when I run below command.

./gradlew dependencyUpdates --stacktrace

     * What went wrong:
     Execution failed for task ':app:dependencyUpdates'.
     > java.lang.String cannot be cast to org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.Version

     * Try:
     Run with --info or --debug option to get more log output.

     * Exception is:
     org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:dependencyUpdates'.
             at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
             at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
             at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
             at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
             at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
             at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
             at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
            at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
            at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
            at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
            at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
            at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
            at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
            at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
            at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
            at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
            at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
            at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
            at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
            at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to
org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.Version
            at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.StaticVersionComparator.compare(StaticVersionComparator.java:25)
            at java_util_Comparator$compare.call(Unknown Source)
            at com.github.benmanes.gradle.versions.updates.VersionComparator.compare(VersionComparator.groovy:49)
            at com.github.benmanes.gradle.versions.updates.VersionComparator$compare.call(Unknown Source)
            at com.github.benmanes.gradle.versions.updates.Resolver.<init>(Resolver.groovy:53)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdates$_run_closure2.doCall(DependencyUpdates.groovy:57)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdates.run(DependencyUpdates.groovy:56)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdates$run.call(Unknown Source)
            at com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask.dependencyUpdates(DependencyUpdatesTask.groovy:54)
            at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
            at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
            at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
            at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
            at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:731)
            at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:705)
            at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
            at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
            at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
            at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
            ... 27 more

    * Get more help at https://help.gradle.org


来源: stackexchange

问:
Resetting unverified session
There are two servers, production.myapp.com and staging.myapp.com that use cookie session store and that cookie is set for myapp.com domain. Is there a way to handle a session cookie that can't be decrypted/verified? Rails version is 5.1.

答:
Take a look at the Documentaion for Cookies. You can use an encrypted cookie and set the domain on the cookie to be myapp.com, i.e.

```<code>cookies.encrypted[:my-key] = {
  domain: ".myapp.com",
  secure: !Rails.env.development?,
  value: "put-your-value-here",
}
</code>```

Note however, that both apps will need to share the secret_key_base since that is what is used to encrypt / read the cookie value.

If you want to delete it be sure to pass the domain as argument.

```<code>cookies.delete(:my-key, domain: ".my-app.com")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Resetting unverified session

Body:
Take a look at the Documentaion for Cookies. You can use an encrypted cookie and set the domain on the cookie to be myapp.com, i.e.

cookies.encrypted[:my-key] = {
  domain: ".myapp.com",
  secure: !Rails.env.development?,
  value: "put-your-value-here",
}

Note however, that both apps will need to share the secret_key_base since that is what is used to encrypt / read the cookie value.

If you want to delete it be sure to pass the domain as argument.

cookies.delete(:my-key, domain: ".my-app.com")


问:
Headers with Dashes in powershell
Is there a way to get rid of the header name and the dashes? For example, instead of having

```<code>Display Name
-------------
Test, Directory
</code>```

It would just display the First and Last Name Test, Directory

this is what i have in my write-output:

```<code>write-output $DataAdapter.Fill($Dataset) | Out-null
</code>```

I thought the out-null would take care of it but it didn't.

Can someone help me with that please .

Thank you.

答:
PowerShell does not treat data as text; data is objects. Objects have properties, and when you send an object to the output pipe, the default processor will handle the conversion to text.

This conversion attempts to preserve the information about the object to the best of its ability. That means, for example, labelling the values of the properties of the object with the name of the property.

Your object, designated by $DataAdapter.Fill($Dataset), has a property called Display Name. The default output processor Write-Output attempts to preserve the information by labelling the data with the property name, Display Name, and so you see your header.

To eliminate this, you need to output not the entire object, but the value of the specific property you are interested in:

```<code>Write-Output ($DataAdapter.Fill($Dataset)).'Display Name'
</code>```

Note that - where you have control over it - having spaces as part of the property name is generally considered poor practice.

Title: Headers with Dashes in powershell

Body:
Is there a way to get rid of the header name and the dashes? For example, instead of having

Display Name
-------------
Test, Directory

It would just display the First and Last Name Test, Directory

this is what i have in my write-output:

write-output $DataAdapter.Fill($Dataset) | Out-null

I thought the out-null would take care of it but it didn't.

Can someone help me with that please .

Thank you.

Body:
PowerShell does not treat data as text; data is objects. Objects have properties, and when you send an object to the output pipe, the default processor will handle the conversion to text.

This conversion attempts to preserve the information about the object to the best of its ability. That means, for example, labelling the values of the properties of the object with the name of the property.

Your object, designated by $DataAdapter.Fill($Dataset), has a property called Display Name. The default output processor Write-Output attempts to preserve the information by labelling the data with the property name, Display Name, and so you see your header.

To eliminate this, you need to output not the entire object, but the value of the specific property you are interested in:

Write-Output ($DataAdapter.Fill($Dataset)).'Display Name'

Note that - where you have control over it - having spaces as part of the property name is generally considered poor practice.


问:
Observer pattern in c++
I am having a bit of trouble with observer pattern
I have a beverage class that uses decorator fine.
I am trying to implement observer to let an observer( say a cell phone/text message) in this case know when there order is done. i wont include the beverage/decorator classes since they work fine.

In main i was going to do something like this:

```<code>Subject mySubject = new Subject();
Observer myObserver1 = new Observer1();
Observer myObserver2 = new Observer2();

// register observers
mySubject.Register(myObserver1);
mySubject.Register(myObserver2);

mySubject.Notify("message 1");
mySubject.Notify("message 2");
</code>```

I have a subject class, observer, phone behavior class and a cellhone1,cellphone2 classes..

Here is the subject class

```<code>#ifndef _SUBJECT_
#define _SUBJECT_

//#include "Starbuzz.h"
//#include "Starbuzz2.h"
#include "Observer.h"
#include <list>

namespace CoffeeHouse {
namespace Observers {

class Subject  {

private:
std::list< Observer* > observers;

public:
Subject();
~Subject();

void Subject::Register(Observer observer)
{

//if (!observers.(observer))
//{

observers.insert(observer);
}
//}

//void Unregister(Observer observer)
//{
// if observer is in the list, remove
//if (observers.Contains(observer))
//{
//observers.Remove(observer);
//}
//}

void Notify(std::string message)
{
//need loop
Observer observer;
observer.update(message);

}
//}
//}

//void Subject::registerObserver( Observer* o ) { assert( o );
    //_observers.push_front(o);
//}
//void Subject::removeObserver( Observer* o ) { assert( o );
//  _observers.remove(o);
//}
//void Subject::notifyObservers() const {
    //for( std::list< Observer* >::iterator iterator = _observers.begin();   _observers.end() != iterator; ++iterator ) {
        //Observer* observer = *iterator;
        //observer->update(message);
    //}
//}
};
} // namespace Observer
}

#endif
</code>```

Here is the observer class

```<code>#ifndef _OBSERVER_
#define _OBSERVER_

#include <string>

namespace CoffeeHouse {
namespace Observers {

class Subject;

class Observer {

//public: virtual ~Observer() = 0;

public: virtual void Update(std::string message) = 0;
};
</code>```

here is the phone behavior class

```<code>#ifndef _PHONEBEHAVIOR_
#define _PHONEBEHAVIOR_

namespace CoffeeHouse {
namespace Observer {

class PhoneBehavior {
public: virtual void Update() const = 0;
};
protected: virtual ~PhoneBehavior() = 0 {

};

};

} // namespace Observer
} //
</code>```

here is cellphone 1

```<code>#ifndef _CELLPHONE1_
#define _CELLPHONE1_

namespace CoffeeHouse {
namespace Observer {
include<iostream>
class CellPhone1: public Observer, public PhoneBehavior {
public:
    CellPhone1();
    ~CellPhone1();
virtual void Update(std::string message)
 {
   std::cout << "CellPhone1: " << message;
}
};

} // namespace Observer
} //

#endif
</code>```

here re the errors i am getting..

```<code>error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
1>        due to following members:
1>        'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
see declaration of 'CoffeeHouse::Observers::Observer::update'
error C2661: 'std::list<_Ty>::insert' : no overloaded function takes 1 arguments
with[_Ty=CoffeeHouse::Observers::Observer *

error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
due to following members:
'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
observer.h(15) : see declaration of 'CoffeeHouse::Observers::Observer::update
</code>```

When i click on error "cannot instantiate abstract class" it takes me to:

```<code>void Subject::Register(Observer observer)
</code>```

I understand that Abstract classes are made such that they cannot be instantiated!

How could i do an update then?? any suggestions of a better way?

I appreciate any help!

答: One error is that Subject::Register is currently taking an Observer object, instead of a pointer to an Observer.  This means that you're trying to instantiate an abstract object, which is illegal.</p>

ContentLicense: CC BY-SA 2.5

Title: Observer pattern in c++

Body:
I am having a bit of trouble with observer pattern
I have a beverage class that uses decorator fine.
I am trying to implement observer to let an observer( say a cell phone/text message) in this case know when there order is done. i wont include the beverage/decorator classes since they work fine.

In main i was going to do something like this:

Subject mySubject = new Subject();
Observer myObserver1 = new Observer1();
Observer myObserver2 = new Observer2();

// register observers
mySubject.Register(myObserver1);
mySubject.Register(myObserver2);

mySubject.Notify("message 1");
mySubject.Notify("message 2");

I have a subject class, observer, phone behavior class and a cellhone1,cellphone2 classes..

Here is the subject class

#ifndef _SUBJECT_
#define _SUBJECT_

//#include "Starbuzz.h"
//#include "Starbuzz2.h"
#include "Observer.h"
#include <list>

namespace CoffeeHouse {
namespace Observers {

class Subject  {

private:
std::list< Observer* > observers;

public:
Subject();
~Subject();

void Subject::Register(Observer observer)
{

//if (!observers.(observer))
//{

observers.insert(observer);
}
//}

//void Unregister(Observer observer)
//{
// if observer is in the list, remove
//if (observers.Contains(observer))
//{
//observers.Remove(observer);
//}
//}

void Notify(std::string message)
{
//need loop
Observer observer;
observer.update(message);

}
//}
//}

//void Subject::registerObserver( Observer* o ) { assert( o );
    //_observers.push_front(o);
//}
//void Subject::removeObserver( Observer* o ) { assert( o );
//  _observers.remove(o);
//}
//void Subject::notifyObservers() const {
    //for( std::list< Observer* >::iterator iterator = _observers.begin();   _observers.end() != iterator; ++iterator ) {
        //Observer* observer = *iterator;
        //observer->update(message);
    //}
//}
};
} // namespace Observer
}

#endif

Here is the observer class

#ifndef _OBSERVER_
#define _OBSERVER_

#include <string>

namespace CoffeeHouse {
namespace Observers {

class Subject;

class Observer {

//public: virtual ~Observer() = 0;

public: virtual void Update(std::string message) = 0;
};

here is the phone behavior class

#ifndef _PHONEBEHAVIOR_
#define _PHONEBEHAVIOR_

namespace CoffeeHouse {
namespace Observer {

class PhoneBehavior {
public: virtual void Update() const = 0;
};
protected: virtual ~PhoneBehavior() = 0 {

};

};

} // namespace Observer
} //

here is cellphone 1

#ifndef _CELLPHONE1_
#define _CELLPHONE1_

namespace CoffeeHouse {
namespace Observer {
include<iostream>
class CellPhone1: public Observer, public PhoneBehavior {
public:
    CellPhone1();
    ~CellPhone1();
virtual void Update(std::string message)
 {
   std::cout << "CellPhone1: " << message;
}
};

} // namespace Observer
} //

#endif

here re the errors i am getting..

error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
1>        due to following members:
1>        'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
see declaration of 'CoffeeHouse::Observers::Observer::update'
error C2661: 'std::list<_Ty>::insert' : no overloaded function takes 1 arguments
with[_Ty=CoffeeHouse::Observers::Observer *

error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
due to following members:
'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
observer.h(15) : see declaration of 'CoffeeHouse::Observers::Observer::update

When i click on error "cannot instantiate abstract class" it takes me to:

void Subject::Register(Observer observer)

I understand that Abstract classes are made such that they cannot be instantiated!

How could i do an update then?? any suggestions of a better way?

I appreciate any help!


问:
Custom editor with split core editor
I need to create a custom designer with a split view. The first half of the view would be the code, the second would be a designer/preview for previewing some custom HTML code. Just like XAML designer.

I already have a Window Tool implemented, but now I want it integrated inside the editor so that it would show only for certain file types.

My best guess is that I would need to create a Custom Editor, but I don't know how to get The Visual Studio core editor control to include it? If that's even possible.

答:
If you want something very easy and fast to implement without implementing a  VSPackage, I believe you can do it with a WPF application, where you have a multiline TextBox (editor) and a WebBrowser control (preview)

When text changes into the editor you can check Html syntax (e.g. you can check if you can deserialize). If the syntax is correct you call NavigateToString()

```<code>_webBrowser.NavigateToString(_editor.Text);
</code>```

If you must develop a VSPackage, forget my answer.

Title: Custom editor with split core editor

Body:
If you want something very easy and fast to implement without implementing a  VSPackage, I believe you can do it with a WPF application, where you have a multiline TextBox (editor) and a WebBrowser control (preview)

When text changes into the editor you can check Html syntax (e.g. you can check if you can deserialize). If the syntax is correct you call NavigateToString()

_webBrowser.NavigateToString(_editor.Text);

If you must develop a VSPackage, forget my answer.


问:
How to read content of text file using function
I am new to Python.
Following this example:
https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f

I have a message template file message.txt that uses template string “${PERSON_NAME}” . The string will be replaced with actual name of the person.

So I am using this function but something is not going right, because it gives me weird output"

```<code>from string import Template

def read_template(filename):
    with open(r'C:\Users\MyUserName\Documents\SQL_NeedToKnow\Python\message.txt', 'r', encoding='utf-8') as template_file:
        template_file_content = template_file.read(100)
    return Template(template_file_content)
print(read_template(r'C:\Users\MyUserName\Documents\SQL_NeedToKnow\Python\message.txt'))
</code>```

What am I missing?

答:
You can use readlines() function to read the file.

```<code>def read_from_file():
    with open('file.txt', 'r') as file:
         content = file.readlines()
     print content
</code>```

This will print the entire content of the file.

Also readline() function will read a single line from file whereas readlines() will read the entire content of the file

Body:
I am new to Python.
Following this example:
https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f

I have a message template file message.txt that uses template string “${PERSON_NAME}” . The string will be replaced with actual name of the person.

So I am using this function but something is not going right, because it gives me weird output"

from string import Template

def read_template(filename):
    with open(r'C:\Users\MyUserName\Documents\SQL_NeedToKnow\Python\message.txt', 'r', encoding='utf-8') as template_file:
        template_file_content = template_file.read(100)
    return Template(template_file_content)
print(read_template(r'C:\Users\MyUserName\Documents\SQL_NeedToKnow\Python\message.txt'))

What am I missing?

Body:
You can use readlines() function to read the file.

def read_from_file():
    with open('file.txt', 'r') as file:
         content = file.readlines()
     print content

This will print the entire content of the file.

Also readline() function will read a single line from file whereas readlines() will read the entire content of the file


问:
Find closest value to determined multiplicated value
I have two values. One is static and equals 24

```<code>int A = 24;
</code>```

and I have entries list :

```<code>[0, 21, 45, 76, 98]
</code>```

All of occurences comes in loop and I want to get closest value which divides on A :

```<code>0 - 24
21 - 24
45 - 48
76 - 72
98 - 96
</code>```

How to calculate this?

答:
One approach is to take the remainder and see if you need to add or substract from the given number to get closest number that divides. If remainder is less then half of A then substract remainder from the number otherwise add to it the difference between remainder and A. Also as a quick exit check if number is less then A the closest one is A itself.

```<code>public static int[] closest(int a, int[] b){
        int[] result = new int[ b.length ];

        int halfOfA = a/2;

        for (int i = 0; i < b.length; i++){
            if ( b[i] <= a ){
                result[i] = a;
            }else{
                int rem =  b[i] % a;
                if (rem < halfOfA) result[i] = b[i] - rem;
                else result[i] = b[i] + (a - rem);
            }
        }
        return result;
    }
</code>```

Body:
I have two values. One is static and equals 24

int A = 24;

and I have entries list :

[0, 21, 45, 76, 98]

All of occurences comes in loop and I want to get closest value which divides on A :

0 - 24
21 - 24
45 - 48
76 - 72
98 - 96

How to calculate this?

Body:
One approach is to take the remainder and see if you need to add or substract from the given number to get closest number that divides. If remainder is less then half of A then substract remainder from the number otherwise add to it the difference between remainder and A. Also as a quick exit check if number is less then A the closest one is A itself.

public static int[] closest(int a, int[] b){
        int[] result = new int[ b.length ];

        int halfOfA = a/2;

        for (int i = 0; i < b.length; i++){
            if ( b[i] <= a ){
                result[i] = a;
            }else{
                int rem =  b[i] % a;
                if (rem < halfOfA) result[i] = b[i] - rem;
                else result[i] = b[i] + (a - rem);
            }
        }
        return result;
    }


问:
Read-write concurrency
I have an object A which contains a bunch of fields that need to be synchronized. I want to enforce the following property:

1) More than one thread can read the object's fields at a time.
2) If at least one thread is reading from the object, the object cannot be modified.
3) If the object is being modified, no thread can read from the object.

In other words, I want a lock such that, any number of readers can hold the lock. But, if any writer holds the lock, nothing else can hold the lock.

How do I do that? I'm using C++, but I expect there should be a language-independent way of doing it.

答: The concept you are looking for is a Readers-Writer-Lock. There are C++ implementations out there, most notably one in boost::thread. The idea is that you use a single (logical, often internally implemented using two mutexes) mutex for reading and writing that you can upgrade to require unique locking (when you write) and that multiple readers can lock simultaneously when reading from it.</p>

Title: Read-write concurrency


问:
How to detect which device view you're on using Twitter Bootstrap API?
I have just started to play around with Twitter Bootstrap API for a project I have coming up. The main nav contains 3 main elements:

site nav

social links nav

search the site form

I am using the collapse plugin to collapse the site nav and search form when viewing the site on mobile devices. The mobile view has 2 buttons which when clicked toggle the search form or main nav on/off.

However if I toggle off the search form and then resize my browser to desktop view the search form is still hidden in this view?

I have read about using classes such as visible-mobile etc but these seem to clash with the collapse plugin. I also realise I could probably write my own CSS hacks to fix this but thought I'd ask if there was an easier solution.

Bootstrap has events for show, shown, hide and hidden so I thought maybe I could write some custom JS which would show or hide these items in each particular device view. However I didn't know how to detect which device I'm using at the time.

Thoughts?

答: Niche case, but you can apply @Kar.ma's to a Mediawiki with Chameleon (bootstrap skin) installed. Pass the "results" of the DIV as a template argument, then test against that within the template.</p>

ContentLicense: CC BY-SA 4.0


问:
Android: Observing SMS for Deleted Threads
I've currently written an app that is observing the content://sms URI for any changes to the database. My observer is successfully being triggered when individual messages are added or removed, however, no notification is triggered when an entire thread is deleted at once. Is there any way to get this event to trigger? Or maybe there's another content provider I should be observing?

```<code>Uri URI = Uri.parse("content://sms");
String[] columns = {"_id", "date"};
Cursor c = getContentResolver().query(URI, columns, "type=?", new String[]{"1"}, "_id DESC");

Observer observer = new Observer();
c.registerContentObserver(observer);
</code>```

And my observer class:

```<code>private class Observer extends ContentObserver {

    public Observer() {
        super(null);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

        if (!selfChange) {
            // do stuff
            // never called when a thread is deleted
        }
    }
}
</code>```

答: I switched to observing the content://mms-sms/conversations content provider. This provider properly signals my observer when a thread is deleted.</p>

Body:
I've currently written an app that is observing the content://sms URI for any changes to the database. My observer is successfully being triggered when individual messages are added or removed, however, no notification is triggered when an entire thread is deleted at once. Is there any way to get this event to trigger? Or maybe there's another content provider I should be observing?

Uri URI = Uri.parse("content://sms");
String[] columns = {"_id", "date"};
Cursor c = getContentResolver().query(URI, columns, "type=?", new String[]{"1"}, "_id DESC");

Observer observer = new Observer();
c.registerContentObserver(observer);

And my observer class:

private class Observer extends ContentObserver {

    public Observer() {
        super(null);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

        if (!selfChange) {
            // do stuff
            // never called when a thread is deleted
        }
    }
}


问:
How to reindex sales_flat_order_grid in Magento 1.9
There was an error when processing the order on our production environment and records were not inserted for sales_flat_order_grid table, is there any command or function from Magento that can be run to fix the missing record? Thanks</p>

答:
Eventually i had to write a shell script to fix this. I'm sharing this small script that will reindex the table in case anyone has the same problem and need to have the right data in the grid again</p>

```<code>    try {
        Mage::getModel('sales/order')->getResource()->updateGridRecords(
            Mage::getResourceModel('sales/order_collection')->getAllIds()
        );
    } catch (Exception $e) {
        echo $e->getMessage() . "\n";
    }
</code>```

Body:
Eventually i had to write a shell script to fix this. I'm sharing this small script that will reindex the table in case anyone has the same problem and need to have the right data in the grid again

    try {
        Mage::getModel('sales/order')->getResource()->updateGridRecords(
            Mage::getResourceModel('sales/order_collection')->getAllIds()
        );
    } catch (Exception $e) {
        echo $e->getMessage() . "\n";
    }


问:
How to use RewriteRule in htaccess using XAMPP
How do I get rid of the folder name using .htaccess and XAMPP.

I saved the folder in --> xampp/htdocs/myproject

In myproject folder there are an index.php and .htaccess files.

```<code>RewriteEngine On
RewriteBase /myproject/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</code>```

index.php

```<code><h1>index</h1>

<?php

    var_dump($_SERVER["REQUEST_URI"]);
</code>```

This redirects me to the index file but when i var_dump requested uri i'm getting also myfoler name.

example:

```<code>http://localhost/myproject/contact
</code>```

i'm getting -->/myproject/contact

Is this possible to get rid of this foldername/path using .htaccess ?
In this case the /myproject/.

答:
```<code>RewriteRule ^myproject/(.*)$  $1
</code>```

This will take any url of the pattern "myproject/whatever" and rewrite it as "whatever". The string (.*) tells .htaccess to take everything after "myproject/" and store it in a backreference, which is referred to in the rewrite portion of the rule as $1. Hope this helps.

Body:
How do I get rid of the folder name using .htaccess and XAMPP.

I saved the folder in --> xampp/htdocs/myproject

In myproject folder there are an index.php and .htaccess files.

RewriteEngine On
RewriteBase /myproject/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

index.php

index

<?php

    var_dump($_SERVER["REQUEST_URI"]);

This redirects me to the index file but when i var_dump requested uri i'm getting also myfoler name.

example:

http://localhost/myproject/contact

i'm getting -->/myproject/contact

Is this possible to get rid of this foldername/path using .htaccess ?
In this case the /myproject/.

Body:
RewriteRule ^myproject/(.*)$  $1

This will take any url of the pattern "myproject/whatever" and rewrite it as "whatever". The string (.*) tells .htaccess to take everything after "myproject/" and store it in a backreference, which is referred to in the rewrite portion of the rule as $1. Hope this helps.


问:
Getting the first int value of a tuple but the first value is a string (Error) Python
I am trying to get the first int value from all of the tuples in my dictionary keys. The problem is I keep getting the error: "ValueError: invalid literal for int() with base 10: 'Population'" The code I am using is

print([int(item[0]) for item in self.countryCat.values()])

Is there any way I can skip over the first value in my tuple which is "Population" so I will not get this error anymore? I have been stuck on this forever.

Thanks!

答:
You can make a generator that filters out the values that can't be cast to ints

```<code>def error_map(f, iterable):
    for item in iterable:
        try:
            yield f(item)
        except ValueError:
            continue
</code>```

Then we can

```<code>print(list(error_map(lambda x: int(x[0]), self.countryCat.values())))
</code>```

Body:
You can make a generator that filters out the values that can't be cast to ints

def error_map(f, iterable):
    for item in iterable:
        try:
            yield f(item)
        except ValueError:
            continue

Then we can

print(list(error_map(lambda x: int(x[0]), self.countryCat.values())))


问:
Azure API Management - require approval of new developer signup
As we all know, the Azure API Management provides a developer portal.  You can change the way that users login to the portal with AAD, Facebook, ...  I understand how to configure those options.

I don't want new developers to have automatic access to the portal.  I want to review the signup and approve them before they get access.  How do I implement this approval process for new users?

答: User registration can be delegated to a third-party system: https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-setup-delegation</p>


问:
BadRequestHttpException POST REST Resource
I am attempting to create a custom REST resource. My module is as follows:

/example.info.yml

```<code>name: Example
description: ''
type: module
core: 8.x
version: DEV
dependencies:
 - serialization
 - basic_auth
 - rest
</code>```

/src/Plugin/rest/resource/BasicGetResource.php

```<code>namespace Drupal\Example\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides an Example Resource
 *
 * @RestResource(
 *   id = "example_resource",
 *   label = @Translation("Example Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/basic",
 *     "https://www.drupal.org/link-relations/create" = "/api/basic"
 *   }
 * )
 */

class ExampleResource extends ResourceBase {
    /**
    * Responds to GET requests.
    * @return \Drupal\rest\ResourceResponse
    */
    public function get() {
        $response = ['data' => 'Basic Authentication'];
        return new ResourceResponse($response);
    }

    /**
    * Responds to POST requests.
    * @return \Drupal\rest\ResourceResponse
    */
    public function post($data) {
        $response = ['data' => $data];
        return new ResourceResponse($response);
    }
}
</code>```

/config/install/rest.resource.example_resource.yml

```<code>langcode: en
status: true
dependencies:
  module:
    - basic_auth
    - example
    - serialization
_core:
  default_config_hash: NSa-WWwv2X-ogB4ojX2-m6rCsWMY6tzOZFZySnI5yfM
id: example_resource
plugin_id: example_resource
granularity: resource
configuration:
  methods:
    - GET
    - POST
  formats:
    - json
  authentication:
    - basic_auth
</code>```

Attaching the following Javascript to a Block for POST:

```<code>var token;
var credentials = btoa("[USERNAME]:[PASSWORD]");

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "/rest/session/token",
    "method": "GET",
    "headers": {"Content-Type": "application/x-www-form-urlencoded"},
};

$.ajax(settings).done(function (response) {
    token = response;
});

$('#btn-basic-post').click(function() {
    var form = new FormData();
    form.append("message", "Hello World!");

    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "/api/basic?_format=json",
        "method": "POST",
        "headers": {
                "x-csrf-token": token,
            "authorization": "Basic " + credentials,
            "cache-control": "no-cache",
            "Content-Type": "application/json",
            "Accept": 'application/json',
          },
          "processData": false,
          "contentType": false,
          "mimeType": "multipart/form-data",
          "data": form
        }

        $.ajax(settings).done(function (response) {
          alert(response.data);
        });

    });
</code>```

I receive status 400, with response {"message":"Syntax error"}. The following log is records:

```<code>Symfony\Component\HttpKernel\Exception\BadRequestHttpException: Syntax error in Drupal\rest\RequestHandler->handle() (line 101 of C:\Users\bamberj\Sites\devdesktop\drupal-rest\core\modules\rest\src\RequestHandler.php).
</code>```

Any advice would be much appreciated. Thanks.

https://www.drupal.org/project/drupal/issues/2928340

答:
Data was not encoded correctly ...

```<code>var data = JSON.stringify({
    message: 'Hello World',
});

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "/api/basic?_format=json",
  "method": "POST",
  "headers": {
    "x-csrf-token": token,
    "authorization": "Basic YWRtaW46YWRtaW4=",
    "cache-control": "no-cache",
    "Content-Type": "application/json",
    "Accept": 'application/json',
  },
  "data": data,
  "dataType": "JSON",
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
</code>```

Thanks cilefen. See https://www.drupal.org/project/drupal/issues/2928340#comment-12371675.

Body:
I am attempting to create a custom REST resource. My module is as follows:

/example.info.yml

name: Example
description: ''
type: module
core: 8.x
version: DEV
dependencies:
 - serialization
 - basic_auth
 - rest

/src/Plugin/rest/resource/BasicGetResource.php

namespace Drupal\Example\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides an Example Resource
 *
 * @RestResource(
 *   id = "example_resource",
 *   label = @Translation("Example Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/basic",
 *     "https://www.drupal.org/link-relations/create" = "/api/basic"
 *   }
 * )
 */

class ExampleResource extends ResourceBase {
    /**
    * Responds to GET requests.
    * @return \Drupal\rest\ResourceResponse
    */
    public function get() {
        $response = ['data' => 'Basic Authentication'];
        return new ResourceResponse($response);
    }

    /**
    * Responds to POST requests.
    * @return \Drupal\rest\ResourceResponse
    */
    public function post($data) {
        $response = ['data' => $data];
        return new ResourceResponse($response);
    }
}

/config/install/rest.resource.example_resource.yml

langcode: en
status: true
dependencies:
  module:
    - basic_auth
    - example
    - serialization
_core:
  default_config_hash: NSa-WWwv2X-ogB4ojX2-m6rCsWMY6tzOZFZySnI5yfM
id: example_resource
plugin_id: example_resource
granularity: resource
configuration:
  methods:
    - GET
    - POST
  formats:
    - json
  authentication:
    - basic_auth

Attaching the following Javascript to a Block for POST:

var token;
var credentials = btoa("[USERNAME]:[PASSWORD]");

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "/rest/session/token",
    "method": "GET",
    "headers": {"Content-Type": "application/x-www-form-urlencoded"},
};

$.ajax(settings).done(function (response) {
    token = response;
});

$('#btn-basic-post').click(function() {
    var form = new FormData();
    form.append("message", "Hello World!");

    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "/api/basic?_format=json",
        "method": "POST",
        "headers": {
                "x-csrf-token": token,
            "authorization": "Basic " + credentials,
            "cache-control": "no-cache",
            "Content-Type": "application/json",
            "Accept": 'application/json',
          },
          "processData": false,
          "contentType": false,
          "mimeType": "multipart/form-data",
          "data": form
        }

        $.ajax(settings).done(function (response) {
          alert(response.data);
        });

    });

I receive status 400, with response {"message":"Syntax error"}. The following log is records:

Symfony\Component\HttpKernel\Exception\BadRequestHttpException: Syntax error in Drupal\rest\RequestHandler->handle() (line 101 of C:\Users\bamberj\Sites\devdesktop\drupal-rest\core\modules\rest\src\RequestHandler.php).

Any advice would be much appreciated. Thanks.

https://www.drupal.org/project/drupal/issues/2928340

Body:
Data was not encoded correctly ...

var data = JSON.stringify({
    message: 'Hello World',
});

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "/api/basic?_format=json",
  "method": "POST",
  "headers": {
    "x-csrf-token": token,
    "authorization": "Basic YWRtaW46YWRtaW4=",
    "cache-control": "no-cache",
    "Content-Type": "application/json",
    "Accept": 'application/json',
  },
  "data": data,
  "dataType": "JSON",
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

Thanks cilefen. See https://www.drupal.org/project/drupal/issues/2928340#comment-12371675.


问:
Microsoft Access 2013 VBA code changes bound control on change of record am getting write conflict
Have just got back into coding in Microsoft Access, so it might be something stupid.

Situation:
Sqlite database linked to Access db via ODBC.
Have created a form which has bound controls from a table.

Due to the way sqlite stores dates, as text, I am not able to use the calendar picker. I thought easy I can create an unbound text box control, set the format to date and then I will have a date picker. Then in VBA just get it to change the value of the bound date control, which would be hidden.

```<code>Me.txt_Date_of_birth.Value = Format(Me.Txtdate_of_birth_with_calandar_control.Text, global_date_format)
</code>```

It works it changes the value of the bound control (which for testing is not hidden).
But when I change records I am getting an error of

Write conflict. This record has been changed by another user since you
  started editing it. If you save the record, you will overwrite the
  changes the other user made.

From my testing it is being caused by this unbound control updating the bound control. Anyone know a simple fix?
And I would prefer not to get my data from a query that formats the text field into a date field.

And I can confirm that the error does not occur when I create an access table and try to update a bound control.

答:
Does this table have a primary key? - in the eyes of Access - by which I mean when you look at the table in design view with Access.....

If not try adding that.

Body:
Have just got back into coding in Microsoft Access, so it might be something stupid.

Situation:
Sqlite database linked to Access db via ODBC.
Have created a form which has bound controls from a table.

Due to the way sqlite stores dates, as text, I am not able to use the calendar picker. I thought easy I can create an unbound text box control, set the format to date and then I will have a date picker. Then in VBA just get it to change the value of the bound date control, which would be hidden.

Me.txt_Date_of_birth.Value = Format(Me.Txtdate_of_birth_with_calandar_control.Text, global_date_format)

It works it changes the value of the bound control (which for testing is not hidden).
But when I change records I am getting an error of

Write conflict. This record has been changed by another user since you
  started editing it. If you save the record, you will overwrite the
  changes the other user made.

From my testing it is being caused by this unbound control updating the bound control. Anyone know a simple fix?
And I would prefer not to get my data from a query that formats the text field into a date field.

And I can confirm that the error does not occur when I create an access table and try to update a bound control.


问:
System.Windows.Forms.Timer performance
We have an application containing a lot of user controls that update frequently based on a System.Windows.Forms.Timer. Am I safe to add a Timer instance to each control peformancewise? Or should I have one Singleton Timer that runs all the time that is to be used by all instances? What is acutally happening under the hood? Will there be a an additional thread (for counting) for each timer?</p>

答:
There is no additional thread. There are just a lot of WM_TIMER messages coming in your thread's message queue. So these timers won't execute their code in parallel, even if their timespans overlap.

I think that it wouldn't hurt to have a separate timer for evey control. At least it definately won't have any measureable performance difference over using a single timer. The code will get more readable though. ;)

Btw - with todays massive move to multiple CPU cores, consider if this perhaps isn't a place where you can benefit from it.

OwnerDisplayName: bitbonk

Title: System.Windows.Forms.Timer performance

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Vilx-


问:
Using new Unity VideoPlayer and VideoClip API to play video
MovieTexture is finally deprecated after Unity 5.6.0b1 release and new API that plays video on both Desktop and Mobile devices is now released.

VideoPlayer and VideoClip can be used to play video and retrieve  texture for each frame if needed.

I've managed to get the video working but coduldn't get the audio to play as-well from the Editor on Windows 10. Anyone know why audio is not playing?

```<code>//Raw Image to Show Video Images [Assign from the Editor]
public RawImage image;
//Video To Play [Assign from the Editor]
public VideoClip videoToPlay;

private VideoPlayer videoPlayer;
private VideoSource videoSource;

//Audio
private AudioSource audioSource;

// Use this for initialization
void Start()
{
    Application.runInBackground = true;
    StartCoroutine(playVideo());
}

IEnumerator playVideo()
{
    //Add VideoPlayer to the GameObject
    videoPlayer = gameObject.AddComponent<VideoPlayer>();

    //Add AudioSource
    audioSource = gameObject.AddComponent<AudioSource>();

    //Disable Play on Awake for both Video and Audio
    videoPlayer.playOnAwake = false;
    audioSource.playOnAwake = false;

    //We want to play from video clip not from url
    videoPlayer.source = VideoSource.VideoClip;

    //Set video To Play then prepare Audio to prevent Buffering
    videoPlayer.clip = videoToPlay;
    videoPlayer.Prepare();

    //Wait until video is prepared
    while (!videoPlayer.isPrepared)
    {
        Debug.Log("Preparing Video");
        yield return null;
    }

    Debug.Log("Done Preparing Video");

    //Set Audio Output to AudioSource
    videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;

    //Assign the Audio from Video to AudioSource to be played
    videoPlayer.EnableAudioTrack(0, true);
    videoPlayer.SetTargetAudioSource(0, audioSource);

    //Assign the Texture from Video to RawImage to be displayed
    image.texture = videoPlayer.texture;

    //Play Video
    videoPlayer.Play();

    //Play Sound
    audioSource.Play();

    Debug.Log("Playing Video");
    while (videoPlayer.isPlaying)
    {
        Debug.LogWarning("Video Time: " + Mathf.FloorToInt((float)videoPlayer.time));
        yield return null;
    }

    Debug.Log("Done Playing Video");
}
</code>```

答:
By now the VideoPlayer should be updated enough you don't need to write code to get to work correctly. Here are the settings I found to have the most desirable effect:

These settings are:

Video Player:

Play On Awake: True

Wait For First Frame: False

Audio Output Mode: None

Audio Source:

Play On Awake: True

Don't forget to have a VideoClip for the VideoPlayer and an AudioClip for the AudioSource. The file formats I found to work the best are .ogv for video and .wav for audio.

Body:
MovieTexture is finally deprecated after Unity 5.6.0b1 release and new API that plays video on both Desktop and Mobile devices is now released.

VideoPlayer and VideoClip can be used to play video and retrieve  texture for each frame if needed.

I've managed to get the video working but coduldn't get the audio to play as-well from the Editor on Windows 10. Anyone know why audio is not playing?

//Raw Image to Show Video Images [Assign from the Editor]
public RawImage image;
//Video To Play [Assign from the Editor]
public VideoClip videoToPlay;

private VideoPlayer videoPlayer;
private VideoSource videoSource;

//Audio
private AudioSource audioSource;

// Use this for initialization
void Start()
{
    Application.runInBackground = true;
    StartCoroutine(playVideo());
}

IEnumerator playVideo()
{
    //Add VideoPlayer to the GameObject
    videoPlayer = gameObject.AddComponent<VideoPlayer>();

    //Add AudioSource
    audioSource = gameObject.AddComponent<AudioSource>();

    //Disable Play on Awake for both Video and Audio
    videoPlayer.playOnAwake = false;
    audioSource.playOnAwake = false;

    //We want to play from video clip not from url
    videoPlayer.source = VideoSource.VideoClip;

    //Set video To Play then prepare Audio to prevent Buffering
    videoPlayer.clip = videoToPlay;
    videoPlayer.Prepare();

    //Wait until video is prepared
    while (!videoPlayer.isPrepared)
    {
        Debug.Log("Preparing Video");
        yield return null;
    }

    Debug.Log("Done Preparing Video");

    //Set Audio Output to AudioSource
    videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;

    //Assign the Audio from Video to AudioSource to be played
    videoPlayer.EnableAudioTrack(0, true);
    videoPlayer.SetTargetAudioSource(0, audioSource);

    //Assign the Texture from Video to RawImage to be displayed
    image.texture = videoPlayer.texture;

    //Play Video
    videoPlayer.Play();

    //Play Sound
    audioSource.Play();

    Debug.Log("Playing Video");
    while (videoPlayer.isPlaying)
    {
        Debug.LogWarning("Video Time: " + Mathf.FloorToInt((float)videoPlayer.time));
        yield return null;
    }

    Debug.Log("Done Playing Video");
}


问:
JOIN - 2 tasks - sql developer
I have 2 tasks:

1. FIRST TASK

Show  first_name, last_name (from employees), job_title, employee_id (from jobs) start_date, end_date (from job_history)

My idea:

```<code>SELECT s.employee_id
    , first_name
    , last_name
    , job_title
    , employee_id
    , start_date
    , end_date
FROM employees
INNER JOIN jobs hp
    on s.employee_id = hp.employee_id
INNER JOIN job_history
    on hp.jobs = h.jobs
</code>```

I know it doesn't work. I'm receiving: "HP"."EMPLOYEE_ID": invalid identifier

What does it mean "on s.employee_id = hp.employee_id". Maybe I should write sthg else instead of this.

2. SECOND TASK

Show department_name (from departments), average and max salary for each department (those data are from employees) and how many employees are working in those departments (from employees). Choose only departments with more than 1 person. The result round to 2 decimal places.

I have the pieces, but i don't know to connect it
My idea:

```<code>SELECT department_name,average(salary),max(salary),count(employees_id)
FROM employees
INNER JOIN departments
on employees_id = departments_id
HAVING count(department) > 1

SELECT ROUND(average(salary),2) from employees
</code>```

答:
I modified your queries a bit by improving table aliasing. Hopefully, if the right columns are present in the tables as you say, it should work:

```<code>SELECT s.employee_id, s.first_name, s.last_name,
hp.job_title, hp.employee_id,
h.start_date, h.end_date
FROM employees s
INNER JOIN jobs hp
on s.employee_id = hp.employee_id
INNER JOIN job_history h
on hp.jobs = h.jobs;
</code>```

When we say on s.employee_id = hp.employee_id it means that if, for example, there is an employee_id = 1234 present in both the tables employees and jobs, then SQL will bring all the columns from both the tables in the same line that corresponds to employee_id = 1234. You can now pick different columns in the SELECT clause as if they are in the same/single table(which was not the case before joining). This is the main logic behind SQL joins.

As to your 2nd task, try the below query. I made some modifications in aggregation by introducing COUNT(DISTINCT s.employees_id). If the same employees_id is present twice for some reason, you still want to count that as one person.

```<code>SELECT d.department_name, avg(s.salary), max(s.salary), count(distinct s.employees_id)
FROM employees s
INNER JOIN departments d
on e.employees_id = d.departments_id
GROUP BY d.department_name
HAVING COUNT(DISTINCT s.employees_id) > 1;
</code>```

Let me know if there is still any issue. Hopefully, this works.

Title: JOIN - 2 tasks - sql developer

Body:
I have 2 tasks:

1. FIRST TASK

Show  first_name, last_name (from employees), job_title, employee_id (from jobs) start_date, end_date (from job_history)

My idea:

SELECT s.employee_id
    , first_name
    , last_name
    , job_title
    , employee_id
    , start_date
    , end_date
FROM employees
INNER JOIN jobs hp
    on s.employee_id = hp.employee_id
INNER JOIN job_history
    on hp.jobs = h.jobs

I know it doesn't work. I'm receiving: "HP"."EMPLOYEE_ID": invalid identifier

What does it mean "on s.employee_id = hp.employee_id". Maybe I should write sthg else instead of this.

2. SECOND TASK

Show department_name (from departments), average and max salary for each department (those data are from employees) and how many employees are working in those departments (from employees). Choose only departments with more than 1 person. The result round to 2 decimal places.

I have the pieces, but i don't know to connect it
My idea:

SELECT department_name,average(salary),max(salary),count(employees_id)
FROM employees
INNER JOIN departments
on employees_id = departments_id
HAVING count(department) > 1

SELECT ROUND(average(salary),2) from employees

Body:
I modified your queries a bit by improving table aliasing. Hopefully, if the right columns are present in the tables as you say, it should work:

SELECT s.employee_id, s.first_name, s.last_name,
hp.job_title, hp.employee_id,
h.start_date, h.end_date
FROM employees s
INNER JOIN jobs hp
on s.employee_id = hp.employee_id
INNER JOIN job_history h
on hp.jobs = h.jobs;

When we say on s.employee_id = hp.employee_id it means that if, for example, there is an employee_id = 1234 present in both the tables employees and jobs, then SQL will bring all the columns from both the tables in the same line that corresponds to employee_id = 1234. You can now pick different columns in the SELECT clause as if they are in the same/single table(which was not the case before joining). This is the main logic behind SQL joins.

As to your 2nd task, try the below query. I made some modifications in aggregation by introducing COUNT(DISTINCT s.employees_id). If the same employees_id is present twice for some reason, you still want to count that as one person.

SELECT d.department_name, avg(s.salary), max(s.salary), count(distinct s.employees_id)
FROM employees s
INNER JOIN departments d
on e.employees_id = d.departments_id
GROUP BY d.department_name
HAVING COUNT(DISTINCT s.employees_id) > 1;

Let me know if there is still any issue. Hopefully, this works.


问:
Angular 4 structure for multi-user webapp
I'm trying to build a webapp with Angular 4 for the front end, where I have 3 types of users. I'm searching on advise as to what the best practices are in achieving this as I'm quite new to this. I'm sharing what I have so far:

```<code>v app
  v shared
    v main
      > app     //this is what u see before login/reg, after that you're redirected to the apropriate view
      > admin-view
         admin-component.html
         admin-component.css
         admin-component.ts
      > patient-view
        > my-profile
          >edit-profile
            //they all have html, css and ts
          >appointments-history
          >procedures-done
        > dentist-search
        > dentist-profile
        > change-password
    > models
    > services
    > util
    app-routing-module.ts
app.module.ts
</code>```

Now I haven't written everything down,such as each html, css and ts file, also the services, models and utils, I think they are pretty straight forward.

My questions are:
 1)  is app-routing module in the correct place, or should it be next to app.module.ts
     2) should I make separate app-routing modules for nested components like in patient view > my profile > edit profile, or is it fine to have them listed as children in the app-routing.module.ts.

What happens if I have repetitive components, such as change password component, also I have a search component that is the same for patient and dentist. Should I place those components in a separate folder and have:

```<code>>main
  >admin-view
  >app
  >dentist-view
  >patient-view
  >shared
</code>```

and just declare them as children in each components routing?
Also if I'm doing something totally wrong, please do tell, as I'm still learning but I want to follow the best conventions and practices.

Thank you in advance!

答:
i suggest you to use Angular-Cli that has a good folder structure. and so may commands for create new app, create module, create component. now many of SPA devlopers use ng-cli for create enterprise spa application.

for example shahred & assets have a single place, and for unitTesting its use e2e framework. and cli has a very good page life cycle.

Good luck

Body:
I'm trying to build a webapp with Angular 4 for the front end, where I have 3 types of users. I'm searching on advise as to what the best practices are in achieving this as I'm quite new to this. I'm sharing what I have so far:

v app
  v shared
    v main
      > app     //this is what u see before login/reg, after that you're redirected to the apropriate view
      > admin-view
         admin-component.html
         admin-component.css
         admin-component.ts
      > patient-view
        > my-profile
          >edit-profile
            //they all have html, css and ts
          >appointments-history
          >procedures-done
        > dentist-search
        > dentist-profile
        > change-password
    > models
    > services
    > util
    app-routing-module.ts
app.module.ts

Now I haven't written everything down,such as each html, css and ts file, also the services, models and utils, I think they are pretty straight forward.

My questions are:
 1)  is app-routing module in the correct place, or should it be next to app.module.ts
     2) should I make separate app-routing modules for nested components like in patient view > my profile > edit profile, or is it fine to have them listed as children in the app-routing.module.ts.

What happens if I have repetitive components, such as change password component, also I have a search component that is the same for patient and dentist. Should I place those components in a separate folder and have:

>main
  >admin-view
  >app
  >dentist-view
  >patient-view
  >shared

and just declare them as children in each components routing?
Also if I'm doing something totally wrong, please do tell, as I'm still learning but I want to follow the best conventions and practices.

Thank you in advance!


问:
How do I mock a class using Rspec and Rails?
I'm using Rails 5 with Rspec 3.  How do I mock a class in my Rspec method?  I have the following class

```<code>require 'rails_helper'

describe CryptoCurrencyService do

  describe ".sell" do

    it "basic_sell" do
      last_buy_price = 3000
      last_transaction = MoneyMakerTransaction.new({
        :transaction_type => "buy",
        :amount_in_usd => "100",
        :btc_price_in_usd => "#{last_buy_price}"
      })
      @client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
      sell_price = 4000
      assert sell_price > last_buy_price * (1 + MoneyMakerThreshhold.find_buy.pct_change)

      allow(@client).to receive(:sell_price).and_return({"base"=>"BTC", "currency"=>"USD", "amount"=>"#{sell_price}"})

      svc = CryptoCurrencyService.new
      svc.sell(last_transaction)
      last_transaction = MoneyMakerTransaction.find_latest_record
      assert last_transaction.transaction_type, "sell"
    end

  end

end
</code>```

Instead of actually instantiating the class "Coinbase::Wallet" in the line

```<code>@client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
</code>```

I'd like to create  mock taht I could then insert into my service class, which I'm testing.  As it stands right now, when I run things, the actual underlying class is getting instantiated, resulting the run time error ...

```<code>  1) CryptoCurrencyService.sell basic_sell
     Failure/Error: payment_method = client.payment_methods()[0]

     Coinbase::Wallet::AuthenticationError:
       invalid api key
</code>```

答:
You could use a Ruby Struct like this:

```<code>Coinbase::Wallet::Client = Struct.new(:api_key, :api_secret)
@client = Coinbase::Wallet::Client.new(ENV['COINBASE_KEY'], ENV['COINBASE_SECRET'])
@client.api_key #=> whatever was in ENV['COINBASE_KEY']
</code>```

Then pass that object in.

If you need behavior on it you can also get that like this:

```<code>Coinbase::Wallet::Client = Struct.new(:api_key, :api_secret) do
  def client_info
    ## logic here
    "info"
  end
end

@client = Coinbase::Wallet::Client.new(ENV['COINBASE_KEY'], ENV['COINBASE_SECRET'])
@client.client_info #=> "info"
</code>```

Body:
I'm using Rails 5 with Rspec 3.  How do I mock a class in my Rspec method?  I have the following class

require 'rails_helper'

describe CryptoCurrencyService do

  describe ".sell" do

    it "basic_sell" do
      last_buy_price = 3000
      last_transaction = MoneyMakerTransaction.new({
        :transaction_type => "buy",
        :amount_in_usd => "100",
        :btc_price_in_usd => "#{last_buy_price}"
      })
      @client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
      sell_price = 4000
      assert sell_price > last_buy_price * (1 + MoneyMakerThreshhold.find_buy.pct_change)

      allow(@client).to receive(:sell_price).and_return({"base"=>"BTC", "currency"=>"USD", "amount"=>"#{sell_price}"})

      svc = CryptoCurrencyService.new
      svc.sell(last_transaction)
      last_transaction = MoneyMakerTransaction.find_latest_record
      assert last_transaction.transaction_type, "sell"
    end

  end

end

Instead of actually instantiating the class "Coinbase::Wallet" in the line

@client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])

I'd like to create  mock taht I could then insert into my service class, which I'm testing.  As it stands right now, when I run things, the actual underlying class is getting instantiated, resulting the run time error ...

  1) CryptoCurrencyService.sell basic_sell
     Failure/Error: payment_method = client.payment_methods()[0]

     Coinbase::Wallet::AuthenticationError:
       invalid api key

Body:
You could use a Ruby Struct like this:

Coinbase::Wallet::Client = Struct.new(:api_key, :api_secret)
@client = Coinbase::Wallet::Client.new(ENV['COINBASE_KEY'], ENV['COINBASE_SECRET'])
@client.api_key #=> whatever was in ENV['COINBASE_KEY']

Then pass that object in.

If you need behavior on it you can also get that like this:

Coinbase::Wallet::Client = Struct.new(:api_key, :api_secret) do
  def client_info
    ## logic here
    "info"
  end
end

@client = Coinbase::Wallet::Client.new(ENV['COINBASE_KEY'], ENV['COINBASE_SECRET'])
@client.client_info #=> "info"


问:
Ant classpath and junit.jar
I have the an build.xml that allows me to run junit tests. Here is the relevant part:

```<code><path id="JUnit 4.libraryclasspath">
    <pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
    <pathelement location="../../../../../eclipse/plugins/org.hamcrest.core_1.1.0.v20090501071000.jar"/>
</path>
<path id="MyProject.classpath">
    <pathelement location="bin"/>
    <path refid="JUnit 4.libraryclasspath"/>
</path>

<target name="run_unit_tests" depends="build">
        <mkdir dir="${junit.output.dir}"/>
        <junit printsummary="yes" haltonfailure="no">
            <classpath refid="MyProject.classpath" />

            <formatter type="xml"/>
            <batchtest todir="${junit.output.dir}">
                    <fileset dir="${src}">
                            <include name="**/*Test*.java"/>
                    </fileset>
            </batchtest>
        </junit>
</target>
</code>```

If I replace the line:

```<code><pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
</code>```

with

```<code><pathelement location="${eclipse.home}/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
</code>```

The change breaks the classpath. I get the following error:

The <classpath> for <junit> must
  include junit.jar if not in Ant's own
  classpath

As far as I understand, the location attribute should hold the same value in both cases. So what can be the reason?

As a side question, this build file will not work on an environment with different junit version (the path will break). Is it possible to add a "general" path to junit.jar?

答:
The JUnit library resides wherever you tell it to reside.  Personally, I would forget entirely about linking against the jar files shipped with Eclipse and instead download the jars directly.

If I have a project, say at path /project then I would try to put the dependency somewhere in that hierarchy, like at /project/test/lib/junit.jar.  If my ant build file is then /project/build.xml then it's as simple as adding ./test/lib/junit.jar to the JUnit classpath.  Trying to reference an arbitrary location on your machine is fragile (remember, Eclipse could be installed anywhere), particularly when using relative paths (since your project contents could also be stored anywhere).

Title: Ant classpath and junit.jar

Body:
I have the an build.xml that allows me to run junit tests. Here is the relevant part:

<path id="JUnit 4.libraryclasspath">
    <pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>
    <pathelement location="../../../../../eclipse/plugins/org.hamcrest.core_1.1.0.v20090501071000.jar"/>
</path>
<path id="MyProject.classpath">
    <pathelement location="bin"/>
    <path refid="JUnit 4.libraryclasspath"/>
</path>

<target name="run_unit_tests" depends="build">
        <mkdir dir="${junit.output.dir}"/>
        <junit printsummary="yes" haltonfailure="no">
            <classpath refid="MyProject.classpath" />

            <formatter type="xml"/>
            <batchtest todir="${junit.output.dir}">
                    <fileset dir="${src}">
                            <include name="**/*Test*.java"/>
                    </fileset>
            </batchtest>
        </junit>
</target>

If I replace the line:

<pathelement location="../../../../../eclipse/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>

with

<pathelement location="${eclipse.home}/plugins/org.junit4_4.5.0.v20090824/junit.jar"/>

The change breaks the classpath. I get the following error:

The <classpath> for <junit> must
  include junit.jar if not in Ant's own
  classpath

As far as I understand, the location attribute should hold the same value in both cases. So what can be the reason?

As a side question, this build file will not work on an environment with different junit version (the path will break). Is it possible to add a "general" path to junit.jar?


问:
android api json Parser
hi i have an app shows the online streamers from Twitch.tv and the data comes from request i send but i cant parse them this is my code

```<code> public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
    for (int i = 0;i<object.length();i++){
        JSONObject streamObjct = object.getJSONObject(i);
        JSONObject chanel = streamObjct.getJSONObject("channel");
        JSONObject url= streamObjct.getJSONObject("preview");
        final Twitch twitch = new Twitch();
        twitch.setName(chanel.getString(CHANEL_NAME));
        twitch.setStatus(chanel.getString(CHANEL_STATUS));
        twitch.setGame(streamObjct.getString(GAME));
        twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
        twitch.setViewrs(streamObjct.getInt(VIEWRS));
        String imageUrl = url.getString("medium");
        ImageRequest request  =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                twitch.setLogo(response);
            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue quew = Volley.newRequestQueue(context);
        quew.add(request);
        chanels.add(twitch);
    }
    return chanels;
}catch (JSONException e){
    e.printStackTrace();
}

return chanels;
}
</code>```

and this my request
https://api.twitch.tv/kraken/search/streams?query=poker&client_id=gxdzx71jhztgyypn4kjemm1htovv1o

at least can anyone tell me should i work with sqlite Database or not?

where i called TwitchParcer

```<code> private void prepareData(String url, final ListView mListView) {

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray stream = response.getJSONArray("streams");
                TwitchApiParser parser = new TwitchApiParser();
                ArrayList items= parser.ParseTwitch(stream);
                TwitchAdapter adapter = new TwitchAdapter(getContext(),
                        R.layout.activity_last_news_fragment,items);
                mListView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
    quew.add(request);
}
</code>```

and this is new Error

```<code>Process: app.mma.introsliderproject, PID: 11542
                                                                        java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                            at app.mma.PokerInfo.twitch.TwitchAdapter.getView(TwitchAdapter.java:39)
</code>```

答:
i solve the problem this is the complete code

```<code>public class TwitchFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.twitch_main, container, false);
    String url="http://192.168.1.101/mySite/Flowers/flowers2.json";
    ListView mListView = (ListView) view.findViewById(R.id.twitch_last);
    prepareData(url,mListView);
    return view;
}
private void prepareData(String url, final ListView mListView) {

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray stream = response.getJSONArray("streams");
                TwitchApiParser parser = new TwitchApiParser();
                ArrayList items= parser.ParseTwitch(stream,getActivity().getApplicationContext());
                TwitchAdapter adapter = new TwitchAdapter(getContext(),
                        R.layout.twitch,items);
                mListView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
    quew.add(request);
}
</code>```

and the parser

```<code>public class TwitchApiParser {
private final String CHANEL_NAME="display_name";
private final String GAME="game";
private final String CHANEL_STATUS = "status";
private final String BROADCASTER_LANGUAGE = "broadcaster_language";
private final String VIEWRS = "viewers";
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
    for (int i = 0;i<object.length();i++){
        JSONObject streamObjct = object.getJSONObject(i);
        JSONObject chanel = streamObjct.getJSONObject("channel");
        JSONObject url= streamObjct.getJSONObject("preview");
        final Twitch twitch = new Twitch();
        twitch.setName(chanel.getString(CHANEL_NAME));
        twitch.setStatus(chanel.getString(CHANEL_STATUS));
        twitch.setGame(streamObjct.getString(GAME));
        twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
        twitch.setViewrs(streamObjct.getInt(VIEWRS));
        String imageUrl = url.getString("medium");
        ImageRequest request  =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                twitch.setLogo(response);
            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue quew = Volley.newRequestQueue(context);
        quew.add(request);
        chanels.add(twitch);
    }
    return chanels;
}catch (JSONException e){
    e.printStackTrace();
}

return chanels;
}
</code>```

Title: android api json Parser

Body:
hi i have an app shows the online streamers from Twitch.tv and the data comes from request i send but i cant parse them this is my code

 public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
    for (int i = 0;i<object.length();i++){
        JSONObject streamObjct = object.getJSONObject(i);
        JSONObject chanel = streamObjct.getJSONObject("channel");
        JSONObject url= streamObjct.getJSONObject("preview");
        final Twitch twitch = new Twitch();
        twitch.setName(chanel.getString(CHANEL_NAME));
        twitch.setStatus(chanel.getString(CHANEL_STATUS));
        twitch.setGame(streamObjct.getString(GAME));
        twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
        twitch.setViewrs(streamObjct.getInt(VIEWRS));
        String imageUrl = url.getString("medium");
        ImageRequest request  =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                twitch.setLogo(response);
            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue quew = Volley.newRequestQueue(context);
        quew.add(request);
        chanels.add(twitch);
    }
    return chanels;
}catch (JSONException e){
    e.printStackTrace();
}

return chanels;
}

and this my request
https://api.twitch.tv/kraken/search/streams?query=poker&client_id=gxdzx71jhztgyypn4kjemm1htovv1o

at least can anyone tell me should i work with sqlite Database or not?

where i called TwitchParcer

 private void prepareData(String url, final ListView mListView) {

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray stream = response.getJSONArray("streams");
                TwitchApiParser parser = new TwitchApiParser();
                ArrayList items= parser.ParseTwitch(stream);
                TwitchAdapter adapter = new TwitchAdapter(getContext(),
                        R.layout.activity_last_news_fragment,items);
                mListView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
    quew.add(request);
}

and this is new Error

Process: app.mma.introsliderproject, PID: 11542
                                                                        java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                            at app.mma.PokerInfo.twitch.TwitchAdapter.getView(TwitchAdapter.java:39)

Body:
i solve the problem this is the complete code

public class TwitchFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.twitch_main, container, false);
    String url="http://192.168.1.101/mySite/Flowers/flowers2.json";
    ListView mListView = (ListView) view.findViewById(R.id.twitch_last);
    prepareData(url,mListView);
    return view;
}
private void prepareData(String url, final ListView mListView) {

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray stream = response.getJSONArray("streams");
                TwitchApiParser parser = new TwitchApiParser();
                ArrayList items= parser.ParseTwitch(stream,getActivity().getApplicationContext());
                TwitchAdapter adapter = new TwitchAdapter(getContext(),
                        R.layout.twitch,items);
                mListView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
    quew.add(request);
}

and the parser

public class TwitchApiParser {
private final String CHANEL_NAME="display_name";
private final String GAME="game";
private final String CHANEL_STATUS = "status";
private final String BROADCASTER_LANGUAGE = "broadcaster_language";
private final String VIEWRS = "viewers";
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
    for (int i = 0;i<object.length();i++){
        JSONObject streamObjct = object.getJSONObject(i);
        JSONObject chanel = streamObjct.getJSONObject("channel");
        JSONObject url= streamObjct.getJSONObject("preview");
        final Twitch twitch = new Twitch();
        twitch.setName(chanel.getString(CHANEL_NAME));
        twitch.setStatus(chanel.getString(CHANEL_STATUS));
        twitch.setGame(streamObjct.getString(GAME));
        twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
        twitch.setViewrs(streamObjct.getInt(VIEWRS));
        String imageUrl = url.getString("medium");
        ImageRequest request  =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                twitch.setLogo(response);
            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue quew = Volley.newRequestQueue(context);
        quew.add(request);
        chanels.add(twitch);
    }
    return chanels;
}catch (JSONException e){
    e.printStackTrace();
}

return chanels;
}


问:
How to summarize column price from 2 tables with no relationship?
In a mysql databse, I have tblA.price and tblB.price. There is no relationship between them.

I want summarize all sales from tableA and tableB. It will be something like that sum(tblA.price)+sum(tblB.price) AS total.

how could I perform that query?

答:
Quick and Dirty. Unions aren't great. But if you have a fixed number of tables, this will work. Performance might get tricky, and it's definitely not pretty, but answers your question.</p>

```<code>select sum(price) as totalprice from
(select sum(a.price) as price
from a
union all
select sum(b.price) as price
from b) as ab
</code>```

Body:
Quick and Dirty. Unions aren't great. But if you have a fixed number of tables, this will work. Performance might get tricky, and it's definitely not pretty, but answers your question.

select sum(price) as totalprice from
(select sum(a.price) as price
from a
union all
select sum(b.price) as price
from b) as ab


问:
SQL - how to query to find if two columes are 1to1 1tomany manytomany relationship?
I want to draw a class diagram to describe the relationship between columes. how to query to find if two columes are 1to1 or 1tomany or manytomany relationship? for example, below table shows that column "name" is 1-to-many with colume "prod".

答:
Any record returned would mean a 1 to many</p>

```<code>select A
from table
group by A,B
having count(*) >1
</code>```

Body:
Any record returned would mean a 1 to many

select A
from table
group by A,B
having count(*) >1