i have a weird problem...
i try to build a button that onClick doing something(i dont use in regular event because i need to transfer a data with the event).
i built a UIButon class and create an instance of him in the parent class.
i create a custom Event class:
package ;
import openfl.events.Event;
/**
* ...
* #author Michael
*/
class ChangeWinEvent extends Event
{
public static inline var CHANGE_WINDOW:String = "changeWindow";
public var _winToClose:String;
public function new(name:String, winToClose:String, bubbles:Bool=false, cancelable:Bool=false)
{
super(type, bubbles, cancelable);
_winToClose = winToClose;
}
}
and i dispatch CHANGE_WINDOW event like this:
dispatchEvent(new ChangeWinEvent(ChangeWinEvent.CHANGE_WINDOW,"LoginWin"));
and listen to this event in parent class:
_loginBtn.addEventListener(ChangeWinEvent.CHANGE_WINDOW, handleChangeWindows);
thank you helpers!
michael
You also have to override the clone method. Take a look at this custom event class i'm currently using:
/**
* Custom button event used for communication
* between button classes and their respective
* views.
* #author Tiago Ling Alexandre
*/
class ButtonEvent extends Event
{
public static var ACTIVATE:String = "Activate";
public var data:Dynamic;
public function new(type:String, data:Dynamic, bubbles:Bool = false, cancelable:Bool = false)
{
super(type, bubbles, cancelable);
this.data = data;
}
override public function clone():Event
{
return new ButtonEvent(type, bubbles, cancelable);
}
}
The only difference from your class is the clone() method. That's the missing piece.
Regards,
super(type, bubbles, cancelable);
...apparently takes type variable from type instance field (as you have constructor parameter named name, not type), so it is null and you haven't registered any listener for null event type.
Related
I am trying to use Laravel Jobs, and that worked for few times but now I am getting this error.
Class Illuminate\Bus\Dispatcher contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods
"message": "Class Illuminate\Bus\Dispatcher contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Contracts\Bus\QueueingDispatcher::findBatch, Illuminate\Contracts\Bus\QueueingDispatcher::batch, Illuminate\Contracts\Bus\Dispatcher::dispatchSync)",
"exception": "Symfony\Component\ErrorHandler\Error\FatalError",
"file": "D:\xampp8\htdocs\sa-new\laravel-develop\vendor\laravel\framework\src\Illuminate\Bus\Dispatcher.php",
"line": 13,
My controller code looks like this
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use App\Model\BccMapping;
use App\Jobs\ProcessUnmappedRequests;
public function processUnmappedRequests(Request $request){
ProcessUnmappedRequests::dispatch('3',$request);
}
While my Job's code looks like this.
<?php
namespace App\Jobs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Model\BccMapping;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessUnmappedRequests implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $request;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($id, $request)
{
$this->siteId = $request->get('siteId');
$this->mappingId = $request->get('mappingId');
$this->email = $request->get('originEmail');
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$unmappedRequests = DB::table('bcc')->where("EmailFrom", trim($this->email))->whereNull('BccMappingId')
->where('Archive',0)->get();
if($unmappedRequests->isNotEmpty()){
$mapping = BccMapping::where('id',$this->mappingId )->first();
if(!$mapping)
return false;
$mappingData = json_decode($mapping->mapping);
$keyword = $mapping->keyword;
foreach ($unmappedRequests as $key=>$bcc){
$bccKeyword = app('App\Http\Controllers\BccToolController')->getDomNodeValue($mappingData->keywordPath->path,$bcc->HTML);
var_dump($bccKeyword);die;
}
}else{
return false;
}
}
}
Currently I am using Laravel 7.0 and PHP 7.4.
I'm currently trying to implement a base class which has multiple properties. All but one property are being injected via the constructor using InversifyJS's #Inject tag. I'm also getting an instance via the container.Get() function in the constructor. When I run my application everything is fine, but when the application recieves a request, the app crashes without an error.
Base class
/**
* Base class for all intent logic
*/
#injectable()
export default abstract class IntentBase implements IIntent {
protected logger: ILogger;
protected responseService: IResponseService;
protected contextService: IContextService;
protected fallbackIntent: IIntent;
protected responseBuilder: IResponseBuilder;
/**
* Constructor
* #param logger logger
* #param responseService response service
* #param contextService context service
*/
constructor(
#inject(TYPES.WinstonLogger) logger: ILogger,
#inject(TYPES.ResponseService) responseService: IResponseService,
#inject(TYPES.ContextService) contextService: IContextService,
#inject(TYPES.ResponseBuilder) responseBuilder: IResponseBuilder,
) {
this.logger = logger;
this.responseService = responseService;
this.contextService = contextService;
this.responseBuilder = responseBuilder;
this.fallbackIntent = container.get(TYPES.DefaultFallbackIntent); // <-- container.Get() line
}
/**
* Override the standard fallback logic for an intent.
* #param fallback fallback to set
*/
setFallback(fallback: IIntent): void {
this.fallbackIntent = fallback;
}
When I uncomment the container.get(TYPES.DefaultFallbackIntent) line, my application can recieve requests like normally and it doesn't crash. The reason why I am trying this injection setup is because I'd like to set a default behavior for each child class in the constructor.
Does anyone have an explaination to why I cannot seem to inject this class?
Thanks in advance
Update
inversify.config.ts
import DefaultFallbackIntent from "./src/bot/intents/fallbacks/defaultFallbackIntent";
import TextResponseRepository from "./src/repositories/textResponseRepository";
import SsmlResponseRepsitory from "./src/repositories/ssmlResponseRepository";
import ContextService from "./src/services/contextService";
import GoogleResponseBuilder from "./src/builders/googleResponseBuilder";
const container = new Container();
container.bind<IGoogleAssistantController>(TYPES.GoogleController).to(GoogleAssistantController);
container.bind<IResponseService>(TYPES.ResponseService).to(ResponseSerivce);
container.bind<IContextService>(TYPES.ContextService).to(ContextService);
container.bind<IResponseRepository>(TYPES.TextResponseRepository).to(TextResponseRepository);
container.bind<IResponseRepository>(TYPES.SsmlResponseRepository).to(SsmlResponseRepsitory);
container.bind<ILogger>(TYPES.WinstonLogger).to(WinstonLogger);
container.bind<IIntent>(TYPES.WelcomeIntent).to(WelcomeIntent);
container.bind<IIntent>(TYPES.DefaultFallbackIntent).to(DefaultFallbackIntent);
container.bind<IResponseBuilder>(TYPES.ResponseBuilder).to(GoogleResponseBuilder);
export { container };
Default fallback intent
/**
* Default fallback intent class
*/
#injectable()
export default class DefaultFallbackIntent extends IntentBase {
invoke(conv: DialogflowConversation): DialogflowConversation {
const response = this.responseService.getResponse("defaultFallback");
return conv.ask(response);
}
}
In order for container.get(<Type>) to work, <Type> must be bound to the container at some point. In your composition root (where you set up your container) you can create this binding:
const container = new Container();
container.bind<IIntent>(TYPES.DefaultFallbackIntent)).to(<TheDefaultFallbackIntentClass>);
EDIT:
From the discussion in the comments it seems that DefaultFallbackIntent inherting from IntentBase is the problem, because at the time DefaultFallbackIntent gets instantiated (through binding it), there doesn't exist such an instance in the container when the base constructor is executed.
A workaround would be to not inherit from IntentBase and just implement the interface and set the required fields in this class as well:
/**
* Default fallback intent class
*/
#injectable()
export default class DefaultFallbackIntent implements IIntent {
protected logger: ILogger;
private responseService: IResponseService;
private contextService: IContextService;
private fallbackIntent: IIntent;
private responseBuilder: IResponseBuilder;
invoke(conv: DialogflowConversation): DialogflowConversation {
const response = this.responseService.getResponse("defaultFallback");
return conv.ask(response);
}
}
However, a better solution would be two create another super class which contains all the required fields both the default fallback intent and others have in order to reduce duplicated code.
I'm learning Groovy and I've seen this example:
button = new JButton('Push me!')
button.actionPerformed = { event ->
println button.text
}
There is no actionPerformed field/method on JButton....
Could someone explain how Closure is being registered by Groovy on actionPerformed ?
TL;DR
JButton metaclass registers 31 listeners methods (one of them is actionPerformed) and whenever you call button.actionPerformed = { event -> } Groovy executes a method like setProperty(object, field, value) which checks if there is a listener registered with a given field name - if does, it executes registered listener method (javax.swing.AbstractButton.addActionListener(java.awt.event.ActionListener) in this case).
Detailed explanation
Groovy uses MOP (metaobject protocol) for a dynamic runtime environment. It means that Groovy does not call methods directly like in Java, but uses this additional layer instead. It allows changing class behavior at a runtime.
Whenever we try to set a class field/property value like
button.actionPerformed = { event -> println "Clicked!" }
Groovy calls proper setProperty method. In case of a setting a property for class like JButton, following setProperty method gets called:
https://github.com/apache/groovy/blob/GROOVY_2_4_X/src/main/groovy/lang/MetaClassImpl.java#L2602
/**
* <p>Retrieves a property on the given receiver for the specified arguments. The sender is the class that is requesting the property from the object.
* The MetaClass will attempt to establish the method to invoke based on the name and arguments provided.
*
* <p>The useSuper and fromInsideClass help the Groovy runtime perform optimisations on the call to go directly
* to the super class if necessary
*
* #param sender The java.lang.Class instance that is mutating the property
* #param object The Object which the property is being set on
* #param name The name of the property
* #param newValue The new value of the property to set
* #param useSuper Whether the call is to a super class property
* #param fromInsideClass Whether the call was invoked from the inside or the outside of the class.
*/
public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) {
checkInitalised();
//----------------------------------------------------------------------
// handling of static
//----------------------------------------------------------------------
boolean isStatic = theClass != Class.class && object instanceof Class;
if (isStatic && object != theClass) {
MetaClass mc = registry.getMetaClass((Class) object);
mc.getProperty(sender, object, name, useSuper, fromInsideClass);
return;
}
// .....
//----------------------------------------------------------------------
// listener method
//----------------------------------------------------------------------
boolean ambiguousListener = false;
if (method == null) {
method = listeners.get(name);
ambiguousListener = method == AMBIGUOUS_LISTENER_METHOD;
if (method != null &&
!ambiguousListener &&
newValue instanceof Closure) {
// let's create a dynamic proxy
Object proxy = Proxy.newProxyInstance(
theClass.getClassLoader(),
new Class[]{method.getParameterTypes()[0].getTheClass()},
new ConvertedClosure((Closure) newValue, name));
arguments = new Object[]{proxy};
newValue = proxy;
} else {
method = null;
}
}
// ......
}
It goes to the block responsible for checking listener methods. Swing related classes register their listener methods so you can add a listener method like:
button.actionPerformed = { event -> .... }
instead of
button.addActionListener(new ActionListener() {
#Override
void actionPerformed(ActionEvent actionEvent) {
}
})
And here is the list of all 31 registered listeners:
Keys are the names of listeners and values are method objects that receives a closure set to a property. Of course it finds a listener method for a key actionPerformed - it gets a reference to a method
public void javax.swing.AbstractButton.addActionListener(java.awt.event.ActionListener)
and it passes a closure
{ event ->
println button.text
}
to it.
When these listeners like actionPerformed get registered to a metaclass?
Metaclass object gets initialized whenever you call a class constructor. Groovy in this case calls
org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(Object receiver, Object arg1, Object arg2)
https://github.com/apache/groovy/blob/GROOVY_2_4_X/src/main/org/codehaus/groovy/runtime/callsite/AbstractCallSite.java#L245
If you follow call stack you will find these two major checkpoints:
at some point dynamic call constructor method reaches CallSiteArray.createCallConstructorSite() method that creates a metaclass object https://github.com/apache/groovy/blob/GROOVY_2_4_X/src/main/org/codehaus/groovy/runtime/callsite/CallSiteArray.java#L86
MetaClassImpl.initialize() method calls addProperties() which sets up metaclass with e.g. listeners https://github.com/apache/groovy/blob/GROOVY_2_4_X/src/main/groovy/lang/MetaClassImpl.java#L3303
Inside MetaClassImpl.addProperties() Groovy lists all listener methods using BeanInfo class and registers all found listeners https://github.com/apache/groovy/blob/GROOVY_2_4_X/src/main/groovy/lang/MetaClassImpl.java#L3343
The full call stack to this MetaClassImpl.addProperties() method from IntelliJ IDEA debugger window looks like this:
You can set a breakpoint at any of these lines if you would like to dig even deeper. Hope it helps.
Using Symfony2 / doctrine2, while we use the find() function to get a specific object based on the entity selected if there are relations (like OneToMany), Doctrine return all other object.
For example :
$em = $this->get(
'doctrine.orm.entity_manager',
$request->getSession()->get('entity_manager')
);
$product = $em->getRepository('MyBundle:Product')->find($id);
The result on $product will be the Product object + other linked objects like (Store, Category, ...etc.)
How can we control doctrine to determinate which object we need to be returned.
I can use Querybuilder, but i am looking if there are any function all determinate.
Doctrine return all other object
This is not how it works, at least by default.
Doctrine uses what is called lazy loading.
From the official documentation, you have the following example:
<?php
/** #Entity */
class Article
{
/** #Id #Column(type="integer") #GeneratedValue */
private $id;
/** #Column(type="string") */
private $headline;
/** #ManyToOne(targetEntity="User") */
private $author;
/** #OneToMany(targetEntity="Comment", mappedBy="article") */
private $comments;
public function __construct {
$this->comments = new ArrayCollection();
}
public function getAuthor() { return $this->author; }
public function getComments() { return $this->comments; }
}
$article = $em->find('Article', 1);
And the following explanation:
Instead of passing you back a real Author instance and a collection of
comments Doctrine will create proxy instances for you. Only if you
access these proxies for the first time they will go through the
EntityManager and load their state from the database.
Reference: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entity-object-graph-traversal
More information about the topic: http://www.doctrine-project.org/blog/doctrine-lazy-loading.html
You can configure extra lazy associations to avoid loading of relations in general.
/**
* #ManyToMany(targetEntity="CmsUser", mappedBy="groups", fetch="EXTRA_LAZY")
*/
protected $property;
I've a base presenter class:
public abstract class PresenterBase<T> where T : IView
{
//Some code
}
A concrete presenter class that implements this base:
public class RegistrationPresenter : PresenterBase<IRegistration>
{
//Some Code
}
A concrete presenter factory to return the instance of presenter which depends on a specific interface contract:
public class ProductPresenterFactory : PresenterFactoryBase
{
// Some code
public override PresenterBase<IView> GetPresenter(IView view, string name = "")
{
if (view == null && string.IsNullOrEmpty(name))
throw new ArgumentNullException();
return presenter;
}
}
I need to implement the GetPresenter method. The user will put the interface contract, for example of type IRegistration in the above case. This method should figure out the class that implements PresenterBase<IRegistration> and return an instance.
I did not write this with a compiler; I might have made a few mistakes.
You'll first need to get the type of the presenterbase, then we'll scour the assemble for the implementation, then call it's constructor. I'll make some assumptions as written in the code.
var genericType = typeof (PresenterBase<>).MakeGenericType(new[] { view.GetType() });
var allTypes = GetType().Assembly.GetTypes(); // I assume the class is in the same assembly.
var typeToImplement = allTypes.Single(t => t.IsSubclassOf(genericType)); // I assume there is only one implementation for the given type
var constructorToCall = typeToImplement.GetConstructors().First(); // I assume there is one constructor
var presenter = constructorToCall.Invoke(new object[0]); // I assume there is no parameter